Tuesday, May 29, 2012

SPMonitoredScope in SharePoint 2010

Before reading this article, it is better to have some knowledge on Developer Dashboard which is a very useful feature for SharePoint Developers. By using Developer Dashboard you will able to see performance of SharePoint 2010 page. It will show details about execution time and some valuable information.

But suppose you have written a piece of code and you want to see the execution time for the custom code section, then SPMonitoredScope class will help us. If we will use this class then we will able to see the execution time in the Developer dashboard.
Here below is a code sample that you can follow to use SPMonitoredScope class. In the below code I am adding an item to my SharePoint list and I want to see how much time SharePoint will take. I have used the TryGetList() method which is a very useful method in SharePoint 2010.

 SPMonitoredScope monitoredScope = new SPMonitoredScope("Testing Performace for Adding List Item");
            {
                SPWeb myTopWeb = SPContext.Current.Site.RootWeb;
                {
                    SPList list = myTopWeb.Lists.TryGetList("MyCustomList");
                    if (list != null)
                    {
                        SPListItem listItem = list.Items.Add();
                        listItem["Title"] = "Test Item 1";
                        listItem.Update();
                    }
                }
            }

Also If you want to use SPMonitoredScope inside this function nestedly then you can use like below:
SPMonitoredScope monitoredScope = new SPMonitoredScope("Testing Performace for Adding List Item");
            {
                SPWeb myTopWeb = SPContext.Current.Site.RootWeb;
                {
SPMonitoredScope monitoredScope = new SPMonitoredScope("Testing Performace for Getting List Item");
            {
                    SPList list = myTopWeb.Lists.TryGetList("MyCustomList");
 }

                    if (list != null)
                    {
                        SPListItem listItem = list.Items.Add();
                        listItem["Title"] = "Test Item 1";
                        listItem.Update();
                    }
                }
            }

Now if you will open the Developer dashboard then, it will show you how much timming it is taking to adding list item as well as how much time it is taking to Getting the list by using TryGetList() method. You can also check How to enable Developer Dashboard in SharePoint 2010 programmatically using SharePoint object model?

1 comment: