About Me

Having 12 years experience in Microsoft technologies.Since more than 7 years working in SharePoint technologies. Expert in providing consultation for SharePoint projects. Hands on with development and administration.

Tuesday, 18 October 2011

SharePoint 2010 Dev-Debugging Tips & Tricks

Critical Tasks
SharePoint developers face many challenging tasks. With the appearance of Visual Studio 2010 and
SharePoint 2010, some things are easier. The integration is improved and the support for server- and
client-side programming is much better than it was in previous editions. With the new possibilities,
however, a new level of application programming arises, and things become more challenging again.
These challenges include
• How to distribute the results—creating and installing packages
• How to debug client-side code, especially Ajax behavior
• How to handle code issues on the server
• How to deal with issues that only arise on the production system (where there is no debugger)
If you develop on a team—and we assume that you do—things are even more complicated. You
have to synchronize your work with others, take over their code, or provide yours to others. You must
deal with configuration settings, farm maintenance, and the data stored in the shared database.
Debugging the Server
Having Visual Studio 2010 properly installed might look like the perfect environment to debug the code.
We assume that you’re already familiar with your IDE. In the section “Introducing Visual Studio 2010’s
SharePoint Support” is a brief introduction to the basic features concerning SharePoint.
A web application consists of several parts. IIS plays a significant role—each request and response
passes through IIS. Debugging the server includes a way to debug IIS to see what data is transmitted
from the browser to the server and back. Despite debugging, performance issues often arise. To test your
SharePoint application under load, a stress test tool is essential.
If your SharePoint server does not respond as expected and the debugger does not reveal useful
results—probably because an internal module beyond your access scope fails—you need more tools.
SharePoint hides error message and replaces stack traces, exception messages, and logs with almost
useless information. It’s primarily designed for end users, and they might get frightened when a
NullReferenceException is displayed (e.g., “Did I lose all my data now?”). In your development
environment, you can turn on developer-friendly (and therefore user-unfriendly) error messages by
setting the appropriate parameters in the web.config file:
<SafeMode CallStack="true" ... />
<customErrors mode="off" />
However, not all errors throw exceptions, and not all such messages are helpful. You need a plan for
how to find the source of the trouble:
1. Look into the event log for SharePoint.
2. Look into the SharePoint logs.
3. Attach a debugger to the working process and watch for exceptions.
4. Look into the IIS logs.
5. Add tracing to your code and watch the traces.
6. Consider remote debugging if the target machine has no debugger installed.
Let’s consider each of these alternatives in more detail.
Looking into the Event Log for SharePoint
The event log contains a special section for SharePoint, and the application event log
can also contain some relevant information. It is even worth looking for events sent here from IIS. If the
SharePoint application causes the worker process to die ungracefully, it can help to know when and why.
Looking into the SharePoint and IIS Logs
SharePoint itself writes a lot of data into the logs if it is enabled in Central Administration. During the
development and test cycle, we strongly recommend activating the logs. You can find the logging files in
<%CommonProgramFiles%>\Microsoft Shared\Web Server Extensions\14\LOGS
The IIS logs are found here:
The IIS logs contain information about each request and the response. If you match certain
reactions of SharePoint with the event of a specific request, there is a good chance of finding the reason
for some unexpected behavior.
If you suspect that your code is causing the misbehavior and the debugger disturbs the data flow, a
private trace is a good option. Just write useful information from your code to a trace provider. You can
turn tracing on and off by setting the appropriate options in the application’s web.config file:
<trace enabled="true" requestLimit="40" localOnly="false"/>
The tracing framework is highly extensible and you can write the data to text files, the event log, or
databases, or as XML. You can start here to learn more about tracing using the .NET Framework:
Using Common Debugging Techniques
In addition to these specific techniques, you should consider using advanced .NET debugging methods
such as the following:
• Attaching a debugger to the working process and watching for exceptions
• Considering remote debugging if the target machine has no debugger installed
• Adding tracing to your code and watching the traces
These methods are not SharePoint-specific, but are nonetheless quite helpful.
The Developer Dashboard
Several tools are quite powerful, though not always appropriate on a production machine. The
Developer Dashboard built into SharePoint 2010 provides at least basic information about internal
Activating the Developer Dashboard Using stsadm
By default the Developer Dashboard is switched off. To activate it on your machine, you can run a stsadm
stsadm –o setproperty –pn developer-dashboard –pv ondemand
The command switch -pv accepts the following settings:
• on: Activate the Developer Dashboard (always appears at the end of a page)
• off: Deactivate
• ondemand: Activate on Demand
The ondemand option is usually the best choice, as it allows you to show or hide the information
using the dashboard icon in the upper-right corner

