Improve you SharePoint code with Red Gate ANTS

As development practices around the SharePoint platform mature the demands for better quality and better performing solutions are being made.  Gone are the days when Enterprises will accept that the Roll-Up Web Part they purchased will not scale beyond a few site collections.  A knowledge of the platform and defensive coding alone will not cut the mustard, the need for a holistic approach to your development practices will be the only way to achieve success.  In this blog post I am focusing on one specific technique, code profiling, and using the excellent Red Gate ANTS Profiler.

Disclaimer:  Red Gate ANTS Profiler is a paid for application.  There are other products on the market that do code profiling including Visual Studio.  The reason for using ANTS in this post is due to the ease with which you can get up an running and the quality of the user experience.  I recommend you set aside a day to look at the profiling in Visual Studio and then a few hours to get that much further with ANTS.

Software Performance Analysis – Wikipedia

In software engineering, performance analysis, more commonly today known as profiling, is the investigation of a program’s behavior using information gathered as the program executes (i.e. it is a form of dynamic program analysis, as opposed to static code analysis). The usual goal of performance analysis is to determine which sections of a program to optimize – usually either to increase its speed or decrease its memory requirement (or sometimes both).

As the quote says this technique is specifically aimed at the optimization of code; the tools enable the developer to quickly target the areas of code that need optimization and lead to an improved return for the effort. (seems strange saying ROI when talking about dev techniques, but this is really what it is).

Getting started

Red Gate provide a 14 day trial, so you can try before you buy.  The latest release, version 4.3 as at the time of writing, has made some great improvements over the 4.1 version – most notably the removal of the need to stop all the IIS web sites listening on port 80 :).

As you would expect this post will focus on profiling SharePoint code, I’m going to use the Magic 8 ball application developed for my TDD session at the Best Practices SharePoint Conference in San Diego.

More details on Test Driven SharePoint development can be in the Agile section of this site.

Environment

The environment that I will do the testing is a typical SharePoint developers Virtual Machine.

  1. Windows 2008 Server (32bit)
  2. Visual Studio 2008
  3. Microsoft Office SharePoint Server 2007
  4. SQL Server 2005

As this is running on Windows 2008 I will be testing against IIS7.   The requirements are identical for Windows 2003 and IIS 6.0

Installation

Download ANTS Profiler and install, not too many options to worry about here.

image

Luckily for my first run through the team have provided a technical paper on installing, using and getting ANTS Profiler to work with SharePoint, How to profile a SharePoint 2007 Site Collection.  There were a few things in here that I prefer not to do,  I will document what I do below and will pass this back – I’m not criticizing, there’s no way I would even attempt to write a Profiler so mucho respect from me to the Red Gate team

Configuration

We are looking for the ability to profile any site collection within a Web Application.  This involves getting the account used for the associated application pool, giving it some additional rights and then configuring the ANTS services to use this account.

Web Application

Depending on your development machine configuration you will have a number of web applications configured in SharePoint, the configuration below should be reasonably familiar to most of you.

image

The key here is to identify the web application (IIS Website) as we need to get the account name from the associated Application Pool.

Load IIS Manager, select the web application and chose Basic Settings from the Actions menu on the right.  This will show the associated application pool as below.

image

Select the Application Pools from the connections menu, choose the application pool identified in the previous step and click advanced settings.  This will give you a properties screen showing the account we need to work with.

image

In this case 21apps\svc-intranet-ap – if you have a local installation this may be set to Local System in which case the steps below may not be required.   I recommend that dev’s don’t have a default install as you really need to understand how SharePoint is setup to undertake any large scale developments.

Web.Config

In IIS 6 days you would need to edit the web.config file to set the application into debug mode.   In IIS 7 the common ASP.NET configuration options have been promoted to the IIS console.  With the web application still selected click on the .NET Compilation option and change the Debug behaviour to True and click Apply.

image

Like all good SharePoint developers you will be working with WSS_Minimal trust settings or a custom policy file.  To do profiling however you will need to set the Trust level to Full.  Again IIS 7 provides a UI or you can edit it manually.

image

It is possible to run the code without setting a Full trust level, but you need to remove the .pdb files and will lose the ability to profile the lines of code.  Which is sort of the point of profiling!  If you don’t set Full trust you will get an error like the one below when loading a web part

Web Part Error: An error has occurred.

Show Error Details
Hide Error Details 

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
  at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
  at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
  at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
  at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly)
  at System.Activator.CreateInstance(Type type, Boolean nonPublic)
  at System.Activator.CreateInstance(Type type)
  at Microsoft.SharePoint.WebPartPages.SPWebPartSerializer.get_DefaultControl()
  at Microsoft.SharePoint.WebPartPages.BinaryWebPartSerializer.SerializedWebPart..ctor(SPWebPartManager webPartManager, XmlNamespaceManager xmlnsManager, Byte[] sharedData, Byte[] userData, String[] links, Type type, SPWeb spWeb)
  at Microsoft.SharePoint.WebPartPages.BinaryWebPartSerializer.Deserialize(SPWebPartManager webPartManager, XmlNamespaceManager xmlnsManager, Byte[] userData, Byte[] sharedData, String[] links, Type type, SPWeb spWeb)
  at Microsoft.SharePoint.WebPartPages.SPWebPartManager.CreateWebPartsFromRowSetData(Boolean onlyInitializeClosedWebParts)

