Walkthrough: Using an Assembly in a Text Template

You can use text templates to generate code, text or HTML artifacts. For more information, see Generating Artifacts Using Text Templates. By using the assembly directive in a text template, you can reference an assembly and then use the types and members from that assembly in your text template code. For example, in this walkthrough, you will use an assembly that accepts a person's birth date in string format, and then returns that person's age by using an integer value.

Tasks illustrated in this walkthrough include:

  • How to create a basic assembly.

  • How to create a text template.

  • How to use the assembly in the text template.

Prerequisites

To complete this walkthrough, you will need:

Creating a Basic Assembly

First you will create a basic assembly to use in your text template.

注意

You will create this assembly for testing purposes only. You can use the assembly directive to reference any existing assembly.

The assembly will have one class, called CustomFunctions, and one method, called GetAge. GetAge will accept a person's birth date in string form and return the person's age.

To create a simple assembly

  1. On the File menu, point to New, and then click Project.

    The New Project dialog box appears.

  2. Under Project types, click the Visual Basic or Visual C# node, according to your preference.

  3. Under Visual Studio installed templates, click Class Library.

  4. In Name, type CustomAssembly, and click OK.

    The system creates a class library project.

  5. In Solution Explorer, double-click Class1.

    This file will have a .cs or .vb extension, based on which language you specified when the project was created.

  6. Replace the code in Class1 with the following code:

    using System;
    
    namespace CustomAssembly
    {
        public static class CustomFunctions
        {
            public static int GetAge(string birthDate)
            {
                DateTime birth;
    
                try
                {
                    birth = DateTime.Parse(birthDate);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException("Unable to read birth date.", ex);
                }
    
                if (DateTime.Today.Month < birth.Month)  //it is before your birthday
                {
                    return DateTime.Today.Year - birth.Year - 1;
                }
                else if (DateTime.Today.Month > birth.Month)  //it is after your birthday
                {
                    return DateTime.Today.Year - birth.Year;
                }
                else // DateTime.Today.Month == birth.Month  //we don't know yet
                {
                    if (DateTime.Today.Day < birth.Day)  //it is before your birthday
                    {
                        return DateTime.Today.Year - birth.Year - 1;
                    }
                    else //it is your birthday, or it is after your birthday
                    {
                        return DateTime.Today.Year - birth.Year;
                    }
                }
            }
        }
    }
    
    Imports System
    
    Public Class CustomFunctions
    
        Public Shared Function GetAge(ByVal birthDate As String) As Integer
    
            Dim birth As DateTime
    
            Try
                birth = DateTime.Parse(birthDate)
    
            Catch ex As Exception
    
                Throw New ApplicationException("Unable to read birth date.", ex)
            End Try
    
            If (DateTime.Today.Month < birth.Month) Then  'it is before your birthday
    
                Return DateTime.Today.Year - birth.Year - 1
    
            ElseIf (DateTime.Today.Month > birth.Month) Then  'it is after your birthday
    
                Return DateTime.Today.Year - birth.Year
    
            Else ' DateTime.Today.Month == birth.Month  'we don't know yet
    
                If (DateTime.Today.Day < birth.Day) Then  'it is before your birthday
    
                    Return DateTime.Today.Year - birth.Year - 1
    
                Else 'it is your birthday, or it is after your birthday
    
                    Return DateTime.Today.Year - birth.Year
                End If
            End If
        End Function
    End Class
    
  7. On the File menu, click Save All.

  8. On the Build menu, click Build Solution.

  9. On the File menu, click Close Solution.

Creating a Text Template

Next, you will create a text template that uses the assembly.

To create a text template

  1. On the File menu, point to New, and then click Project.

    The New Project dialog box appears.

  2. Under Project types, click the Visual Basic or Visual C# node, according to your preference.

    注意

    The language of the text template does not need to match the language of the assembly.

  3. Under Visual Studio installed templates, click Class Library.

  4. In Name, type TemplateTest, and click OK.

    The system creates a class library project.

  5. On the Project menu, click Add New Item.

  6. Under Visual Studio installed templates, click Text File.

  7. In Name, type AssemblyTest.tt, and then click Add.

    注意

    When you generate a template, you will get a message that warns you not to run text templates from untrusted sources. If you do not want to see this message again, select the Do not show this message again check box, and click OK. Otherwise, click OK.

  8. In Solution Explorer, click the new text file AssemblyTest.tt.

    警告

    When you add the text file to the project, it will be highlighted in Solution Explorer but not selected. If you do not select the file, the following step will not work.

  9. On the View menu, click Properties Window.

  10. Be sure that you set the Custom Tool property to TextTemplatingFileGenerator.

  11. On the File menu, click Save All.

Using the Assembly in the Text Template

Finally, you will use the types and methods from the assembly in your text template.

To use the assembly in the text template

  1. Add the following directives to the top of AssemblyTest.tt to reference the assembly that you just created.

    注意

    The language of the text template does not need to match the language of the assembly.

    <#@ assembly name="<YOUR PATH>\CustomAssembly\CustomAssembly\bin\Debug\CustomAssembly.dll" #>
    <#@ import namespace="CustomAssembly" #>
    <#@ output extension="txt" #>
    
    <#@ assembly name="<YOUR PATH>\CustomAssembly\CustomAssembly\bin\Debug\CustomAssembly.dll" #>
    <#@ import namespace="CustomAssembly" #>
    <#@ template language="vb" #>
    <#@ output extension="txt" #>
    

    注意

    In addition to the assembly directive, we also have used the import directive to import a namespace from our assembly. These two directives are often used in conjunction.

  2. In the code, replace <YOUR PATH> with the path of your assembly.

    注意

    If your assembly is installed in the global assembly cache, you can just specify the name of the assembly.

  3. Add the following text block and statement to AssemblyTest.tt.

    This code calls the GetAge function in the referenced assembly.

    Welcome Ben Smith.
    <#
        int age = CustomFunctions.GetAge("10/9/1940");
    #>
    
    Welcome Ben Smith.
    <#
        Dim age as Integer = CustomFunctions.GetAge("10/9/1940")
    #>
    
  4. Add the following text block and expression to AssemblyTest.tt.

    This code displays the result of calling the GetAge function.

    Your current age is:
    <#= age #>
    
    Your current age is:
    <#= age #>
    
  5. In Solution Explorer, right-click AssemblyTest.tt, and then click Run Custom Tool.

  6. In Solution Explorer, expand AssemblyTest.tt, and then double-click AssemblyTest.txt to open it in the editor.

    The generated text output appears and looks like the following example:

    Welcome Ben Smith.

    Your current age is:

    65

Security

For more information, see Security of Text Templates.

Next Steps

If you have problems with your code, you might want to try some debugging. To debug text templates, you must set the debug parameter of the template directive. For more information, see How to: Debug Text Templates.

See Also

Concepts

Walkthrough: Creating and Running Text Templates

How to: Reference Assemblies in Text Templates

Directive Syntax (Domain-Specific Languages)

Domain-Specific Language Tools Glossary