HOW TO:建立 SharePoint 方案的自訂功能和封裝驗證規則
您可以建立自訂驗證規則來驗證 Visual Studio 所產生的方案套件。您可以藉由從 [封裝總管] 中「封裝」或「功能」的內容功能表選取 [驗證],對整個「功能」或「封裝」執行完整驗證。當您將新的 SharePoint 專案項目或「功能」加入至專案來判斷「封裝」或「功能」是否為有效狀態時,會執行部分驗證。
若要建立自訂的「封裝」驗證規則
建立類別庫專案。
加入下列組件的參考:
Microsoft.VisualStudio.SharePoint
System.ComponentModel.Composition
建立會實作下列介面之一的類別:
若要建立「封裝」驗證規則,請實作 IPackageValidationRule 介面。
若要建立「功能」驗證規則,請實作 IFeatureValidationRule 介面。
將 System.ComponentModel.Composition.ExportAttribute 加入至類別。此屬性可讓 Visual Studio 探索並載入您的驗證規則。將 IPackageValidationRule 或 IFeatureValidationRule 型別傳遞至屬性建構函式。
範例
下列程式碼範例會示範如何建立自訂的「功能」驗證規則。
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 工具的擴充功能。