[VerificationException: Operation could destabilize the runtime.]

Services

ANTS runs as two services

  1. ANTS Memory Profiler 4 Service
  2. ANTS Performance Profiler 4 Service

Change the accounts on these two services to the same accounts used in the web application we identified above.

If this is the first time the account has been associated with a service it will be automatically granted the ‘Log On As A Service’ right.

image

Local Security Policy

From the Administrators menu choose Local Security Policy and grant the application pool account the following rights

  1. Act as Part of the Operating System
  2. Impersonate Client after authentication

image

Open a command prompt and run gpupdate /force.

image

Profiling your code

Your environment is now configured, we can start profiling.  As this is SharePoint I tend to just hit the bit i’m planning to profile first to make sure this is working before I start profiling.  Many hours can be lost trying to solve a configuration issue with a profiler that is not at fault.

Start Red Gate ANTS Performance Profiler.  It knows we’re running on a system a system that has UAC, it offers to make our life easy and always run as an Administrator.  I normally click yes here.

image

ANTS loads the Profile Settings window is automatically.

There are only a few things to set.

  1. Choose the ASP.Net web application (hosted in IIS)
  2. The URL to the SharePoint site
  3. Use the original port

image

Further profiling counters can be set, but we just want to get our first run going for now.  Click on Start Profiling.  (In this example I have added a long running process to show how ANTS can identify this as a hotspot).

Profile Results

Profiling will start and a new browser will open at the location specified.  As this is SharePoint the profiler restarts the service so you will always have a small delay while SharePoint is JIT compiled. The profile timeline will show this impact on the processor.

image

Once the processor has levelled out its time to start profiling your code.   Navigate and interact with the bit of the application you are interested in.  If it is a  web part or navigation load you are interested in then you can refresh the page.

Once you are happy you have performed enough tasks,  I recommend keeping these focused, stop the profiling. ANTS will present you with the HOT code, the bit of code that is the worst performing. You can focus the analysis on any part of the profile graph to show poor performing code around a specific spike in the processor or memory.

image

In the example above I am focused on the code that runs (including my long running process) when I ask the magic 8 ball a question.

Viewing source code when you have enabled Line level profiling shows every line, the hit count and the % of time taken to perform that operation.

image

The really cool thing is you can click through the methods to follow the slow running process through the code!

image

Showing the method grid allows you to open up a call graph for any method to see how the processing is broken down in a dynamic tree view.  This really is just brilliant!  The image below does not do it justice you really do need to see this for yourself to appreciate it.

image

Conclusion

The long running process I added for the demonstration was picked up and allowed me to drill down into the lines of code that were the slowest.  It even showed how the internal calls within the base classes performed.

Red Gate ANTS Profiler is easy to setup and proves to be an invaluable tool in your software development tool kit.  I suspect profiling will not be something that you do every day, however with the speed and ease of use I would like to think that you will consider the inclusion of profiling a must have rather than a nice to have.

This entry was posted in Agile, Development, SharePoint and tagged , , . Bookmark the permalink.
  • http://wss.made4the.net Jeremy Thake

    Great post Andrew, always wanted to get some time to have a look at this. You’ve made my life a lot easier by documenting the steps mate! Great work!
    Be interested to throw some SPQuery vs enumerating list collections at it to to see how that reports it.

  • http://www.21apps.com Andrew Woodward

    Jeremy,

    Yes that is one of the things I was going to look at as examples of where the profiling can help improve performance. That and the 2000 items in a list magic number.

  • http://community.zevenseas.com/blogs/daniel Daniel McPherson

    Thanks Andrew, this is some really important tooling and you have also saved me a stack of time.

    My experience with SharePoint tells me that the performance bottlenecks are not always in the place that intuition tells you it is. Being able to be objective about it is really important.

    Finally, as you guys pointed out, be really great to see the effects of increasing data volumes on performance.

    Thanks again,
    Daniel

  • AndrewWoody

    Testing Disqus comments

  • Ian Campbell

    We've also used JetBrains Profiler, from the same makers as reshaper
    http://www.jetbrains.com/profiler/
    This was a lot easier to setup and use with SharePoint tahn ANTS

  • http://www.21apps.com AndrewWoody

    Ian,
    Do you have any blog posts showing how this is a lot easier to setup and use. I would be interested in a comparison between the tools.

    Andrew

  • http://atcrawford.com/ atcrawford

    Just in case anyone is still interested in this, here’s a similar scenario… In one of my client’s (particularly large) deployments, I got a 300ms improvement with essentially a one line code change, just changing this:
    var myList = someWeb.Lists["ListName"];
    to this:
    var myList = someWeb.GetList(“/serverRelative/ListUrl”);

    Would have never caught this without ANTS!

  • s_stewarta

    7lE – Lately I was down on cash and debts were killing me from all sides!! that was RIGHT UNTIL I learned to generate money on the internet! I landed on surveymoneymaker d.o.t net, and started doing surveys for straight cash, and YES, I have been great amounts more able to do my things!! i am very glad, that i did this!!! – qrr3