Wednesday, February 27, 2013

Best Practice coding & MSOCAF checking for SharePoint 2013

Sometime, I think that to convert the code of web part from SharePoint 2010 to SharePoint 2013 is simple to change the reference all of SharePoint DLLs then make a package. That’s it. But it is not simple as I thought. The Apps or Web Parts which are running on SharePoint 2013 must be also checked by MSOCAF before they are pushed on storefront. MSOCAF will check many rules to improve the performance, guarantee the safety security, memory leaks and other things following the test cases. The specialist is to have the difference between MSOCAF for SharePoint 2010 and MSOCAF for SharePoint 2013. Except for 2013 upgrading rules and some new rules, the code for 2010 could not apply to 2013.

Here is example: To improve the performance in process the large list, my code in SharePoint 2010 look like this:





 Of course, that code was passed by MSOCAF for SharePoint 2010. But it’s failed by MSOCAF for SharePoint 2013.
 




 The message shows that the object “SPListItemCollection” must not be declared in the loop statement. Assume that if you need to process data through SPListItemCollection object, so you must declare an “items” variable to handle the collection of items after execute the query. By this way, you will interact to SPListItem object easily, but unfortunately the MSOCAF catches the code in violation of rules. Now, I try to write another code of using SPListItemCollection in the loop statement to make sure this rule is very confused.



And as a result:



That’s for sure SPListItemCollection must not be declared in loop statement, instead of using another C# object to handle a collection of SPListItem. My solution is to change the code using DataTable instead of SPListItemCollection and process the data through that array.




And result is:
 


Conclusion:

 Try to use the .NET object collection in loop statement to improve your performance, or if you need to use SPListItemCollection object, try to build the query CAML with many conditions and execute one time to avoid the loop and pass the MSOCAF checking. For now, I don’t have any solution as well to pass the MSOCAF checking with this rule, I just try to change the code a little bit and use .NET object collection for my purpose. In many cases, think more about the situation to avoid using SharePoint object modal , and of course by using .NET object collection it will improve performance a lot while SharePoint object modal collection still keeps the connection to database when we access to each of item in collection. I think that’s the reason why SharePoint 2013 does not recommend to use SPListItemCollection in loop statement.

1 comment: