Sunday, December 29, 2013

Best Coding Practices in Share Point Object Model

When developers code in SOM they always faces the  issues related to performance, extensibility, and scalability. Usually all these issue are trouble shoot and tried to resolve by doing some alternate options and developers skips the main reason causing for it.

I am listing some of the key points to use the best coding practice which could avoid the above issues in SOM. I have taken help of MS tech net and MSDN to prepare this article.


Caching Data and Objects

some  of the developers use the Microsoft .NET Framework caching objects to 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

Developers use  cache to hold the SPItemCollection for less memory utilization but this object contains the SPWeb opbject which is not thread safe and it leads to execute multiple times in the memory to cause bad performance of the application

Understanding the Potential Pitfalls of Thread Synchronization

Consider the scenario that  you trying to update the list item by Item.update method and you get this happens in 10sec. It works perfectly with you and with 10 more developers.But it start becoming severe when number of users grows try to update the same item with multiple thread at same time. You must it add the lock on the code to happen it in sequence.   

 Coding practice with list and folders

Developers write the code to fetch the list item or update list item in regular development practice. Following are some important points must need to remember while doing the above mentioned operations

Dont fetch the list items using SPList.Items- It selects all items from all sub folders, including all fields in the list. Use the following alternatives for each use case. Use the below given syntax instead of it
SPList.GetItems(SPQuery query)

Paginate the items while fetching it from large lists - When you try to fetch the items from large list always remember to add the row limit  to the items. This will fetch the items with row item size and you will get good performance using this 

Getting items by identifierInstead of using SPList.Items.GetItemById-

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.

Table from MSDN
Poor Performing Methods and Properties Better Performing Alternatives
SPList.Items.Count SPList.ItemCount
SPList.Items.XmlDataSchema Create an SPQuery object to retrieve only the items you want.
SPList.Items.NumberOfFields Create an SPQuery object (specifying the ViewFields) to retrieve only the items you want.
SPList.Items[System.Guid] SPList.GetItemByUniqueId(System.Guid)
SPList.Items[System.Int32] SPList.GetItemById(System.Int32)
SPList.Items.GetItemById(System.Int32) SPList.GetItemById(System.Int32)
SPList.Items.ReorderItems(System.Boolean[],System.Int32[],System.Int32) Perform a paged query by using SPQuery and reorder the items within each page.
SPFolder.Files.Count SPFolder.ItemCount

 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 an 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.

 

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.
Following are the important questions  that you can check while developing any artifact in SP using SOM
  • Does my code properly dispose of SharePoint objects?
  • Does my code cache objects properly?
  • Does my code cache the correct types of objects?
  • Does my code use thread synchronization when necessary?
  • Does my code work as efficiently for 1,000 users as it does for 10 users?
     


 

 


Tuesday, December 24, 2013

Creating and consuming web service in Share Point Hosted environment




The service-oriented applications can be build using WCF ( windows communication foundation). Using WCF, data can be sent in asynchronous way from one service endpoint to another.
The WCF is mostly used in following scenarios.
A Silverlight application to poll a service for the latest data feeds
A chat service that allows two people to communicate or exchange data in real time.
A secure service to process business transactions.
A service that supplies current data to others, such as a traffic report or other monitoring service.
A dashboard application that polls one or more services for data and presents it in a logical presentation.
Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.

The WCF can be created as one of the feature and can be deployed to hosted share point environment. It has to deploy to ISAPI folder as WSP package or under web application vti_bin folder. Once it’s added to share point then it can used in any web application, Silver light application or any other application as interface to share point.
Below some description provided for creating share point hosted WCF and consuming it in your application.
To prepare this article I have taken the help from MSDN.
To create a SharePoint Foundation project for the WCF service, open the ProjectTracker solution in Visual Studio. In Solution Explorer, click the solution. On the File menu, point to Add, and then click New Project. In the Installed Templates tab of the Add New Project dialog box, expand Visual C# node, select SharePoint, select Empty SharePoint Project, and then type ChangeTitleWCFProject as the name of the project. Click OK.
In the SharePoint Customization Wizard, verify that the correct local site is specified for debugging. Because sandboxed solutions do not support WCF services, select Deploy as a farm solution, and then click Finish.
To create the external WCF project to obtain its IService1 and Service1 .cs files, click the ProjectTracker solution again, and follow the same procedure as in Step 1 to open the Add New Project dialog box. Expand Visual C# node, select WCF, select WCF Service Library, type ChangeTitleWCF as the name, and then click OK.

