How to: Create a Feature to Register a Health Rule

Applies to: SharePoint Foundation 2010

You install a new health rule by registering the rule with SharePoint Health Analyzer. To do that, you must first place the assembly that contains the rule into the Global Assembly Cache (GAC) on every machine and then call the RegisterRules(Assembly) method of the SPHealthAnalyzer class.

When you are working in your development environment, you can use the Global Assembly Cache Tool (Gacutil.exe) to place the assembly in the GAC, and then you can write custom code to load the assembly and register the rule. In a production environment, you should use a procedure that is more robust. In this case, the rule will probably be installed by someone else, such as a server farm administrator, and it will very likely be installed on multiple servers, not only the server that you use for development.

The best way to register a rule with SharePoint Health Analyzer in a production environment is to create a SharePoint Feature for the purpose. The key to this technique is to include, as part of the rule assembly, event handlers for the FeatureActivated and FeatureDeactivating events. When a server farm administrator installs the Feature, your event handlers are registered with the system. When a farm administrator activates the Feature, code in your FeatureActivated event handler can call the RegisterRules(Assembly) method to register the rule. When a server farm administrator deactivates the Feature, code in your FeatureDeactivating event handler can call the UnregisterRules(Assembly) method to remove the rule.

This topic explains how to create event handlers that register and unregister a rule, and how to include event handlers and the rule assembly in a farm-level Feature. For information about deploying the Feature and installing the rule assembly in the GAC, see How to: Deploy a Health Rule with a Solution Package.

To create event handlers that register and unregister a health rule

  1. Open Visual Studio as an administrator by right-clicking the program in the Start menu and selecting Run as administrator.

  2. Open the project that contains the code for your health rule.

  3. Add a new class to the project.

    In Solution Explorer, select the project name, choose Add, then New Item…. In the Add New Item dialog, choose the Class template. Name the class RuleFeatureReceiver. Then click Add.

  4. Add using statements (Imports in Visual Basic) for the namespaces shown in the following example.

    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration.Health;
    
    Imports System
    Imports System.Collections.Generic
    Imports System.Reflection
    Imports Microsoft.SharePoint
    Imports Microsoft.SharePoint.Administration.Health
    
  5. Modify the class declaration so that the class inherits from the SPFeatureReceiver class.

    class RuleFeatureReceiver : SPFeatureReceiver
    
    Public Class RuleFeatureReceiver
        Inherits SPFeatureReceiver
    
  6. Override and implement the FeatureActivated(SPFeatureReceiverProperties) method, as shown in the following example.

    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        Assembly a = Assembly.GetExecutingAssembly();
        IDictionary<Type, Exception> exceptions = SPHealthAnalyzer.RegisterRules(a);
    
        if (exceptions != null)
        {
            string logEntry = a.FullName;
            if (exceptions.Count == 0)
            {
                logEntry += " All rules were registered.";
            }
            else
            {
                foreach (KeyValuePair<Type, Exception> pair in exceptions)
                {
                    logEntry += string.Format(" Registration failed for type {0}. {1}",
                                              pair.Key, pair.Value.Message);
                }
            }
            System.Diagnostics.Trace.WriteLine(logEntry);
        }
    }
    
    Public Overrides Sub FeatureActivated(ByVal properties As Microsoft.SharePoint.SPFeatureReceiverProperties)
    
        Dim a As Assembly = Assembly.GetExecutingAssembly()
        Dim exceptions As IDictionary(Of Type, Exception) = SPHealthAnalyzer.RegisterRules(a)
    
        If Not exceptions Is Nothing Then
            Dim logEntry As String = a.FullName
            If exceptions.Count = 0 Then
                logEntry += " All rules were registered."
            Else
                Dim pair As KeyValuePair(Of Type, Exception)
                For Each pair In exceptions
                    logEntry += String.Format(" Registration failed for type {0}. {1}", _
                                                  pair.Key, pair.Value.Message)
                Next
            End If
            System.Diagnostics.Trace.WriteLine(logEntry)
        End If
    
    End Sub
    
  7. Override and implement the FeatureDeactivating(SPFeatureReceiverProperties) method, as shown in the following example.

    public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
    {
        Assembly a = Assembly.GetExecutingAssembly();
        IDictionary<Type, Exception> exceptions = SPHealthAnalyzer.UnregisterRules(a);
    
        if (exceptions != null)
        {
            string logEntry = a.FullName;
            if (exceptions.Count == 0)
            {
                logEntry += " All rules were unregistered.";
            }
            else
            {
                foreach (KeyValuePair<Type, Exception> pair in exceptions)
                {
                    logEntry += string.Format(" Unregistration failed for type {0}. {1}",
                                              pair.Key, pair.Value.Message);
                }
            }
            System.Diagnostics.Trace.WriteLine(logEntry);
        }
    }
    
    Public Overrides Sub FeatureDeactivating(ByVal properties As Microsoft.SharePoint.SPFeatureReceiverProperties)
    
        Dim a As Assembly = Assembly.GetExecutingAssembly()
        Dim exceptions As IDictionary(Of Type, Exception) = SPHealthAnalyzer.UnregisterRules(a)
    
        If Not exceptions Is Nothing Then
            Dim logEntry As String = a.FullName
            If exceptions.Count = 0 Then
                logEntry += " All rules were unregistered."
            Else
                Dim pair As KeyValuePair(Of Type, Exception)
                For Each pair In exceptions
                    logEntry += String.Format(" Unregistration failed for type {0}. {1}", _
                                                  pair.Key, pair.Value.Message)
                Next
            End If
            System.Diagnostics.Trace.WriteLine(logEntry)
        End If
    
    End Sub
    
  8. Build the project.

To create a Feature that installs a health rule

  1. Create a Features folder.

    In Solution Explorer, right-click the project name, select Add, and then select New Folder. Type Features.

  2. Create a subfolder for your feature.

    Right-click the Features folder, select Add, and then select New Folder. Type the name of your feature (for example, CompanyName.HealthRules).

    Later, when you create a solution package to deploy the Feature, a folder with the same name is created in the %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\FEATURES folder of every server in the server farm. The name that you give the folder can help administrators locate the definition file for your Feature.

  3. Create a feature definition file.

    Right-click the subfolder for your feature, select Add, and then select New Item.... In the Add New Item dialog, select the XML File template. Name the file Feature.xml. Then click Add.

  4. Open Feature.xml in the editor.

  5. Delete the first (and only) line in the file. In its place, paste the following code.

    <Feature xmlns="https://schemas.microsoft.com/sharepoint/"
             Scope="Farm"
             Hidden="FALSE"
             Title="Your Title"
             Description="Your description"
             Id="00000000-0000-0000-0000-000000000000"
             ReceiverAssembly="<assembly name>, Version=<number>, Culture=<culture>, PublicKeyToken=<token>"
             ReceiverClass="MyNamespace.RuleFeatureReceiver"
             AlwaysForceInstall="TRUE"
             ImageUrl=""/>
    
  6. In Feature.xml, replace the values of the Title and Description attributes with your own text.

  7. Replace the value of the Id attribute with a newly generated GUID (without braces).

    You can use the GuidGen Tool (guidgen.exe) to get a new GUID. On the Tools menu in Visual Studio, choose Create GUID. In the Create GUID dialog, select 4. Registry Format, then click Copy. Paste the content of the clipboard between the quotation marks after the Id attribute. Remove the braces from the GUID.

  8. Replace the value of the ReceiverAssembly attribute with the full, four-part name of your assembly.

    For information about how to get the full name of your assembly, see How to: Create a Tool to Get the Full Name of an Assembly.

  9. Replace the value of the ReceiverClass attribute with the namespace-qualified name of your SPFeatureReceiver subclass.

  10. Save the file.

For information about how to deploy the Feature, see How to: Deploy a Health Rule with a Solution Package.

See Also

Tasks

How to: Deploy a Health Rule with a Solution Package

How to: Create a Tool to Get the Full Name of an Assembly

Concepts

Using Features in SharePoint Foundation