如何:为 SharePoint 解决方案创建自定义功能和包验证规则

您可以创建自定义验证规则来验证 Visual Studio 生成的解决方案包。 可通过在**“打包资源管理器”中从包或功能的上下文菜单中选择“验证”**,对整个功能或包执行完全验证。 当您向项目中添加新的 SharePonit 项目项或功能时,将执行部分验证来确定包或功能是否将处于有效的状态。

创建自定义包验证规则

  1. 创建一个类库项目。

  2. 添加对下列程序集的引用:

    • Microsoft.VisualStudio.SharePoint

    • System.ComponentModel.Composition

  3. 创建实现以下接口之一的类:

  4. System.ComponentModel.Composition.ExportAttribute 添加到该类中。 此特性使 Visual Studio 能够发现并加载您的验证规则。 将 IPackageValidationRuleIFeatureValidationRule 类型传递到特性构造函数。

示例

下面的代码示例演示如何创建自定义功能验证规则。

Imports Microsoft.VisualStudio.SharePoint
Imports Microsoft.VisualStudio.SharePoint.Validation
Imports System.ComponentModel.Composition

<Export(GetType(IFeatureValidationRule))> _
Public Class CustomFeatureValidationRule
    Implements IFeatureValidationRule

    Public Sub ValidateFeature(ByVal context As IFeatureValidationContext) _
        Implements IFeatureValidationRule.ValidateFeature
        For Each projectItem In context.Feature.ProjectItems
            ValidateProjectItem(context, projectItem)
        Next projectItem
    End Sub

    Public Sub ValidateProjectItem(ByVal context As IFeatureValidationContext, _
        ByVal projectItem As ISharePointProjectItem) _
        Implements IFeatureValidationRule.ValidateProjectItem
        If projectItem.Name = "" Then
            context.RuleViolations.Add( _
                "CustomFeatureValidationRule001", _
                ValidationRuleViolationSeverity.Warning, _
                "SharePoint project items must have a name.")
        End If
    End Sub
End Class
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.SharePoint.Validation;
using System.ComponentModel.Composition;

namespace Extension
{
    [Export(typeof(IFeatureValidationRule))]
    internal class CustomFeatureValidationRule : IFeatureValidationRule
    {
        public void ValidateFeature(IFeatureValidationContext context)
        {
            foreach (var projectItem in context.Feature.ProjectItems)
            {
                ValidateProjectItem(context, projectItem);
            }
        }

        public void ValidateProjectItem(
            IFeatureValidationContext context,
            ISharePointProjectItem projectItem)
        {
            if (projectItem.Name == "")
            {
                context.RuleViolations.Add(
                    "CustomFeatureValidationRule001",
                    ValidationRuleViolationSeverity.Warning,
                    "SharePoint project items must have a name.");
            }
        }
    }
}

编译代码

此示例需要对以下程序集的引用:

  • Microsoft.VisualStudio.SharePoint。

  • System.ComponentModel.Composition。

部署扩展

若要部署扩展,请为要随此扩展分发的程序集和任何其他文件创建 Visual Studio 扩展 (VSIX) 包。 有关更多信息,请参见在 Visual Studio 中部署 SharePoint 工具扩展

请参见

其他资源

扩展 SharePoint 打包和部署