Copy the generated IService1 and Service1 files into the ChangeTitleWCFProject project. Because you no longer need the WCF Service Library project, you can remove it from the solution by right-clicking the WCF Service Library and clicking Remove.

Add references in the ChangeTitleWCFProject to the System.Runtime.Serialization and System.ServiceModel WCF assemblies, and to Microsoft.SharePoint, the main assembly of the server object model. Right-click the ChangeTitleWCFProject, click Add Reference, and select each of these assemblies on the .NET tab.

To add a reference to Microsoft.SharePoint.Client.ServerRuntime, which contains the service factories that are provided by SharePoint Foundation, use the Browse tab of the Add Reference box to navigate to the Microsoft.SharePoint.Client.ServerRuntime.dll file in %Windows%\assembly\GAC_MSIL\Microsoft.SharePoint.Client.ServerRuntime, select the DLL, and then click OK.

To specify the contract of your custom WCF service in IService1.cs replace the auto-generated service contract with the following interface definition, where the ChangTitle method accepts the name of the list in which to change the title of the item






  Now that the implementation of the service is ready, you can deploy the service to SharePoint Foundation. Right-click the ChangeTitleWCFProject project, point to Add, and click SharePoint Mapped Folder. In the Add SharePoint Mapped Folder dialog box, select ISAPI, and then click OK to map the ISAPI folder of the SharePoint Foundation hive to the ChangeTitleWCFProject project. If Visual Studio creates a ChangeTitle subfolder in the ISAPI folder of the ChangeTitleWCFProject, right-click the subfolder and click Remove to delete it.
 To create a registration file for your service in the ISAPI folder, click the ISAPI folder in your project, and on the Project menu, click Add New Item. Under Installed Templates, select General. Select Text File, name the file Revert.svc, and then click Add.
 

Add the following service declaration to ChangeTItle.svc, which specifies the SharePoint Foundation factories and the namespace that contains them. In the example, MultipleBaseAddressBasicHttpBindingServiceHostFactory specifies the service factory for the SOAP type of web service. The service class declaration also specifies the name of the service class and uses a token to specify the strong name of the assembly.

<%@ServiceHost Language="C#" Debug="true"
    Service="WcfService.ChangeTitleService, $SharePoint.Project.AssemblyFullName$"
    Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressBasicHttpBindingServiceHostFactory,
Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=80e7sde143e94929r" %>

After you add the previous tag, save the project and close the .csproj file. In Solution Explorer, right-click the ChangeTitleWCFProject project, and then click Reload Project.

 To deploy the custom web service to SharePoint Foundation, in Solution Explorer, right-click the ChangeTitleWCFProject project, and then click Deploy. Visual Studio compiles the project’s code, builds a WSP file, and deploys the file to the front-end web server.

  To use the custom web service from your ProjectTracker client application, right-click the Service References node of the application in Solution Explorer, and then click Add Service Reference. In the Add Service Reference dialog box, type the URL of your custom WCF service in the Address box, and specify MEX as the standard name for the metadata exchange endpoint, as follows: http://Server/sites/SiteCollection/MyWebSite/_vti_bin/Revert.svc. Click Go to download the service information, and then click OK to add the reference.


  Double-click the Change button and add to its Click event the following standard WCF proxy setup code with a call to your custom WCF service. Resolve references to assemblies by right-clicking red underlined elements in the code, pointing to Resolve, and accepting recommended assembly references for the System.ServiceModel namespace and for the namespace of your custom WCF service (ProjectTracker.ServiceReference2).
This is how it’s get used in the separate application.