Share point 2013 coding standards and best practices 1.0
Upcoming SlideShare
Loading in...5
×
 

Share point 2013 coding standards and best practices 1.0

on

  • 285 views

Collection of SharePoint 2013 coding standards and Best Practices. Hope it will useful for you.

Collection of SharePoint 2013 coding standards and Best Practices. Hope it will useful for you.

Statistics

Views

Total Views
285
Views on SlideShare
285
Embed Views
0

Actions

Likes
0
Downloads
8
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Share point 2013 coding standards and best practices 1.0 Share point 2013 coding standards and best practices 1.0 Document Transcript

  • Page1 SharePoint 2013 coding standards and best practices
  • Page2 Contents 1) Using SharePoint data and objects efficiently 2) Working with folders and lists 3) Deleting Multiple Versions of a List Item 4) Writing applications that scale to large numbers of users 5) Using SPQuery Objects 6) Using Web Controls 7) Creating Timer Jobs 8) File naming restrictions 9) Accessing web and site objects 10) Access external systems 11) Dispose objects 12) Exception handling in SharePoint 13) General Principals
  • Page3 Using SharePoint Data and Objects Efficiently Caching is one good way to improve system performance. However, you must weigh the benefits of caching against the need for thread safety. Additionally, you should not create certain SharePoint objects within event receivers because this will cause performance problems related to excessive database calls. Caching Data and Objects Many developers use the Microsoft .NET Framework caching objects (for example, System.Web.Caching.Cache) to help take better advantage of memory and increase overall system performance. But many objects are not "thread safe" and caching those objects can cause applications to fail and unexpected or unrelated user errors. Caching SharePoint Objects That Are Not Thread Safe You might try to increase performance and memory usage by caching SPListItemCollection objects that are returned from queries. In general, this is a good practice; however, the SPListItemCollection object contains an embedded SPWeb object that is not thread safe and should not be cached. For example, assume the SPListItemCollection object is cached in a thread. As other threads try to read this object, the application can fail or behave strangely because the embedded SPWeb object is not thread safe. For more information about the SPWeb object and thread safety, see the Microsoft.SharePoint.SPWeb class. The guidance in the following section describes how you can prevent multiple threads from attempting to read the same cached object. Understanding the Potential Pitfalls of Thread Synchronization You might not be aware that your code is running in a multithreaded environment (by default, Internet Information Services, or IIS, is multithreaded) or how to manage that environment. The following example shows the code some developers use to cache Microsoft.SharePoint.SPListItemCollection objects. Bad Coding Practice Caching an Object That Multiple Threads Might Read public void CacheData() { SPListItemCollection oListItems; oListItems = (SPListItemCollection)Cache["ListItemCacheName"]; if(oListItems == null) { oListItems = DoQueryToReturnItems(); Cache.Add("ListItemCacheName", oListItems, ..); } } Although the use of the cache in this example is functionally correct, because the ASP.NET cache object is thread safe, it introduces potential performance problems. (For more information about ASP.NET caching, see the Cache class.) If the query in the preceding example takes 10 seconds to complete, many users could try to access that page simultaneously during that amount of time. In this case, all of the users would run the same query, which would attempt to update the same cache object. If that same query runs 10, 50, or 100 times, with multiple threads trying to update the same object at the same time—especially on multiprocess, hyperthreaded computers—performance problems would become especially severe.
  • Page4 To prevent multiple queries from accessing the same objects simultaneously, you must change the code as follows. Applying a Lock Checking for null private static object _lock = new object(); public void CacheData() { SPListItemCollection oListItems; lock(_lock) { oListItems = (SPListItemCollection)Cache["ListItemCacheName"]; if(oListItems == null) { oListItems = DoQueryToReturnItems(); Cache.Add("ListItemCacheName", oListItems, ..); } } } You can increase performance slightly by placing the lock inside the if(oListItems == null) code block. When you do this, you do not need to suspend all threads while checking to see if the data is already cached. Depending on the time it takes the query to return the data, it is still possible that more than o ne user might be running the query at the same time. This is especially true if you are running on multiprocessor computers. Remember that the more proces sors that are running and the longer the query takes to run, the more likely putting the lock in the if() code block will cause problems. If you want to make absolutely sure that another thread has not createdoListItems before the curre nt thread has a chance to work on it, you could use the following pattern. Applying a Lock Rechecking for null C# private static object _lock = new object(); public void CacheData() { SPListItemCollection oListItems; oListItems = (SPListItemCollection)Cache["ListItemCacheName"]; if(oListItems == null) { lock (_lock) { //Ensure that the data was not loaded by a concurrent thread while waiting for lock. oListItems = (SPListItemCollection)Cache[“ListItemCacheName”]; if (oListItems == null) {
  • Page5 oListItems = DoQueryToReturnItems(); Cache.Add("ListItemCacheName", oListItems, ..); } } } } If the cache is already populated, this last example performs as well as the initial implementation. If the cache is not populated and the system is under a light load, acquiring the lock will cause a slight performance penalty. This approach should significantly improve performance when the system is under a heavy load, because the query will be executed only once instead of multiple times, and queries are usually expensive in comparison with the cost of synchronization. The code in these examples suspends all other threads in a critical section running in IIS, and prevents other threads from accessing the cached object until it is completely built. This addresses the thread synchronization issue; however, the code is still not correct because it is caching an object that is not thread safe. To address thread safety, you can cache a DataTable object that is created from the SPListItemCollection object. You would modify the previous example as follows so that your code gets the data from the DataTable object. Good Coding Practice Caching a DataTable Object C# private static object _lock = new object(); public void CacheData() { DataTable oDataTable; SPListItemCollection oListItems; lock(_lock) { oDataTable = (DataTable)Cache["ListItemCacheName"]; if(oDataTable == null) { oListItems = DoQueryToReturnItems(); oDataTable = oListItems.GetDataTable(); Cache.Add("ListItemCacheName", oDataTable, ..); } } } For more information and examples of using the DataTable object, and other good ideas for developing SharePoint applications, see the reference topic for the DataTable class. Using Objects in Event Receivers Do not instantiate SPWeb, SPSite, SPList, or SPListItem objects within an event receiver. Event receivers that instantiate SPSite, SPWeb, SPList, or SPListItem objects instead of using the instances passed via the event properties can cause the following problems:  They incur significant additional roundtrips to the database. (One write operation can result in up to five additional roundtrips in each event receiver.)
  • Page6  Calling the Update method on these instances can cause subsequent Update calls in other registered event receivers to fail. Bad Coding Practice Instantiating a SPSite Object inside an Event Receiver C# public override void ItemDeleting(SPItemEventProperties properties) { using (SPSite site = new SPSite(properties.WebUrl)) using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists[properties.ListId]; SPListItem item = list.GetItemByUniqueId(properties.ListItemId); // Operate on item. } } } Good Coding Practice Using SPItemEventProperties C# // Retrieve SPWeb and SPListItem from SPItemEventProperties instead of // from a new instance of SPSite. SPWeb web = properties.OpenWeb(); // Operate on SPWeb object. SPListItem item = properties.ListItem; // Operate on item. If you do not apply this fix in your code, when you call Update on the new instance, you must invalidate it with the Invalidate method in the appropriate child class of SPEventPropertiesBase (for example, SPItemEventProperties.InvalidateListItem or SPItemEventProperties.InvalidateWeb). Working with Folders and Lists When folders and lists grow in size, custom code that works with them needs to be designed in ways that optimize performance. Otherwise, your applications will run slowly and even cause timeouts to occur. The following recommendations for addressing performance concerns while working with large folders and lists Do not use SPList.Items SPList.Items selects all items from all subfolders, including all fields in the list. Use the following alternatives for each use case. Retrieving all items in a list Use SPList.GetItems(SPQuery query) instead. Apply filters, if appropriate, and specify only the fields you need to make the query more efficient. If the list contains more than 2,000 items, you will need to paginate the list in increments of no more than 2,000 items. The following code example shows how to paginate a large list.
  • Page7 Good Coding Practice Retrieving Items with SPList.GetItems C# SPQuery query = new SPQuery(); SPListItemCollection spListItems ; string lastItemIdOnPage = null; // Page position. int itemCount = 2000 while (itemCount == 2000) { // Include only the fields you will use. query.ViewFields = "<FieldRef Name="ID"/><FieldRef Name="ContentTypeId" />"; query.RowLimit = 2000; // Only select the top 2000. // Include items in subfolder (if necessary). query.ViewAttributes = "Scope="Recursive""; StringBuilder sb = new StringBuilder(); // To make it order by ID and stop scanning the table, specify the OrderBy override attribute. sb.Append("<OrderBy Override="TRUE"><FieldRef Name="ID"/></OrderBy>"); //.. Append more text as necessary .. query.Query = sb.ToString(); // Get 2,000 more items. SPListItemCollectionPosition pos = new SPListItemCollectionPosition(lastIt emIdOnPage); query.ListItemCollectionPosition = pos; //page info spListItems = spList.GetItems(query); lastItemIdOnPage = spListItems.ListItemCollectionPosition.PagingInfo; // Code to enumerate the spListItems. // If itemCount <2000, we finish the enumeration. itemCount = spListItems.Count; } The following example shows how to enumerate and paginate a large list. C# SPWeb oWebsite = SPContext.Current.Web; SPList oList = oWebsite.Lists["Announcements"]; SPQuery oQuery = new SPQuery(); oQuery.RowLimit = 10; int intIndex = 1; do { Response.Write("<BR>Page: " + intIndex + "<BR>"); SPListItemCollection collListItems = oList.GetItems(oQuery); foreach (SPListItem oListItem in collListItems)
  • Page8 { Response.Write(SPEncode.HtmlEncode(oListItem["Title"].ToString()) +"<BR> "); } oQuery.ListItemCollectionPosition = collListItems.ListItemCollectionPositi on; intIndex++; } while (oQuery.ListItemCollectionPosition != null); Getting items by identifier Instead of using SPList.Items.GetItemById, use SPList.GetItemById(int id, string field1, params string[] fields). Specify the item identifier and the field that you want. Do not enumerate entire SPList.Items collections or SPFolder.Files collections. Accessing the methods and properties that are listed in the left column of the following table will enumerate the entire SPList.Items collection, and cause poor performance and throttling for large lists. Instead, use the alternatives listed in the right column Poor performing Methods and Properties Better performing alternatives SPList.Items.Count SPList.ItemCount SPList.Items.XmlDataSchema Create a SPQuery object to retrieve only the items you want. SPList.Items.NumberOfFields Create a SPQuery object (specifying the ViewFields) to retrieve only the items you want. SPList.Items[System.GUID] SPList.GetItemByUniqueId(System.GU ID) SPList.Items[System.Int32] SPList.GetItemById(System.Int32) SPList.Items.GetItemById(System.Int32) SPList.GetItemById(System.Int32) SPList.Items.ReorderItems(System.Boolea n[], System.Int32[], System.Int32) Perform as paged query by using SPQuery and reorder the items within each page. Note: The SPList.ItemCount property is the recommended way to retrieve the number of items in a list. As a side effect of tuning this property for performance, however, the property can occasionally return unexpected results. If the precise number is required, you should use the poorer performing GetItems(SPQuery query), as shown in the preceding example. Whenever possible, acquire a reference to a list by using the list's GUID or URL as a key. You can retrieve an SPList object from the SPWeb.Lists property by using the list's GUID or display name as an indexer. Using SPWeb.Lists[GUID] andSPWeb.GetList(strURL) is always preferable to using SPWeb.Lists[strDisplayName]. Using the GUID is preferable because it is unique, permanent, and requires only a single database lookup. The display name indexer retrieves the names of all the lists in the site and then does a string comparison with them. If you
  • Page9 have a list URL instead of a GUID, you can use the GetList method to look up the list's GUID in the content database before retrieving the list. Deleting Multiple Versions of a List Item When you delete multiple versions of a list item, use the DeleteByID method; do not use the Delete method. You will experience performance problems if you delete each SPListItemVersion object from a SPListItemVersionCollection object. The recommended practice is to create and array that contains the ID properties of each version and then delete each version by using the SPFileVersionCollection.DeleteByID method. The following examples demonstrate both the approach that is not recommended approach to deleting all versions of the first item of a custom list. Bad coding practice Deleting each SPListItemVersion object C# SPSite site = new SPSite("site url"); SPWeb web = site.OpenWeb(); SPList list = web.Lists["custom list name"]; SPListItem item = list.GetItemById(1); SPListItemVersionCollection vCollection = item.Versions; ArrayList idList = new ArrayList(); foreach(SPListItemVersion ver in vCollection) { idList.Add(ver.VersionId); } foreach(int verID in idList) { SPListItemVersion version = vCollection.GetVersionFromID(verID); try { version.Delete(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } Good coding practice Deleting each version of a list item by using the SPFileVersionCollection.DeleteByID method C# SPSite site = new SPSite("site url"); SPWeb web = site.OpenWeb(); SPList list = web.Lists["custom list name"]; SPListItem item = list.GetItemById(1); SPFile file = web.GetFile(item.Url); SPFileVersionCollection collection = file.Versions; ArrayList idList = new ArrayList(); foreach (SPFileVersion ver in collection) {
  • Page10 idList.Add(ver.ID); } foreach (int verID in idList) { try { collection.DeleteByID(verID); } catch (Exception ex) { MessageBox.Show(ex.Message); } } Writing applications that scale to large numbers of users You might be aware that you need to write your code to be scalable so that it can handle multiple users simultaneously. A good example is creating custom navigation information for all sites and subsites on each page or as part of a master page. If you have a SharePoint site on a corporate intranet and each department has its own site with many subsites, your code might resemble the following: C# public void GetNavigationInfoForAllSitesAndWebs() { foreach(SPSite oSPSite in SPContext.Current.Site.WebApplication.Sites) { try { SPWeb oSPWeb = oSPSite.RootWeb; AddAllWebs(oSPWeb); } finally { oSPSite.Dispose(); } } } public void AddAllWebs(SPWeb oSPWeb) { foreach(SPWeb oSubWeb in oSPWeb.Webs) { try { //.. Code to add items .. AddAllWebs(oSubWeb); } finally { if (oSubWeb != null) oSubWeb.Dispose(); } } }
  • Page11 While the previous code disposes of objects properly, it still causes problems because the code iterates through the same lists over and over. For example, if you have 10 site collections and an average of 20 sites or subsites per site collection, you would iterate through the same code 200 times. For a small number of users this might not cause bad performance. But, as you add more users to the system, the problem gets worse, as shown in below table. Users Iterations 10 2000 50 10000 100 200000 250 500000 Although the code executes for each user that hits the system, the data remains the same for eac h user. The impact of this can vary depending on what the code is doing. In some cases, repeating code might not cause performance problem; however, in the previous example the system must create a COM object (SPSite or SPWeb objects are created when retrieved from their collections), retrieve data from the object, and then dispose of the object for each item in the collection. This can have a significant impact on performance. How to make this code more scalable or fine-tune it for a multiple user environment can be a hard question to answer. It depends on what the application is designed to do. You should take the following into consideration when asking how to make code more scalable: a) Is the data static, somewhat static, or dynamic? b) Is the data same for all users, or does it change? For example, does it change depending on the user who is logged on, the part of the site being accessed, or the time of year? c) Is the data easily accessible or does it require a long time to return the data? For example, is it returning from a long-running database query or from remote databases that can have some network latency in the data transfers? d) Is the data public or does it require a high level of security? e) What is the size of the data? f) Is the SharePoint site on a single server or on a server farm? How you answer the previous questions will determine in which of several ways you can make your code more scalable and handle multiple users. The intent of this article is not to provide answers for all of the questions or scenarios but to provide a few ideas that you can apply to your specific needs. The following sections offer areas for your consideration. Caching Raw Data You can cache your data by using the System.Web.Caching.Cache object. This object requires that you query the data one time and store it in the cache for access by other users. If your data is static, you can set up the cache to load the data only one time and not expire until the application is restarted, or to load the data once per day to ensure data freshness.
  • Page12 You can create the cache item when the application starts, when the first user session starts, or when the first user tries to access that data. If your data is somewhat static, you can set up the cached items to expire within a certain number of seconds, minutes, or hours after the data is created. This enables you to refresh your data within a timeframe that is acceptable to your users. Even if the data is cached for only 30 seconds, under heavy loads you will still see improved performance because you are running the code only one time every 30 seconds instead of multiple times per second for each user who hits the system. Security trimming is another issue to consider whenever you cache data. For example, if you cache items as you iterate through a list, you may get only a subset of the data (the data that the current user can see), or if you use a DataTable object to cache all of the items in a list, you have no easy way of applying security trimming to users who belong to groups that can see only a subset of the data. For more information about storing security trimmed data in caches, see the CrossListQueryCache class. In addition, ensure you consider the issues described earlier in Caching Data and Objects. Building Data before Displaying It Think about how your cached data will be used. If this data is used to make run-time decisions, putting it into a Dataset or DataTable object might be the best way to store it. You can then query those objects for the data to make run-time decisions. If the data is being used to display a list, table, or formatted page to the user, consider building a display object and storing that object in the cache. At run time, you need only retrieve the object from the cache and call its render function to display its contents. You could also store the rendered output; however, this can lead to security issues and the cached item could be quite large, causing increased page swapping or memory fragmentation. Caching For a Single Server or Server Farm Depending on how you set up your SharePoint site, you might have to address certain caching issues differently. If your data must be the same on all servers at all times, then you must ensure that the same data is cached on each server. One way to ensure this is to create the cached data and store it on a common server or in a Microsoft SQL Server database. Again, you must consider how much time it takes to access the data and what security issues can arise from storing the data on a common server. You can also create business-layer objects that cache data on a common sever, and then access that data by using various interprocess communications that are available in networking objects or APIs. Whenever possible, acquire a reference to a list by using the list's GUID or URL as a key. You can retrieve a SPList object from the SPWeb.Lists property by using the list's GUID or display name as an indexer. Using SPWeb.Lists[GUID] and SPWeb.GetList(strURL) is always preferable to using SPWeb.Lists[strDisplayName]. Using the GUID is preferable because it is unique, permanent, and requires only a single database lookup. The display name indexer retrieves the names of all the lists in the site and then does a string comparison with them. If you have a list URL instead of a GUID, you can use the GetList method to look up the list's GUID in the content database before retrieving the list.
  • Page13 Avoid creating and destroying objects unnecessarily in code Avoid creating and destroying objects unnecessarily in code, as this may require that extra queries be made against the database and may even involve code that is incorrect. In the following example, separate objects for the Tasks list must be instantiated each time the indexer is used to set properties and the method for updating is called. This is not a recommended practice. Bad Practice SPWeb myWeb = SPContext.Current.Web; myWeb.Lists["Tasks"].Title = "List_Title"; myWeb.Lists["Tasks"].Description = "List_Description"; myWeb.Lists["Tasks"].Update(); Good Practice SPWeb myWeb = SPContext.Current.Web; SPList myList = myWeb.Lists["Tasks"]; myList.Title="List_Title"; myList.Description="List_Description"; myList.Update(); Note: a) The object models in the Microsoft.SharePoint assembly optimize performance and minimize the number of SQL queries that are made. However, to monitor code performance, it is recommended that you use the SQL Profiler. b) To return a single item from a collection, always use a Get* method when one is provided through a parent object, instead of iterating through the entire collection and using an indexer. 5) Handling large folders and lists When the size of folders and lists increases, you must design custom code that works with them to optimize performance. Otherwise, your applications will run slowly and can cause service or page load timeouts. The two primary areas for concern when handling large folders and lists are the following: Query throttling, which can cause the behavior of your code to change in unexpected and unpredictable ways over time as your site evolves and your queries begin to return items that exceed the query threshold. Efficient retrieval of items from large folders and lists. 6) Throttling for Large List Queries Microsoft SharePoint Foundation 2013 and Microsoft SharePoint Server 2013 apply a default query threshold of 5,000 items. Any custom code that relies on query result sets that can exceed this maximum will not perform as expected. Queries on lists consisting of more than 5,000 items that include fields that are not indexed in their query conditions will also fail, because those queries must scan all rows in a list. Follow the steps listed below to view and increase this limit or to enable the object model to override the limit: To view and increase this threshold or to enable the object model to override the threshold
  • Page14 On the Central Administration site, under Application Management, click Manage Web Applications. Click General Settings, and then click Resource Throttling. View and update the threshold or allow the object model to override the limit. 7) Deleting Multiple Versions of a List Item When you delete multiple versions of a list item, use the DeleteByID method; do not use the Delete method. You will experience performance problems if you delete eachSPListItemVersion object from a SPListItemVersionCollection object. The recommended practice is to create an array that contains the ID properties of each version and then delete each version by using the SPFileVersionCollection.DeleteByID method. The following code examples demonstrate both the approach that is not recommended and the recommended approach to deleting all versions of the first item of a custom list. Bad Coding Practice Deleting each SPListItemVersion object SPSite site = new SPSite("site url"); SPWeb web = site.OpenWeb(); SPList list = web.Lists["custom list name"]; SPListItem item = list.GetItemById(1); SPListItemVersionCollection vCollection = item.Versions; ArrayList idList = new ArrayList(); foreach(SPListItemVersion ver in vCollection) { idList.Add(ver.VersionId); } foreach(int verID in idList) { SPListItemVersion version = vCollection.GetVersionFromID(verID); try { version.Delete(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } Good Coding Practice Deleting each version of a list item by using the SPFileVersionCollection.DeleteByID method SPSite site = new SPSite("site url"); SPWeb web = site.OpenWeb(); SPList list = web.Lists["custom list name"]; SPListItem item = list.GetItemById(1); SPFile file = web.GetFile(item.Url); SPFileVersionCollection collection = file.Versions; ArrayList idList = new ArrayList(); foreach (SPFileVersion ver in collection)
  • Page15 { idList.Add(ver.ID); } foreach (int verID in idList) { try { collection.DeleteByID(verID); } catch (Exception ex) { MessageBox.Show(ex.Message); } } Using SPQuery Objects SPQuery objects can cause performance problems whenever they return large result sets. The following suggestions will help you optimize your code so that performance will not suffer greatly whenever your searches return large numbers of items. Do not use an unbounded SPQuery object. An SPQuery object without a value for RowLimit will perform poorly and fail on large lists. Specify a RowLimit between 1 and 2000 and, if necessary, page through the list. Use indexed fields. If you query on a field that is not indexed, the query will be blocked whenever it would result in a scan of more items than the query threshold (as soon as there are more items in the list than are specified in the query threshold). Set SPQuery.RowLimit to a value that is less than the query threshold. If you know the URL of your list item and want to query by FileRef, use SPWeb.GetListItem(string strUrl, string field1, params string[] fields)instead. Using Web Controls When you inherit and override controls in the Microsoft.SharePoint.WebControls namespace, remember that SharePoint Web controls are templated controls. Unlike Microsoft ASP.NET Web controls, they are defined and rendered with templates instead of with the CreateChildControls method. Instead of having a thickCreateChildControls method that uses the new operator to create child controls, perform most child control creation and rendering by using the rendering templates that are referenced in the Template, AlternateTemplate, DisplayTemplate, CustomTemplate, and AlternateCustomTemplate properties of the SharePoint Web control. SharePoint Web controls do inherit the CreateChildControls method, but that method should typically do little or nothing beyond calling the parent control's CreateChildControlsmethod and perhaps a bit of "final polish" rendering, such as assigning default values to child control properties in New mode or assigning the current values in Edit mode.
  • Page16 Creating Timer Jobs Design your timer jobs so that they consist of small, manageable pieces. Because administrators and other events, such as system restarts, can stop timer jobs, you can minimize the amount of rework after any interruption by breaking timer jobs into small pieces of work. Avoiding Unnecessary Construction of SPWeb and SPSite Objects A SPWeb or SPSite object can occupy a lot of memory. Avoid constructing objects of these types simply to get a reference to a parent object. Instead, to get a reference to a web application, use the static SPWebApplication.Lookup(Uri) method, and pass it a Uri object that is created with the URI of the web application. You can then get a reference to the farm by using the Farm property of the web application object. (You can get a reference to a remote farm by using the static Open(String) method.) TheContentDatabases property of the web application object contains a collection of the content databases in the web application. You can get a reference to a particular content database through this property if you know its index in the collection. For more information, see the reference topic for the SPContentDatabaseCollection class. The following code illustrates some of these points. SPWebApplication webApplication = SPWebApplication.Lookup(new Uri("http://localhost/"); SPFarm farm = webApplication.Farm; SPContentDatabase content = webApplication.ContentDatabases[0]; File Naming Restrictions For security reasons, SharePoint Foundation reads files in the %ProgramFiles%Common FilesMicrosoft Sharedweb server extensions15TEMPLATE directory tree only if their names are composed of ASCII letters, numbers, periods, underscores, or dashes. In addition, file names cannot contain two or more consecutive periods. For example: Following are permitted file names: a) AllItems.aspx b) Dept_1234.doc c) Long.Name.With.Dots.txt The following are not permitted file names: a) Cæsar.wav b) File Name with Spaces.avi c) Wow...ThisIsBad.rtf d) 揵.htm Accessing Web and Site Objects 1) Get Current Site details using SPSite SPSite oSiteCollection = SPContext.Current.Site;
  • Page17 2) Get Current Web details using SPWeb SPWeb oWebSite = SPContext.Current.Web; 3) When your code is contained in an .aspx file or the "code behind" in an .aspx.cs file, you can use methods to get the SPWeb. SPWeb oWebSite = SPControl.GetContextWeb(Context); where Context = System.Web.UI.Page.Context 4) To get reference of the current web object from .aspx page that is inherited from LayoutsPageBase is : SPWeb oWebSite = this.Web; 5) Use the Microsoft.SharePoint.SPSite.AllWebs property to obtain a reference to a Web site other than the current one. SPWeb oWebSite = SPContext.Current.Site.AllWebs["myOtherSite"]; 6) Get reference of server farm or current physical server : SPFarm oFarm = SPFarm.Local; Access external systems When the data source is a Web service or database, consider using the Business Data Catalog (BDC) for SP 2007 and Business Connectivity Services (BCS) for SP 2013. SharePoint Databases Do not make calls directly to the SharePoint content and configuration databases. Packaging Structure your code project so that solution packaging is integrated into the project Dispose Objects We should not dispose any SPWeb, SPSite object create using SPContext.Current.Site, SPContext.Current.Web, SPControl.GetContextWeb(Context), this.Web We should explicitly dispose of references to objects obtained through the AllWebs property The code should dispose any SPSite or SPWeb object obtained by using a constructor. Do not dispose dispose of the SPWeb.ParentWeb The SPWeb.Webs property returns a SPWebCollection object. The SPWeb objects in this collection must be disposed. The SPWeb.Webs.Add method (or Add) creates and returns a new SPWeb object. You should dispose of any SPWeb object returned from this method call. If the object is obtained from the SharePoint context objects (GetContextSite method and GetContextWeb method), the calling application should not call the Dispose method on the object. You should still dispose of an object that is created from these objects, for example, if a Web site is opened from an SPSite object that you obtained by using the GetContextSite method. Wrong Way void CombiningCallsLeak()
  • Page18 { using (SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb()) { // ... New SPSite will be leaked. } // SPWeb object web.Dispose() automatically called. } Right Way void CombiningCallsBestPractice() { using (SPSite siteCollection = new SPSite(SPContext.Current.Web.Url)) { using (SPWeb web = siteCollection.OpenWeb()) { //Perform operations on site. } // SPWeb object web.Dispose() automatically called. } // SPSite object siteCollection.Dispose() automatically called. } Exception Handling in SharePoint 1. Avoid empty Catch blocks All the errors should be reported using error logging functionality, if not handled sufficiently. Wrong Way try { // code } catch { } 2. Use throw; if you’re going to throw an exception Wrong Way try { // code } catch (Exception ex) { throw ex; } Right Way try { // code } catch { throw;
  • Page19 } 3. Handle the specific exception wherever possible Right Way try { spList = spWeb.GetList("/Path/List"); } catch (FileNotFoundException ex) { // handle exception } catch (ArgumentException ex) { // handle exception } 4. Try to check condition before it throws exception Wrong Way try { myString = listItem["MyField"].ToString(); } catch (Exception ex) { // handle exception } Right Way if (String.IsNullOrEmpty(listItem["MyField"])) { myString = listItem["MyField"].ToString(); } 6. Use an appropriate form of logging exception. The most important takeaway is to ensure that the errors are logged. The 2 most logical locations to log the errors would be the ULS or Event Log, however this may not always be appropriate. If these locations aren’t regularly monitored or accessible by the people who need to know about the errors, then it is essentially no better than swallowing the errors in the first place. Email, CRM, a database or even a SharePoint list are other potential locations that could be more accessible. Logging to a file on the file system makes little sense seeing if that is an accessible option you could just use the ULS. 7. Use a custom error page. Nothing looks worse on a public facing internet site or even an intranet application than when you get the SharePoint default error page. Wherever possible you should display a user friendly message rather than an ugly generic error page.
  • Page20 General Principals  All new functionality and customizations must be documented.  Do not edit out of the box files. o For a few well defined files such as the Web.config or docicon.xml files, the built-in files included with SharePoint Products and Technologies should never be modified except through official supported software updates, service packs, or product upgrades.  Do not modify the Database Schema. o Any change made to the structure or object types associated with a database or to the tables included in it. This includes changes to the SQL processing of data such as triggers and adding new User Defined Functions. o A schema change could be performed by a SQL script, by manual change, or by code that has appropriate permissions to access the SharePoint databases. Any custom code or installation script should always be scrutinized for the possibility that it modifies the SharePoint database.  Do not directly access the databases. o Any addition, modification, or deletion of the data within any SharePoint database using database access commands. This would include bulk loading of data into a database, exporting data, or directly querying or modifying data. o Directly querying or modifying the database could place extra load on a server, or could expose information to users in a way that violates security policies or personal information management policies. If server- side code must query data, then the process for acquiring that data should be through the built-in SharePoint object model, and not by using any type of query to the database. Client-side code that needs to modify or query data in SharePoint Products and Technologies can do this by using calls to the built-in SharePoint Web services that in turn call the object model.  Exception: In SharePoint 2010 the Logging database can be queried directly as this database was designed for that purpose.  Use best practices when accessing data using the SharePoint object model. See Working with Large Lists, Common Coding Issues When Using the SharePoint Object Model, and Using Disposable Windows SharePoint Services Objects Development Decisions: There are plenty of challenging decisions that go into defining what the right solution for a business or technical challenge will be. What follows is a chart meant to help developers when selecting their development approach. Sandbox Apps Farm When to use Deprecated. Therefore, it’s unadvisable to build new sandboxed solutions. Best practice. Create apps whenever you can. Create farm solutions when you can’t do it in an app. Server-side code Runs under a strict CAS policy and is limited in what it can do. No SharePoint server- code. When apps are hosted in an isolated SharePoint site, no Can run full trust code or run under fine grained custom CAS policies.
  • Page21 server-code whatsoever is allowed. Resource throttling Run under an advanced resource management system that allows resource point allocation and automatic shutdown for troublesome solutions. Apps run isolated from a SharePoint farm, but can have an indirect impact by leveraging the client object model. Can impact SharePoint server-farm stability directly. Runs cross-domain No, and there’s no need to since code runs within the SharePoint farm. Yes, which provides a very interesting way to distribute server loads. No, and there’s no need to since code runs within the SharePoint farm. Efficiency/Performance Runs on the server farm, but in a dedicated isolated process. The sandbox architecture provides overhead. Apps hosted on separate app servers (even cross- domain) or in the cloud may cause considerable overhead. Very efficient. Safety Very safe. Apps rely on OAuth 2.0. The OAuth 2.0 standard is surrounded by some controversy. In fact, some SharePoint experts have gone on the record stating that security for Apps will become a big problem. We’ll just have to wait and see how this turns out. Can be very safe, but this requires additional testing, validation and potential monitoring. Should IT pros worry over it? Due the the limited CAS permissions and resource throttling system, IT pros don’t have to worry. Apps are able to do a lot via the client OM. There are some uncertainties concerning the safety of an App running on a page with other Apps. For now, this seems to be the most worry-able option, but we’ll have to see how this plays out. Definitely. This type of solutions run on the SharePoint farm itself and therefore can have a profound impact. Manageability Easy to manage within the SharePoint farm. Can be managed on a dedicated environment without SharePoint. Dedicated app admins can take care of this. Easy to manage within the SharePoint farm. Cloud support Yes Yes, also support for App MarketPlace. No, on-premises (or dedicated) only. App Development (SharePoint 2013):  When developing an app select the most appropriate client API: o Apps that offer Create/Read/Update/Delete (CRUD) actions against SharePoint or BCS external data, and are hosted on an application server separated by a firewall benefit most from using the JavaScript client object model.
  • Page22 o Server-side code in Apps that offer Create/Read/Update/Delete (CRUD) actions against SharePoint or BCS external data, and are hosted on an application server but not separated by a firewall mainly benefit from using the .managed client object model, but the Silverlight client object model, JavaScript client object model or REST are also options. o Apps hosted on non-Microsoft technology (such as members of the LAMP stack) will need to use REST. o Windows phone apps need to use the mobile client object model. o If an App contains a Silverlight application, it should use the Silverlight client object model. o Office Apps that also work with SharePoint need to use the JavaScript client object model. Quality Assurance:  Custom code must be checked for memory leaks using SPDisposeCheck. o False positives should be identified and commented.  Code should be carefully reviewed and checked. As a starting point use this code review checklist (and provide additional review as needed). Branding:  A consistent user interface should be leveraged throughout the site. If a custom application is created it should leverage the same master page as the site.  Editing out of the box master pages is not allowed. Instead, duplicate an existing master page; make edits, then ensure you add it to a solution package for feature deployment.  When possible you should avoid removing SharePoint controls from any design as this may impact system behavior, or impair SharePoint functionality.  All Master Pages should have a title, a description, and a preview image.  All Page Layouts should have a title, a description, and a preview image. Deployment:  All custom SharePoint work should be deployed through SharePoint Solution (.wsp) files.  Do not deploy directly into the SharePointRoot (15-Hive) Folders. Instead deploy into a folder identified by Project Name. Documentation:  Provide an Installation Guide which contains the following items: o Solution name and version number. o Targeted environments for installation. o Software and hardware Prerequisites: explicitly describes what is all needed updates, activities, configurations, packages, etc. that should be installed or performed before the package installation. o Deployment steps: Detailed steps to deploy or retract the package.
  • Page23 o Deployment validation: How to validate that the package is deployed successfully. o Describe all impacted scopes in the deployment environment and the type of impact. Features:  Features must have a unique GUID within the farm.  Features with event receivers should clean up all changes created in the activation as part of the deactivation routine. o The exception to this is if the feature creates a list or library that contains user supplied data. Do not delete the list/library in this instance.  Features deployed at the Farm or Web Application level should never be hidden.  Site Collection and Site Features may be hidden if necessary.  Ensure that all features you develop have an appropriate name, description, updated version number and icon. SharePoint Designer:  SharePoint Designer 2013 updates are generally only allowed by a trained individual. o The following is a recommended way of managing the creation of DataForm Web Parts: Create a temporary web part page (for managing the manipulation of a data view web part). Once the web part is ready for release and all modifications have been made export the .webpart and then delete the page. You can now import it onto a page elsewhere or place it in the gallery. This way none of your production pages are un- ghosted. The other advantage is that you can place the DVWP on a publishing page (as long as there are web part zones to accept them). o DataForm Web Parts should be exported through the SharePoint GUI and solution packaged for deployment as a feature.  SharePoint Designer workflows should not be used for Business Critical Processes. o They are not portable and cannot be packaged for solution deployment.  Exception Note: Based on the design and approach being used it may be viable in SharePoint 2013 for you to design a workflow that has more portability. This should be determined on a case by case basis as to whether it is worth the investment and is supportable in your organization. Site Definitions:  Site and list templates must be created through code and features (site and list definitions). o STP files are not allowed as they are not updatable.  Site definitions should use a minimal site definition with feature stapling. Solutions:  Solutions must have a unique GUID within the farm.  Ensure that the new solution version number is incremented (format V#.#.#).  The solution package should not contain any of the files deployed with SharePoint.  Referenced assemblies should not be set to “Local Copy = true”
  • Page24  All pre-requisites must be communicated and pre-installed as separate solution(s) for easier administration. Source Control:  All source code must be under a proper source control (like TFS or SVN).  All internal builds must have proper labels on source control.  All releases have proper labels on source control. InfoPath:  If an InfoPath Form has a code behind file or requires full trust then it must be packaged as a solution and deployed through Central Administration.  If an InfoPath form does not have code behind and does not need full trust the form can be manually published to a document library, but the process and location of the document library must be documented inside the form. o Just add the documentation text into a section control at the top of the form and set conditional formatting on that section to always hide the section, that way users will never see it. WebParts  All WebParts should have a title, a description, and an icon. Application Configuration  There are only a few methods in which application configuration data can be stored. When selecting the option that is right for the situation before making the decision. o Web.config  APIs such as the ConfigurationSection class and SPWebConfigModification class should always be used when making modifications to the Web.config file.  HTTPModules, FBA membership and Role provider configuration must be made to the Web.config. o Property Bags  It is recommended that you create your own _layouts page for your own settings.  It is also recommended that you use this codeplex tool to support this method http://pbs2010.codeplex.com/ o Lists  This is not a recommended option for Farm or Web Application level configuration data.  It is also recommended that you use this codeplex tool to support this method http://spconfigstore.codeplex.com/
  • Page25 o Hierarchical Object Store (HOS) or SPPersistedObject  Ensure that any trees or relationships you create are clearly documented.  It is also recommended that you use the Manage Hierarchical Object Store feature at http://features.codeplex.com/. This feature only stores values in the Web Application. You can build a hierarchy of persisted objects but these objects don’t necessarily map to SPSites and SPWebs. Process: All customizations and custom code will go through our review and release cycle. Example of Review and Release cycle.