Best Practices of SharePoint Developers

Wednesday Nov 5th 2014 by Uma Narayanan

Learn about the best practices a SharePoint developer should follow while writing code.


There are a number of best practices a SharePoint developer should follow while writing code. Knowing these will help you to improve code quality and performance. I will cover the best practices in two sections:

  • Best practices for server side object model
  • Best practices for client side object mode

Best Practices for Server Side Object Model

Best Server Side SharePoint Practice 1

Make sure SharePoint objects that implement IDisposable (such as SPSite or SPWeb) are explicitly or implicitly disposed and are not stored in static variables.

Explicit Disposing:

SPSite siteColl = null;
      siteColl = new SPSite("http://abc");
      if (siteColl != null)

The site object is disposed in the finally block.

Automatic Disposing:

using (SPSite siteColl = new SPSite("http://abc"))

The Using statement takes care of disposing the object automatically. This is applicable for both site and web objects.

Best Server Side SharePoint Practice 2

There are no explicit dispose techniques required when using 'RootWeb'.

using (SPSite siteColl = new SPSite("http://abc"))
      SPWeb rootWeb = siteColl.RootWeb;

Best Server Side SharePoint Practice 3

There are no explicit dispose techniques required when using SPContext or SPControl.

SPWeb rootWeb = SPContext.Current.Site.RootWeb



This applies to both site and web objects.

Best Server Side SharePoint Practice 4

When working with lists and libraries, follow these points for performance:

  • Specify filters to retrieve limited records.
  • Specify the number of records to be returned.
  • Explicitly specify the fields to be retrieved.

For example:

a. SPQuery qry = new SPQuery();
b. SPListItemCollection spListItems ;
c. int itemCount = 100
d. qry.ViewFields = "<FieldRef Name=\"ID\"/>
   <FieldRef Name=\"ContentTypeId\"/>";
e. qry.RowLimit = itemCount;
f. StringBuilder qryString = new StringBuilder();
g. qryString.Append("<OrderBy Override=\"TRUE\">
   <FieldRef Name=\"ID\"/></OrderBy>");
h. qry.Query = qryString.ToString();
i. spListItems = spList.GetItems(qry);

In this example, we explicitly mention the fields to be retrieved, row limit, and a query. A query normally contains the filter and/or the order by clause. In this example, the 'Order by' clause is specified to avoid scanning the table.

Best Server Side SharePoint Practice 5

Explicitly check if the object exists instead of handling it in a try/catch block.

See how it works:

a. using (SPSite selectedlistsite = new SPSite(SelectedSite))
b. {
c.    using (SPWeb selectedlistsiteweb =
d.    {
e.       //Check if the lists exist
f.       SPList list = selectedlistsiteweb.Lists.
g.       if (list == null)
h.          throw new Exception("List doesn't exist, or
               you dont have permissions.");
i.     }
j. }

In this example, we have used 'TryGetList'. It returns the list object if it exists; otherwise, it returns null. Handle the null condition explicitly.

If we use selectedlistsiteweb.Lists[SelectedListName] and the list doesn't exist, it will throw an exception and handling the catch is an expensive operation.

Best Practices for Client Side Object Model

Best Client Side SharePoint Practice 1

Run ClientContext.Executequery or ClientContext.ExecuteQueryAsync before accessing any item properties.

Best Server Side SharePoint Practice 2

Explicitly specify the properties to be retrieved.

Best Server Side SharePoint Practice 3

Use group data retrieval to increase performance.

Let's understand best practices 1, 2, and 3 with the help of an example.

a. var clientContext = SP.ClientContext.get_current();
b. var web = context.get_web();
c. var currentUser = web.get_currentUser();
d. groupCollection = currentUser.get_groups();
e. context.load(currentUser);
f. context.load(groupCollection,
g. context.executeQueryAsync(function () {
h.    var termArray = [];
i.    var groupEnumerator = groupCollection.getEnumerator();
j.    while (groupEnumerator.moveNext()) {
k.       var oGroup = groupEnumerator.get_current();
l.       var groupName = oGroup.get_title();
m.       termArray.push({ groupName: groupName });
n.       }
o.    }
p.    , function (s, a) {
q.       Console.log(a.get_message());
r. });

This example is based on the JavaScript object model. Line 'a' gets the current SharePoint context, Line 'b' gets the web object, 'c' gets the current logged in user, and 'd' gets all the groups current user belongs to. If you notice, all four statements are dependent on each other.

Until Line 'd', none of the objects are retrieved yet. The next two statements are instructions to load the objects and statement. In Line 'g', 'executeQueryAsync' is actually responsible for retrieving the objects and the properties.

Statement 'i' loops through the collection and statement 'l' retrieves the value of the property 'title'.

Note: In statement 'f', 'Include(Title,Id,Users.Include(Id,Title,LoginName))') in the include statement, we also include the properties of the User object. In this example, all the properties are explicitly retrieved and are used only when the exeQueryAsync is successfully executed.

Best Server Side SharePoint Practice 4

Use separate calls to use value objects returned from methods/properties in the same query.

For example:

Note: This is a client side code in C#.
a. ClientContext context = new ClientContext("http://siteCollUrl");
b. Web web = context.Web;
c. context.Load(web, w => w.Title);

d. context.ExecuteQuery();
e. GroupCreationInformation grpCreationinfo =
      new GroupCreationInformation();
f. grpCreationinfo.Title = web.Title + "_NewGroup";
g. grpCreationinfo.Description = "New group creation";
h. web.SiteGroups.Add(grpCreationinfo);

i. context.ExecuteQuery();

In this example, the web's title is used to create a group. Because the web's title is of type value, we need to use ExecuteQuery to retrieve the title first and then create the group.

Best Server Side SharePoint Practice 5

Use scopes to test preconditions, such as access to the list or item and handle exceptions

It is easier to understand Point 5 with the help of code. This example is a C# client object model.

a. ClientContext ctx = new ClientContext("http://SiteCollUrl");
b. ExceptionHandlingScope exScope = new ExceptionHandlingScope(ctx);
c. using (exScope.StartScope())
d. {
e.    using (exScope.StartTry())
f.    {
g.       List lst = ctx.Web.Lists.GetByTitle("Tutorial");
h.       Console.Write("List exists");
i.    }
j.    using (exScope.StartCatch())
k.    {
l.       Console.Write("List doesnt exist");
m.    }
n.    using (scope.StartFinally())
o.    {
p.       Console.Write("In finally block");
q.    }
r. }
t. ctx.ExecuteQuery();

In this example, you are trying to retrieve a list that doesn't exist and the exception is handled in the exception block.


In this article, some of SharePoint's best practices are cited with the help of examples. These should help developers prevent some common mistakes when developing applications. The examples were divided into two sections, server side and client side. The client side examples were based on JavaScript and the C# client object model. These practices help in efficient memory and performance management.


Originally published on .
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved