Názorný postup: Vytváření vlastní procesor směrnice
Směrnice procesory přidáním kódu do práce generována třída transformace.Pokud zavoláte směrnice z text šablony, zbývající kód, který píšete do textu šablony lze spoléhat na funkce, které poskytuje směrnice.
Můžete napsat vlastní směrnice procesorů.Umožňuje přizpůsobit text šablony.Chcete-li vytvořit vlastní procesor směrnice vytvořit třídu, která dědí buď z DirectiveProcessor nebo RequiresProvidesDirectiveProcessor.
Následující úkoly, které jsou uvedeny v tomto návodu:
Vytvoření vlastní procesor směrnice
Registrace směrnice procesoru
Testování směrnice procesoru
Požadavky
K dokončení toho návodu budete potřebovat:
Visual Studio 2010,
Visual Studio 2010 SDK
Vytvoření vlastní procesor směrnice
V tomto postupu vytvoříte vlastní procesor směrnice.Přidat vlastní směrnice, který přečte soubor XML, uloží jej v XmlDocument proměnné a zpřístupní prostřednictvím vlastnosti.V části "Testování směrnice zpracovatelem" pomocí této vlastnosti v šabloně text pro přístup k souboru XML.
Volání vašeho vlastního směrnice vypadá následovně:
<#@ CoolDirective Processor="CustomDirectiveProcessor" FileName="<Your Path>DocFile.xml" #>
Vlastnost proměnné a přidá vlastní směrnice procesor třídy vygenerované transformace.Směrnice psaní používá System.CodeDom třídy vytvořit kód, který přidá třídy vygenerované transformace motoru.System.CodeDom Třídy vytvořit kód v obou Visual C# nebo Visual Basicv závislosti na jazyce zadaném v language parametr template směrnice.Jazyk směrnice procesoru a jazyk textu šablony, která přistupuje k směrnice procesoru nemusí odpovídat.
Kód, který vytváří směrnice vypadá následovně:
private System.Xml.XmlDocument document0Value;
public virtual System.Xml.XmlDocument Document0
{
get
{
if ((this.document0Value == null))
{
this.document0Value = XmlReaderHelper.ReadXml(<FileNameParameterValue>);
}
return this.document0Value;
}
}
Private document0Value As System.Xml.XmlDocument
Public Overridable ReadOnly Property Document0() As System.Xml.XmlDocument
Get
If (Me.document0Value Is Nothing) Then
Me.document0Value = XmlReaderHelper.ReadXml(<FileNameParameterValue>)
End If
Return Me.document0Value
End Get
End Property
Vytvořit vlastní procesor směrnice
V aplikaci Visual Studio vytvořte C# nebo projektu knihovny třídy jazyka Visual Basic s názvem CustomDP.
[!POZNÁMKA]
Pokud chcete nainstalovat směrnice procesor na více než jednom počítači, je vhodnější použít Visual Studio rozšíření (VSIX) projektu a zahrnout do rozšíření souboru .pkgdef.Další informace naleznete v tématu Zavedení směrnice vlastní procesor.
Přidáte odkazy na sestavení:
Microsoft.VisualStudio.TextTemplating.11.0
Microsoft.VisualStudio.TextTemplating.Interfaces.11.0
Nahradit kód v Class1 s následujícím kódem.Tento kód definuje, které dědí z třídy CustomDirectiveProcessor DirectiveProcessor třídy a implementuje nezbytné metody.
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; using Microsoft.VisualStudio.TextTemplating; namespace CustomDP { public class CustomDirectiveProcessor : DirectiveProcessor { //this buffer stores the code that is added to the //generated transformation class after all the processing is done //--------------------------------------------------------------------- private StringBuilder codeBuffer; //Using a Code Dom Provider creates code for the //generated transformation class in either Visual Basic or C#. //If you want your directive processor to support only one language, you //can hard code the code you add to the generated transformation class. //In that case, you do not need this field. //-------------------------------------------------------------------------- private CodeDomProvider codeDomProvider; //this stores the full contents of the text template that is being processed //-------------------------------------------------------------------------- private String templateContents; //These are the errors that occur during processing. The engine passes //the errors to the host, and the host can decide how to display them, //for example the the host can display the errors in the UI //or write them to a file. //--------------------------------------------------------------------- private CompilerErrorCollection errorsValue; public new CompilerErrorCollection Errors { get { return errorsValue; } } //Each time this directive processor is called, it creates a new property. //We count how many times we are called, and append "n" to each new //property name. The property names are therefore unique. //----------------------------------------------------------------------------- private int directiveCount = 0; public override void Initialize(ITextTemplatingEngineHost host) { //we do not need to do any initialization work } public override void StartProcessingRun(CodeDomProvider languageProvider, String templateContents, CompilerErrorCollection errors) { //the engine has passed us the language of the text template //we will use that language to generate code later //---------------------------------------------------------- this.codeDomProvider = languageProvider; this.templateContents = templateContents; this.errorsValue = errors; this.codeBuffer = new StringBuilder(); } //Before calling the ProcessDirective method for a directive, the //engine calls this function to see whether the directive is supported. //Notice that one directive processor might support many directives. //--------------------------------------------------------------------- public override bool IsDirectiveSupported(string directiveName) { if (string.Compare(directiveName, "CoolDirective", StringComparison.OrdinalIgnoreCase) == 0) { return true; } if (string.Compare(directiveName, "SuperCoolDirective", StringComparison.OrdinalIgnoreCase) == 0) { return true; } return false; } public override void ProcessDirective(string directiveName, IDictionary<string, string> arguments) { if (string.Compare(directiveName, "CoolDirective", StringComparison.OrdinalIgnoreCase) == 0) { string fileName; if (!arguments.TryGetValue("FileName", out fileName)) { throw new DirectiveProcessorException("Required argument 'FileName' not specified."); } if (string.IsNullOrEmpty(fileName)) { throw new DirectiveProcessorException("Argument 'FileName' is null or empty."); } //Now we add code to the generated transformation class. //This directive supports either Visual Basic or C#, so we must use the //System.CodeDom to create the code. //If a directive supports only one language, you can hard code the code. //-------------------------------------------------------------------------- CodeMemberField documentField = new CodeMemberField(); documentField.Name = "document" + directiveCount + "Value"; documentField.Type = new CodeTypeReference(typeof(XmlDocument)); documentField.Attributes = MemberAttributes.Private; CodeMemberProperty documentProperty = new CodeMemberProperty(); documentProperty.Name = "Document" + directiveCount; documentProperty.Type = new CodeTypeReference(typeof(XmlDocument)); documentProperty.Attributes = MemberAttributes.Public; documentProperty.HasSet = false; documentProperty.HasGet = true; CodeExpression fieldName = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), documentField.Name); CodeExpression booleanTest = new CodeBinaryOperatorExpression(fieldName, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)); CodeExpression rightSide = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("XmlReaderHelper"), "ReadXml", new CodePrimitiveExpression(fileName)); CodeStatement[] thenSteps = new CodeStatement[] { new CodeAssignStatement(fieldName, rightSide) }; CodeConditionStatement ifThen = new CodeConditionStatement(booleanTest, thenSteps); documentProperty.GetStatements.Add(ifThen); CodeStatement s = new CodeMethodReturnStatement(fieldName); documentProperty.GetStatements.Add(s); CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = true; options.IndentString = " "; options.VerbatimOrder = true; options.BracingStyle = "C"; using (StringWriter writer = new StringWriter(codeBuffer, CultureInfo.InvariantCulture)) { codeDomProvider.GenerateCodeFromMember(documentField, writer, options); codeDomProvider.GenerateCodeFromMember(documentProperty, writer, options); } }//end CoolDirective //One directive processor can contain many directives. //If you want to support more directives, the code goes here... //----------------------------------------------------------------- if (string.Compare(directiveName, "supercooldirective", StringComparison.OrdinalIgnoreCase) == 0) { //code for SuperCoolDirective goes here... }//end SuperCoolDirective //Track how many times the processor has been called. //----------------------------------------------------------------- directiveCount++; }//end ProcessDirective public override void FinishProcessingRun() { this.codeDomProvider = null; //important: do not do this: //the get methods below are called after this method //and the get methods can access this field //----------------------------------------------------------------- //this.codeBuffer = null; } public override string GetPreInitializationCodeForProcessingRun() { //Use this method to add code to the start of the //Initialize() method of the generated transformation class. //We do not need any pre-initialization, so we will just return "". //----------------------------------------------------------------- //GetPreInitializationCodeForProcessingRun runs before the //Initialize() method of the base class. //----------------------------------------------------------------- return String.Empty; } public override string GetPostInitializationCodeForProcessingRun() { //Use this method to add code to the end of the //Initialize() method of the generated transformation class. //We do not need any post-initialization, so we will just return "". //------------------------------------------------------------------ //GetPostInitializationCodeForProcessingRun runs after the //Initialize() method of the base class. //----------------------------------------------------------------- return String.Empty; } public override string GetClassCodeForProcessingRun() { //Return the code to add to the generated transformation class. //----------------------------------------------------------------- return codeBuffer.ToString(); } public override string[] GetReferencesForProcessingRun() { //This returns the references that we want to use when //compiling the generated transformation class. //----------------------------------------------------------------- //We need a reference to this assembly to be able to call //XmlReaderHelper.ReadXml from the generated transformation class. //----------------------------------------------------------------- return new string[] { "System.Xml", this.GetType().Assembly.Location }; } public override string[] GetImportsForProcessingRun() { //This returns the imports or using statements that we want to //add to the generated transformation class. //----------------------------------------------------------------- //We need CustomDP to be able to call XmlReaderHelper.ReadXml //from the generated transformation class. //----------------------------------------------------------------- return new string[] { "System.Xml", "CustomDP" }; } }//end class CustomDirectiveProcessor //------------------------------------------------------------------------- // the code that we are adding to the generated transformation class // will call this method //------------------------------------------------------------------------- public static class XmlReaderHelper { public static XmlDocument ReadXml(string fileName) { XmlDocument d = new XmlDocument(); using (XmlTextReader reader = new XmlTextReader(fileName)) { try { d.Load(reader); } catch (System.Xml.XmlException e) { throw new DirectiveProcessorException("Unable to read the XML file.", e); } } return d; } }//end class XmlReaderHelper }//end namespace CustomDP
Imports System Imports System.CodeDom Imports System.CodeDom.Compiler Imports System.Collections.Generic Imports System.Globalization Imports System.IO Imports System.Text Imports System.Xml Imports System.Xml.Serialization Imports Microsoft.VisualStudio.TextTemplating Namespace CustomDP Public Class CustomDirectiveProcessor Inherits DirectiveProcessor 'this buffer stores the code that is added to the 'generated transformation class after all the processing is done '--------------------------------------------------------------- Private codeBuffer As StringBuilder 'Using a Code Dom Provider creates code for the 'generated transformation class in either Visual Basic or C#. 'If you want your directive processor to support only one language, you 'can hard code the code you add to the generated transformation class. 'In that case, you do not need this field. '-------------------------------------------------------------------------- Private codeDomProvider As CodeDomProvider 'this stores the full contents of the text template that is being processed '-------------------------------------------------------------------------- Private templateContents As String 'These are the errors that occur during processing. The engine passes 'the errors to the host, and the host can decide how to display them, 'for example the the host can display the errors in the UI 'or write them to a file. '--------------------------------------------------------------------- Private errorsValue As CompilerErrorCollection Public Shadows ReadOnly Property Errors() As CompilerErrorCollection Get Return errorsValue End Get End Property 'Each time this directive processor is called, it creates a new property. 'We count how many times we are called, and append "n" to each new 'property name. The property names are therefore unique. '-------------------------------------------------------------------------- Private directiveCount As Integer = 0 Public Overrides Sub Initialize(ByVal host As ITextTemplatingEngineHost) 'we do not need to do any initialization work End Sub Public Overrides Sub StartProcessingRun(ByVal languageProvider As CodeDomProvider, ByVal templateContents As String, ByVal errors As CompilerErrorCollection) 'the engine has passed us the language of the text template 'we will use that language to generate code later '---------------------------------------------------------- Me.codeDomProvider = languageProvider Me.templateContents = templateContents Me.errorsValue = errors Me.codeBuffer = New StringBuilder() End Sub 'Before calling the ProcessDirective method for a directive, the 'engine calls this function to see whether the directive is supported. 'Notice that one directive processor might support many directives. '--------------------------------------------------------------------- Public Overrides Function IsDirectiveSupported(ByVal directiveName As String) As Boolean If String.Compare(directiveName, "CoolDirective", StringComparison.OrdinalIgnoreCase) = 0 Then Return True End If If String.Compare(directiveName, "SuperCoolDirective", StringComparison.OrdinalIgnoreCase) = 0 Then Return True End If Return False End Function Public Overrides Sub ProcessDirective(ByVal directiveName As String, ByVal arguments As IDictionary(Of String, String)) If String.Compare(directiveName, "CoolDirective", StringComparison.OrdinalIgnoreCase) = 0 Then Dim fileName As String If Not (arguments.TryGetValue("FileName", fileName)) Then Throw New DirectiveProcessorException("Required argument 'FileName' not specified.") End If If String.IsNullOrEmpty(fileName) Then Throw New DirectiveProcessorException("Argument 'FileName' is null or empty.") End If 'Now we add code to the generated transformation class. 'This directive supports either Visual Basic or C#, so we must use the 'System.CodeDom to create the code. 'If a directive supports only one language, you can hard code the code. '-------------------------------------------------------------------------- Dim documentField As CodeMemberField = New CodeMemberField() documentField.Name = "document" & directiveCount & "Value" documentField.Type = New CodeTypeReference(GetType(XmlDocument)) documentField.Attributes = MemberAttributes.Private Dim documentProperty As CodeMemberProperty = New CodeMemberProperty() documentProperty.Name = "Document" & directiveCount documentProperty.Type = New CodeTypeReference(GetType(XmlDocument)) documentProperty.Attributes = MemberAttributes.Public documentProperty.HasSet = False documentProperty.HasGet = True Dim fieldName As CodeExpression = New CodeFieldReferenceExpression(New CodeThisReferenceExpression(), documentField.Name) Dim booleanTest As CodeExpression = New CodeBinaryOperatorExpression(fieldName, CodeBinaryOperatorType.IdentityEquality, New CodePrimitiveExpression(Nothing)) Dim rightSide As CodeExpression = New CodeMethodInvokeExpression(New CodeTypeReferenceExpression("XmlReaderHelper"), "ReadXml", New CodePrimitiveExpression(fileName)) Dim thenSteps As CodeStatement() = New CodeStatement() {New CodeAssignStatement(fieldName, rightSide)} Dim ifThen As CodeConditionStatement = New CodeConditionStatement(booleanTest, thenSteps) documentProperty.GetStatements.Add(ifThen) Dim s As CodeStatement = New CodeMethodReturnStatement(fieldName) documentProperty.GetStatements.Add(s) Dim options As CodeGeneratorOptions = New CodeGeneratorOptions() options.BlankLinesBetweenMembers = True options.IndentString = " " options.VerbatimOrder = True options.BracingStyle = "VB" Using writer As StringWriter = New StringWriter(codeBuffer, CultureInfo.InvariantCulture) codeDomProvider.GenerateCodeFromMember(documentField, writer, options) codeDomProvider.GenerateCodeFromMember(documentProperty, writer, options) End Using End If 'CoolDirective 'One directive processor can contain many directives. 'If you want to support more directives, the code goes here... '----------------------------------------------------------------- If String.Compare(directiveName, "supercooldirective", StringComparison.OrdinalIgnoreCase) = 0 Then 'code for SuperCoolDirective goes here End If 'SuperCoolDirective 'Track how many times the processor has been called. '----------------------------------------------------------------- directiveCount += 1 End Sub 'ProcessDirective Public Overrides Sub FinishProcessingRun() Me.codeDomProvider = Nothing 'important: do not do this: 'the get methods below are called after this method 'and the get methods can access this field '----------------------------------------------------------------- 'Me.codeBuffer = Nothing End Sub Public Overrides Function GetPreInitializationCodeForProcessingRun() As String 'Use this method to add code to the start of the 'Initialize() method of the generated transformation class. 'We do not need any pre-initialization, so we will just return "". '----------------------------------------------------------------- 'GetPreInitializationCodeForProcessingRun runs before the 'Initialize() method of the base class. '----------------------------------------------------------------- Return String.Empty End Function Public Overrides Function GetPostInitializationCodeForProcessingRun() As String 'Use this method to add code to the end of the 'Initialize() method of the generated transformation class. 'We do not need any post-initialization, so we will just return "". '------------------------------------------------------------------ 'GetPostInitializationCodeForProcessingRun runs after the 'Initialize() method of the base class. '----------------------------------------------------------------- Return String.Empty End Function Public Overrides Function GetClassCodeForProcessingRun() As String 'Return the code to add to the generated transformation class. '----------------------------------------------------------------- Return codeBuffer.ToString() End Function Public Overrides Function GetReferencesForProcessingRun() As String() 'This returns the references that we want to use when 'compiling the generated transformation class. '----------------------------------------------------------------- 'We need a reference to this assembly to be able to call 'XmlReaderHelper.ReadXml from the generated transformation class. '----------------------------------------------------------------- Return New String() {"System.Xml", Me.GetType().Assembly.Location} End Function Public Overrides Function GetImportsForProcessingRun() As String() 'This returns the imports or using statements that we want to 'add to the generated transformation class. '----------------------------------------------------------------- 'We need CustomDP to be able to call XmlReaderHelper.ReadXml 'from the generated transformation class. '----------------------------------------------------------------- Return New String() {"System.Xml", "CustomDP"} End Function End Class 'CustomDirectiveProcessor '-------------------------------------------------------------------------- ' the code that we are adding to the generated transformation class ' will call this method '-------------------------------------------------------------------------- Public Class XmlReaderHelper Public Shared Function ReadXml(ByVal fileName As String) As XmlDocument Dim d As XmlDocument = New XmlDocument() Using reader As XmlTextReader = New XmlTextReader(fileName) Try d.Load(reader) Catch e As System.Xml.XmlException Throw New DirectiveProcessorException("Unable to read the XML file.", e) End Try End Using Return d End Function End Class 'XmlReaderHelper End Namespace
Pro Visual Basic , otevřete projektu nabídce a klepněte na CustomDP vlastnosti.Na aplikace karta v kořenový obor názvů, odstraňte výchozí hodnotu CustomDP.
V nabídce Soubor klikněte na příkaz Uložit vše.
V nabídce Sestavení klikněte na příkaz Sestavit řešení.
Vytvořte projekt
Projekt sestavte.V nabídce Sestavení klikněte na příkaz Sestavit řešení.
Registrace směrnice procesoru
Než zavoláte směrnice ze šablony text v Visual Studio, je nutné přidat klíč registru pro procesor směrnice.
[!POZNÁMKA]
Pokud chcete nainstalovat směrnice procesor na více než jednom počítači, je lépe definovat Visual Studio rozšíření (VSIX), který obsahuje soubor .pkgdef spolu s vaší sestavení.Další informace naleznete v tématu Zavedení směrnice vlastní procesor.
Klávesy pro procesory směrnice existují v registru v následujícím umístění:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\11.0\TextTemplating\DirectiveProcessors
Pro 64bitové systémy je umístění registru:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\11.0\TextTemplating\DirectiveProcessors
V této části Přidání klíče pro vlastní procesor směrnice do registru ve stejném umístění.
Upozornění |
---|
Nesprávná úprava registru může vážně poškodit systém.Před prováděním změn v registru zálohujte veškerá cenná data, která je v počítači. |
Přidání klíče registru pro procesor směrnice
Spustit regedit příkazu pomocí nabídky Start nebo pomocí příkazového řádku.
Přejděte do umístění HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\11.0\TextTemplating\DirectiveProcessorsa klepněte na uzel.
Použijte na 64bitové systémyHKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\11.0\TextTemplating\DirectiveProcessors
Přidáte nový klíč s názvem CustomDirectiveProcessor.
[!POZNÁMKA]
Toto je název, který budete používat v poli vlastní direktivy procesoru.Tento název se nemusí shodovat s názvem směrnice název třídy procesoru směrnice nebo směrnice procesoru oboru názvů.
Přidáte novou řetězcovou hodnotu s názvem třídy, která má hodnotu pro název nový řetězec CustomDP.CustomDirectiveProcessor.
Přidáte novou řetězcovou hodnotu s názvem CodeBase, který má hodnotu, která se rovná cesta CustomDP.dll, který jste vytvořili dříve v tomto.
Například cesta může vypadat C:\UserFiles\CustomDP\bin\Debug\CustomDP.dll.
Klíč registru by měla mít následující hodnoty:
Název
Type
Data
(Výchozí)
REG_SZ
(hodnota není zadána)
Třída
REG_SZ
CustomDP.CustomDirectiveProcessor
CodeBase
REG_SZ
< cesta k řešení > CustomDP\bin\Debug\CustomDP.dll
Pokud jste v modulu GAC sestavení, hodnoty by měl vypadat takto:
Název
Type
Data
(Výchozí)
REG_SZ
(hodnota není zadána)
Třída
REG_SZ
CustomDP.CustomDirectiveProcessor
Sestavení
REG_SZ
CustomDP.dll
Restartujte aplikaci Visual Studio.
Testování směrnici procesoru
Chcete-li otestovat směrnice procesoru potřebujete napsat text šablony, který jej volá.
V tomto příkladu text šablony zavolá směrnice a předá jménem souboru XML, který obsahuje dokumentaci, soubor třídy.Další informace naleznete v tématu Komentáře XML dokumentace (Příručka programování C#).
Potom použije text šablony XmlDocument vlastnost, která směrnice vytvoří přechod XML a tisknout komentáře k dokumentaci.
Vytvořit soubor XML pro použití v testování směrnice procesoru
Vytvořte textový soubor s názvem DocFile.xml pomocí libovolného textového editoru (například Poznámkový blok).
[!POZNÁMKA]
Tento soubor můžete vytvořit na libovolném místě (například C:\Test\DocFile.xml).
Text souboru přidejte následující:
<?xml version="1.0"?> <doc> <assembly> <name>xmlsample</name> </assembly> <members> <member name="T:SomeClass"> <summary>Class level summary documentation goes here.</summary> <remarks>Longer comments can be associated with a type or member through the remarks tag</remarks> </member> <member name="F:SomeClass.m_Name"> <summary>Store for the name property</summary> </member> <member name="M:SomeClass.#ctor"> <summary>The class constructor.</summary> </member> <member name="M:SomeClass.SomeMethod(System.String)"> <summary>Description for SomeMethod.</summary> <param name="s">Parameter description for s goes here</param> <seealso cref="T:System.String">You can use the cref attribute on any tag to reference a type or member and the compiler will check that the reference exists.</seealso> </member> <member name="M:SomeClass.SomeOtherMethod"> <summary>Some other method.</summary> <returns>Return results are described through the returns tag.</returns> <seealso cref="M:SomeClass.SomeMethod(System.String)">Notice the use of the cref attribute to reference a specific method</seealso> </member> <member name="M:SomeClass.Main(System.String[])"> <summary>The entry point for the application.</summary> <param name="args">A list of command line arguments</param> </member> <member name="P:SomeClass.Name"> <summary>Name property</summary> <value>A value tag is used to describe the property value</value> </member> </members> </doc>
Soubor uložte a zavřete.
Vytvoření šablony text testování směrnice procesoru
V aplikaci Visual Studio C# nebo vytvořte projekt knihovny třídy Visual Basic s názvem TemplateTest.
Přidání nového souboru text šablony s názvem TestDP.tt.
Ujistěte se, že Vlastní nástroj je vlastnost TestDP.tt nastavena na TextTemplatingFileGenerator.
Změníte obsah TestDP.tt v následujícím textu.
[!POZNÁMKA]
Nezapomeňte nahradit řetězec <YOUR PATH> s cestou k souboru DocFile.xml.
Jazyk šablony text nemá s jazykem směrnice procesoru.
<#@ assembly name="System.Xml" #> <#@ template debug="true" #> <#@ output extension=".txt" #> <# //This will call the custom directive processor. #> <#@ CoolDirective Processor="CustomDirectiveProcessor" FileName="<YOUR PATH>\DocFile.xml" #> <# //Uncomment this line if you want to see the generated transformation class. #> <# //System.Diagnostics.Debugger.Break(); #> <# //This will use the results of the directive processor. #> <# //The directive processor has read the XML and stored it in Document0. #> <# XmlNode node = Document0.DocumentElement.SelectSingleNode("members"); foreach (XmlNode member in node.ChildNodes) { XmlNode name = member.Attributes.GetNamedItem("name"); WriteLine("{0,7}: {1}", "Name", name.Value); foreach (XmlNode comment in member.ChildNodes) { WriteLine("{0,7}: {1}", comment.Name, comment.InnerText); } WriteLine(""); } #> <# //You can call the directive processor again and pass it a different file. #> <# //@ CoolDirective Processor="CustomDirectiveProcessor" FileName="<YOUR PATH>\<Your Second File>" #> <# //To use the results of the second directive call, use Document1. #> <# //XmlNode node2 = Document1.DocumentElement.SelectSingleNode("members"); //... #>
<#@ assembly name="System.Xml" #> <#@ template debug="true" language="vb" #> <#@ output extension=".txt" #> <# 'This will call the custom directive processor. #> <#@ CoolDirective Processor="CustomDirectiveProcessor" FileName="<YOUR PATH>\DocFile.xml" #> <# 'Uncomment this line if you want to see the generated transformation class. #> <# 'System.Diagnostics.Debugger.Break() #> <# 'This will use the results of the directive processor. #> <# 'The directive processor has read the XML and stored it in Document0. #> <# Dim node as XmlNode = Document0.DocumentElement.SelectSingleNode("members") Dim member As XmlNode For Each member In node.ChildNodes Dim name As XmlNode = member.Attributes.GetNamedItem("name") WriteLine("{0,7}: {1}", "Name", name.Value) Dim comment As XmlNode For Each comment In member.ChildNodes WriteLine("{0,7}: {1}", comment.Name, comment.InnerText) Next WriteLine("") Next #> <# 'You can call the directive processor again and pass it a different file. #> <# '@ CoolDirective Processor="CustomDirectiveProcessor" FileName="<YOUR PATH>\DocFileTwo.xml" #> <# 'To use the results of the second directive call, use Document1. #> <# 'node = Document1.DocumentElement.SelectSingleNode("members") '... #>
[!POZNÁMKA]
Například hodnota Processor parametr je CustomDirectiveProcessor.Hodnota Processor parametru musí odpovídat názvu klíče registru procesoru.
V nabídce Soubor klikněte na příkaz Uložit vše.
Testování směrnice procesoru
V Aplikaci Solution Explorer, TestDP.tt tlačítkem a potom klepněte na tlačítko Spustit vlastní nástroje.
Pro Visual Basic uživatelé, TestDP.txt nemusí v Aplikaci Solution Explorer ve výchozím nastavení.Chcete-li zobrazit všechny soubory, které jsou přiřazeny k projektu, otevřete projektu nabídce a klepněte na Zobrazit všechny soubory.
V Aplikaci Solution Explorer, rozbalte uzel TestDP.txt a poklepejte na položku otevřít v editoru TestDP.txt.
Zobrazí se výstup generovaný text.Výstup by měl vypadat takto:
Name: T:SomeClass summary: Class level summary documentation goes here. remarks: Longer comments can be associated with a type or member through the remarks tag Name: F:SomeClass.m_Name summary: Store for the name property Name: M:SomeClass.#ctor summary: The class constructor. Name: M:SomeClass.SomeMethod(System.String) summary: Description for SomeMethod. param: Parameter description for s goes here seealso: You can use the cref attribute on any tag to reference a type or member and the compiler will check that the reference exists. Name: M:SomeClass.SomeOtherMethod summary: Some other method. returns: Return results are described through the returns tag. seealso: Notice the use of the cref attribute to reference a specific method Name: M:SomeClass.Main(System.String[]) summary: The entry point for the application. param: A list of command line arguments Name: P:SomeClass.Name summary: Name property value: A value tag is used to describe the property value
Přidání HTML generovaný Text
Po otestování vlastní procesor směrnice můžete přidat některé HTML generovaný text.
Přidat HTML generovaný text
Nahraďte následující kód v TestDP.tt.HTML je zvýrazněný.Nezapomeňte nahradit řetězec YOUR PATH s cestou k souboru DocFile.xml.
[!POZNÁMKA]
Otevřít další < # a # zavřít > značky kód příkazu oddělit od značky jazyka HTML.
<#@ assembly name="System.Xml" #> <#@ template debug="true" #> <#@ output extension=".htm" #> <# //this will call the custom directive processor #> <#@ CoolDirective Processor="CustomDirectiveProcessor" FileName="<YOUR PATH>\DocFile.xml" #> <# //uncomment this line if you want to see the generated transformation class #> <# //System.Diagnostics.Debugger.Break(); #> <html> <body> <# //this will use the results of the directive processor #> <# //the directive processor has read the XML and stored it in Document0#> <# XmlNode node = Document0.DocumentElement.SelectSingleNode("members"); foreach (XmlNode member in node.ChildNodes) { #> <h3> <# XmlNode name = member.Attributes.GetNamedItem("name"); WriteLine("{0,7}: {1}", "Name", name.Value); #> </h3> <# foreach (XmlNode comment in member.ChildNodes) { WriteLine("{0,7}: {1}", comment.Name, comment.InnerText); #> <br/> <# } } #> </body> </html>
<#@ assembly name="System.Xml" #> <#@ template debug="true" language="vb" #> <#@ output extension=".htm" #> <# 'this will call the custom directive processor #> <#@ CoolDirective Processor="CustomDirectiveProcessor" FileName="<YOUR PATH>\DocFile.xml" #> <# 'uncomment this line if you want to see the generated transformation class #> <# 'System.Diagnostics.Debugger.Break() #> <html> <body> <# 'this will use the results of the directive processor #> <# 'the directive processor has read the XML and stored it in Document0#> <# Dim node as XmlNode = Document0.DocumentElement.SelectSingleNode("members") Dim member As XmlNode For Each member In node.ChildNodes #> <h3> <# Dim name As XmlNode = member.Attributes.GetNamedItem("name") WriteLine("{0,7}: {1}", "Name", name.Value) #> </h3> <# Dim comment As XmlNode For Each comment In member.ChildNodes WriteLine("{0,7}: {1}", comment.Name, comment.InnerText) #> <br/> <# Next Next #> </body> </html>
Na soubor nabídky, klepněte na tlačítko Uložit TestDP.txt.
Zobrazit výstup v prohlížeči, v Aplikaci Solution Explorer, TestDP.htm, klepněte a Zobrazení V prohlížeči.
Výstup by měl být stejný jako původní text s výjimkou by měla mít formát HTML.Každý název položky by se zobrazí tučně.