The on option is helpful if the layout of a page is destroyed or you can’t reach the Dashboard icon for
some reason.
Activating the Developer Dashboard Using PowerShell
To activate the Developer Dashboard via PowerShell, use a script such as this:
Write-Host("Current Level: " + $contentSvc.DeveloperDashboardSettings.DisplayLevel)
The supported properties for the $level variable are the same as those for stsadm:
• "On": Activate the Developer Dashboard (always appears at the end of a page)
• "Off": Deactivate
• "OnDemand": Activate on Demand
This code is good for running in a batch file using a parameter. To copy a command-line parameter
to the variable, use something like this:
There is neither error handling nor user help in this batch file. Consider adding such lines to turn
this sample batch file into production-quality code.
Activating the Developer Dashboard Using Code
You’re probably going to write some clever tools for SharePoint. Using code to activate the dashboard
may help others to investigate what they are doing. A simple piece of code does the trick:
SPWebService svc = SPWebService.ContentService;
svc.DeveloperDashboardSettings.DisplayLevel = SPDeveloperDashboardLevel.OnDemand;
Note that the usage of the SPFarm object, which is shown in several blogs regarding earlier versions
of SharePoint 2010, is no longer supported in the final SharePoint product.
Working with the Developer Dashboard
This tool will give you the following:
• A breakdown of the request/response cycle with timings for each operation
• A breakdown of the response times for each database query that the rendering
process triggers
• A breakdown of the load times for each Web Part on the page

To access the dashboard, click the icon in upper-right corner to the left of the help button question
mark. The dashboard analyses the current page only. The underlying ASP.NET engine has a lot more
information beyond what the dashboard shows. It is written to the file Trace.axd, and can be displayed
by clicking the small link at the end of the dashboard screen showing “Show or hide additional tracing

The ASP.NET trace shows virtually everything available from the current request/response cycle,
such as headers, cookies, and form data. This includes internal traces, stack traces, and names of stored
procedures and the time that they appeared. That makes the dashboard not only a perfect tool to find
errors, but even more helpful to find performance flaws. The complete control tree is exposed and
makes it possible to find the reason an element is not where you expect it or why it is missing altogether.
Making Your Code Dashboard-Aware
The dashboard displays any useful information that’s available from the runtime environment.
However, the reason for a malfunction, bad performance, or unexpected behavior could be in your code.
It’s good practice, in addition to using debugging tools, to add diagnostic output to your code that
generates content to the dashboard.
You can use the SPMonitoredScope class to create a section that is logged and explicitly exposed to
the dashboard’s output.
Let’s assume you create a visual Web Part and you want to know what happens inside the Load
event, when is it called, and how much time a specific operation consumes. The following code explains
how to use the SPMonitoredScope class:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
namespace VisualWebPartDashboard.VisualWebPart1

public partial class VisualWebPart1UserControl : UserControl
protected void Page_Load(object sender, EventArgs e)
using (SPMonitoredScope scope =
new SPMonitoredScope(this.GetType().Name))
Button b = new Button();
b.Text = "Click me!";
using (SPMonitoredScope scopeInner =
new SPMonitoredScope("Inner Scope"))
System.Threading.Thread.Sleep(500); // lengthy operation
In this code, the SPMonitoredScope class exposes two lines to the dashboard output. The first uses
the current internal name of the control, while the second uses a constant string. The inner operation is
delayed to show the effect of the timer.
The advantage of this method is that the output appears within the context of the execution tree,
and you see not only your information, but also when your code is executed.

Debugging the Client
On the client, the same effort has to be made to ensure that it’s working correctly. The situation here is
more complicated because several different browsers need to be supported. The developers of
SharePoint 2010 did well to support all common browsers, such as Internet Explorer 7 and newer
versions of Safari, Opera, and Firefox.
The application pages or Web Parts you create will programmatically send HTML, styles, and other
content straight to the browser. You have to ensure that it runs without errors in the designated
environment. Because SharePoint relies heavily on Ajax (asynchronous JavaScript and XML) and your
customers invariably demand it, you may decide to use Ajax, too. Asynchronous calls from the browser
to the server, while the page is visible, complicate things even further.
Using Fiddler to Understand What’s Going on the Wire
Sniffing the protocol activity on the connection with SharePoint requires a tool like Fiddler. It shows the data flow, headers, cookies, and raw data sent down to the server and back to the browser. Fiddler is a web-debugging proxy that sits between the browser and the network socket. It logs all incoming HTTP (and HTTPS) traffic. You can inspect the headers received and sent, investigate the raw data, and edit data to test your server. Fiddler itself is independent of a specific browser and works well with Internet Explorer, Firefox, Opera, and others. For advanced scenarios, Fiddler can be extended using .NET-based plug-ins to automate traffic analysis. There are several add-ons available.

SharePoint makes heavy use of Ajax. Such calls to the server (called postbacks) run in the
background. Fiddler is able to sniff this traffic and show what—if anything—happens.
To start Fiddler, you can use the icon that appears in the toolbar of Internet Explorer ( ). It runs
as a separate application, so you can start it from the Start menu and use it with any other browser. After
you start Fiddler, the program registers itself as a proxy for Internet Services (WinInet), the HTTP layer
built into Windows. The proxy settings of the WinInet configuration dialog should express this, as shown

When you close Fiddler, it unregisters itself automatically and restores previous settings.
Fiddler supports breakpoints. Because there is now code, breakpoints are based on conditions. If an
incoming response or outgoing request matches your criteria, Fiddler will pause, allowing you to
investigate the data further.
Fiddler has one serious limitation when sniffing local traffic—a common situation when debugging
SharePoint. IE and the .NET Framework are hard-coded to not send requests for localhost through any
proxies, and as a proxy, Fiddler will not receive such traffic. The workaround is to use your machine
name as the hostname instead of localhost or So, for instance, rather than navigating to
http://localhost/Default.aspx, instead visit http://machinename/Default.aspx.
The latest version of Fiddler also supports some other monikers such as http://ipv4.fiddler to
reach localhost on the IPv4 adapter, or http://ipv6.fiddler to access localhost on the IPv6 adapter. This
works especially well with the Visual Studio 2010 internal web server, which is internally using the IPv4
loopback adapter.

Using Developer Tools to Investigate What’s Running in the Browser
Eventually the page is rendered in the browser. If the rendered page does not display correctly, you
will need to check the HTML, styles, and resources. The Internet Explorer Developer Toolbar will unlock
those and more. You can download a free copy from
Using this add-on you can
• Explore and modify the Document Object Model (DOM) of a web page.
• Locate and select specific elements on a web page through a variety of techniques.
• Selectively disable Internet Explorer settings.
• View HTML object class names, IDs, and details such as link paths, tab index
values, and access keys.
• Outline tables, table cells, images, and selected tags.
• Validate HTML, CSS, WAI, and RSS web feed links.
• Display image dimensions, file sizes, path information, and alternate (alt) text.
• Immediately resize the browser window to a new resolution.
• Selectively clear the browser cache and saved cookies. You can choose from all
objects or those associated with a given domain.
• Display a fully featured design ruler to help accurately align and measure objects
on your pages.
• Find the style rules used to set specific style values on an element.
• View the formatted and syntax-colored source of HTML and CSS.
To get started with this tool, press F12 when working within Internet Explorer. You will see several
tabs that give access to parts of the loaded data (e.g., HTML, CSS, and scripts).
Introducing Visual Studio 2010’s SharePoint Support.
Visual Studio 2010
If you already have experience with SharePoint 2007 and Visual Studio 2008, this may seem like a long list of obvious extensions. In essence, they will make third-party tools obsolete.
Preparing Visual Studio
If you use the SharePoint templates and create solutions or features for deploying, everything works
well. However, if you start creating regular ASP.NET web applications that simply reference SharePoint
and run standalone, the internal debugger and web server will fail. There are some requirements that
you can easily fulfill using IIS. For details, refer to the “Handling 64-Bit Quirks”. For Visual Studio 2010 it turns out that it’s not trivial. One solution is to replace the internal web server with IIS, even for debugging purposes. To accomplish this, you have to set a few settings in your project. First, a web site is required. To create one, use IIS Manager. Follow the steps described in the
“Configuring IIS to Run with the Right Account” section to set the correct application pool settings. Then
configure your project as follows:
1. Open the Properties page of your web application project.
2. Change to the Web tab.
3. Select “Use Local IIS Web server” and enter the URL of the root web site—
Localhost:81, Use any port number that is not in
use on your system. It must be configured in IIS as well.
4. You can now create a new virtual directory if several projects run under the
same web. Enter the name of your project. If the root web points to the path
above the project, the current project’s leaf folder is converted into a virtual

You can now start debugging against IIS without worrying about the limitations of the internal web
The SharePoint Development Templates
Visual Studio 2010 comes with a set of templates ready to create SharePoint features.
Visual Studio supports SharePoint 2010 completely and SharePoint 2007 for workflow projects only. When you create a new project, you can find the appropriate path under the language selection. SharePoint templates are available for both VB .NET and C#. You can also choose to program against any of the supported .NET Frameworks: 2.0, 3.0, 3.5, or 4.0.
Each of these projects allows the addition of several items. Some of the templates are just an empty
solution with at least one item predefined.
After choosing the most suitable template, a wizard appears. You can now choose against which site
the project is to be deployed for debugging purposes. Visual Studio takes care to deploy
the required files and register the assembly in the Global Assembly Cache (GAC).

The remaining tasks of the wizard depend on the item selected. Clicking Finish will create the
project skeleton. As an example let’s investigate a new list definition and its various settings. First, check
the settings of the project by pressing F4 to open the properties pane

You can change the site and the assembly deployment target. If the project consists of only ASPX
files or resources, you may deploy directly against the web application. If it is an assembly, it must be
deployed into the GAC.
Investigating a Package
The package contains several folders, even if it is something like a simple list definition. This structure
represents a part of SharePoint’s 14 hive—the SharePoint root. An item defined in the project is usually
not able to act standalone. To deploy, it must be part of a feature or solution package. Hence, the project
must meet specific requirements, and the templates take care of this. At least two items are required:
• Features
• Package
Under the Features folder, you’ll find a feature definition as a configuration file. Each feature has a
specific name. Just select the predefined name (Feature1) and rename it to whatever you choose. The
files under the folder are then automatically renamed. A feature consists of at least an XML file. You
could immediately start typing XML to create the feature. However, in a world of designers and graphical
user interfaces (GUIs), you can also launch the Feature Designer.
The Feature Designer
The Feature Designer is primarily a collection of files comprising the solution. You can
decide which files are parts of the feature.

The list definition template contains the support files for a list template and a list instance.
Building and Deploying
There are several options for building a package and deploying it to the connected server. Deploying
directly to the server allows a fast check of your work and provides immediate debugging capabilities.
The build step performs two tasks:
1. Building the solution and creating the assembly
2. Packing and creating the WSP package
The deploy step includes the build step and performs several more tasks:
1. Checking the WSP package
2. Recycling the application pool
3. Retracting a previously installed version
4. Deploying the current solution as a new version
5. Activating the features in the package
There is also a retract option to remove the current solution from SharePoint. Furthermore, the package option isolates the packaging step from the build step to refine the process in case you’re hunting a difficult bug.
SharePoint as a Development Toolkit and Framework
The .NET Framework, Visual Studio, and the Windows SDKs provide everything you need to get and
build what you want. However, there are a lot repetitive tasks for every application. You need a UI for
administrative purposes, pages to log users on and off, the ability to handle identities, and so on. With
SharePoint, you get many of these features, providing more than 80 percent of a typical web application
out of the box. That includes but is not limited to the administration functions, a set of powerful
components, logging and maintenance capabilities, reporting and connectivity, and workflow and
search engine support.
Even if you only need a few parts, the built-in functionality saves considerable time because you
gain more than features. You get ready-to-use components that don’t need any further testing or
Command-Line Tools
SharePoint comes with several command-line tools to support administration and automation tasks.
Some of the tools particularly aid developers.
This tool configures a fresh SharePoint installation or repairs a damaged one. It’s the same as the
graphical SharePoint Products and Technologies Configuration Wizard, but the console mode allows it
to be executed in batch files for automation purposes.
The most important tool is stsadm.exe. Almost all administrative tasks can be performed using this
command-line program. Developers can extend it by adding private commands. It gives your
administrators more power without introducing more tools. stsadm was the only automation tool for
SharePoint 2007. With SharePoint 2010, Microsoft made a major shift to supporting PowerShell.
PowerShell uses so-called cmdlets (pronounced commandlets).
It’s important to note that stsadm supports several operations that have no equivalent in the Central
Administration or Site Administration UI. That means that unless you program against the API, there is
no alternative way to perform certain tasks without using stsadm (or its successors, PowerShell’s
SharePoint cmdlets). However, using PowerShell is the preferred way, because Microsoft is going to
move all administration tools to cmdlets. Sooner or later, Microsoft is going to drop the antiquated batch
support, whether you like it or not.
Using SPMetal you can create a proxy class from existing lists and libraries to enable access using LINQ
to SharePoint. The tool runs at the command line and can be invoked as a prebuild command within
Visual Studio to create base classes for a type-safe data access layer.
Graphical Tools
Some graphical tools accompany the installation and support administrators and developers installing
and configuring SharePoint properly.
This is the common SharePoint Products and Technologies Configuration Wizard that is available after
installation and from the Start menu. It supports basic configuration of a fresh installation or repair of an
installation that doesn’t work.
Handling 64-Bit Quirks
SharePoint 2010 runs on 64-bit hardware only. For you as a developer, this means that you have to create
and build against the 64-bit version of the .NET Framework running on x64 processor architecture. Even
with Visual Studio 2010 installed on the same machine, some settings need to be changed to support the
right architecture.
For projects running inside the context of SharePoint, the templates ensure correct functionality.
However, if you plan to develop administrative support tools, such as console applications or even a web
site running in IIS and dedicated to helping administrators running advanced tasks, things are rather
Programming SharePoint Using a Console Application
For a console application, you merely set the processor architecture to 64 bit. Proceed with the steps
shown in the following exercise.Making a Console Application 64-Bit Ready
1. Create a new application using the Console Application project template.
2. Select .NET Framework 3.5 as the target framework.
3. Open the Properties pane from the project’s context menu.
4. Click the Build tab.
5. Click the “Platform target” drop-down and select x64 . If this entry isn’t available, you must create the target:

Open the Configuration Manager via the Build 􀀂 Configuration Manager menu entry.
b. For your project, select <New...> in the Platform column.
c. In the next dialog, select x64 for “New platform” and x86 in the “Copy settings from” drop-down.
d. Click OK.
6. Build your project.

Programming SharePoint Using ASP.NET
To create web applications, you don’t have to run inside SharePoint. For administrative tasks in
particular, it’s recommended to use separate applications. While console programs are fine for scripting
automated tasks, a web application provides an advanced UI, including help and support information
Administrators lacking skills on the platform and users who help manage the servers may struggle with
command-line tools. Therefore, creating administration web applications is common.
However, for ASP.NET, the same restrictions apply as for console applications. They must be
configured to run on 64 bit. In addition, the application must run under the same account you would
use to administer your SharePoint central administrations.
Preparing ASP.NET for the x64 Platform
To prepare ASP.NET for the x64 platform, you need to configure the application pool of your web site.
The following exercise shows you how to set the appropriate property, enable32BitAppOnWin64, to false.
Configuring ASP.NET Applications to Run 64-Bit Code
1.Open IIS Manager.
2. Ensure that your ASP.NET application has a dedicated application pool. If not, create one and assign
it to your web site.
3. Select the application pool from the Application Pools view and click Advanced Settings... on the
Actions pane.
4. Search for the Enable 32-Bit Applications entry.
5. Select False from the drop-down as shown
6. Close by clicking OK

USE IIS Console or Scripting?
There are several blogs and a Knowledge Base entry regarding this issue that recommend using a script
provided by IIS to change the settings via this command:
Cscript C:\inetpub\AdminScripts\adsutil.vbs set w3svc/AppPools/Enable32BitAppOnWin64 0
This script results in exactly the same setting change described previously, and simply changes an entry in
the IIS settings. We recommend using the IIS management console method.
Configuring IIS to Run with the Right Account
For an ASP.NET application, two settings are required. First, you must set the application pool to
run under the administrative account. The following exercise shows you how to configure it.
Running the Application Pool in the Appropriate Account
1. Open IIS Manager.
2. Ensure that your ASP.NET application has a dedicated application pool. If not, create one and assign
it to your web site.
3. Select the application pool from the Application Pools view and click Advanced Settings... in the
Actions pane.
4. Search for Identity in the Process Model group entry and click the ellipses (the default account is
5. In the next dialog, select “Custom account” and click Set...
6. In the next dialog, enter the account you want to use, such as “Administrator,” and enter the password

Next you must ensure that the user you use is able to log onto your web site. You can either edit your
web.config file or use the IIS Manager management console. In the web.config file, the following settings
<authentication mode="Windows" />
<deny users="?" />
This code sets ASP.NET to authenticate using Windows authentication. The <authorization> tag
prevents anonymous users from accessing the pages. Setting Windows authentication mode via the IIS
management console requires the steps shown in the following exercise.

Forcing Authentication for an ASP.NET Application
1. Open the web site’s Features view.
2. Click the Authentication icon.
3. From the list of available authentication modes, select Windows Authentication.
4. Click Enable in the Actions pane.
The settings apply immediately.
For the authorization part, a similar set of settings are required.
Setting Authorization for an ASP.NET Application
1.Open the web site’s Features view.
2. Click the Authorization icon.
3. Click the Add Deny Rule... action.
4. In the next dialog, select “Specified users” and enter a question mark (?) here.
5. Close by clicking OK.
The settings change the corresponding web.config setting and take effect immediately.
Once everything is done, you can deploy and run your application.

No comments:

Post a Comment