Thursday, February 28, 2013

MSOCAF rule: SharePointFeatureReceiver must log to ULS Logs.

If you are working on Apps or Web Part for SharePoint Online (Office 365), you must run the MSOCAF to check all rules accepted by Microsoft before deploy on SharePoint Online. One of these rules there is a rule for Feature Receiver. The code which is implemented for Feature Receiver will fire when the feature is activated, de-activated, activating or de-activating. And if there is any error during the executing time, all exceptions must be log so that user can handle the exception.

This is example:

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                //TODO: SOMETHING
            }
            catch (Exception e)
            {
                logger.Write("Error:", e);
            }
        }

To handle exception, I write the value of "e" variable to log file in TMP folder. Ans result as well if the code run under SharePoint local or SharePoint hosting. But it is not compatible with SharePoint Online, and because Office 365/SharePoint Online will write the log into SharePoint list and MSOCAF will not accept this way to manage the error.

 MSOCAF will give the message:

  The catch block at line number '[symbols not found to locate the line number]' in method ...FeatureDeactivating(Microsoft.SharePoint.SPFeatureReceiverProperties) must log to ULS Logs. For ULS logging, please use the Microsoft.SharePoint.Administration.SPDiagnosticsServiceBase.WriteTrace API in SharePoint 2010.

To solve this issue, just throw exception to parent process and write the exception to SharePoint log.

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                //TODO: SOMETHING
            }
            catch (Exception e)
            {
                Microsoft.SharePoint.Administration.SPDiagnosticsServiceBase w = SPDiagnosticsService.Local;
                w.WriteTrace(1, SPDiagnosticsService.Local.Areas["SharePoint Foundation"].Categories["Unknown"], TraceSeverity.Verbose, "");

                throw new ApplicationException("Feature1EventReceiver.FeatureDeactivating", e.InnerException);
            }
        }
You can customize the log category and severity to show the exception to be friendly instead of leaving the default setting.

2 comments:

Anonymous said...

Thank you very much, you saved my time.

Binh Luong said...

you are awesome