연습: 생성된 지시문 프로세서에 호스트 연결

텍스트 템플릿 처리를 직접 호스트를 작성할 수 있습니다.기본 사용자 지정 호스트를 확인할 수 있습니다 연습: 사용자 지정 텍스트 템플릿 호스트 만들기.여러 개의 출력 파일을 생성 하는 등의 기능을 추가 하려면 해당 호스트를 확장할 수 있습니다.

이 연습에서는 지시문 프로세서를 호출 하는 텍스트 템플릿을 지 원하는 사용자 지정 호스트를 확장 합니다.도메인 관련 언어를 정의 하면 생성 한 지시문 프로세서 도메인 모델에 대 한.지시문 프로세서 쉽게 사용자가 어셈블리를 작성 하 고 가져올 템플릿에서 지시문을 줄이기는 모델에 액세스 하는 서식 파일을 작성할 수 있습니다.

주의 정보주의

이 연습에서는 빌드 연습: 사용자 지정 텍스트 템플릿 호스트 만들기.이 연습에서는 먼저 수행 합니다.

이 연습에서는 다음 작업을 포함 됩니다.

  • 사용 하 여 도메인별 언어 도구 도메인 모델을 기반으로 하는 지시문 프로세서를 생성 합니다.

  • 사용자 정의 텍스트 템플릿 호스트 생성 된 지시문 프로세서에 연결 합니다.

  • 사용자 지정 호스트 생성 된 지시문 프로세서를 테스트 합니다.

사전 요구 사항

DSL을 정의 하려면 다음 구성 요소가 설치 되어 있어야:

Visual Studio

https://go.microsoft.com/fwlink/?LinkId=185579

Visual Studio SDK

https://go.microsoft.com/fwlink/?LinkId=185580

Visual Studio 시각화 및 SDK 모델링

란?LinkID = 186128

만든 사용자 지정 텍스트 템플릿 변환 해야 뿐만 아니라, 연습: 사용자 지정 텍스트 템플릿 호스트 만들기.

도메인 관련 언어 도구를 사용 하 여 지시문 프로세서를 생성

이 연습에서는 도메인 관련 언어 디자이너 마법사 DSLMinimalTest 솔루션을 위한 도메인 관련 언어를 만드는 데 사용 합니다.

도메인 관련 언어 도구를 사용 하 여 도메인 모델을 기반으로 하는 지시문 프로세서를 생성 하려면

  1. 다음과 같은 특성을 가진 dsl 솔루션을 만들:

    • 이름: DSLMinimalTest

    • 솔루션 템플릿: 최소한의 언어

    • 파일 확장명: 분

    • 회사 이름: Fabrikam

    도메인 관련 언어 솔루션을 작성 하는 방법에 대 한 자세한 내용은 참조 하십시오. 방법: 도메인별 언어 솔루션 만들기.

  2. 빌드 메뉴에서 솔루션 빌드를 클릭합니다.

    중요중요

    이 단계 지시문 프로세서를 생성 및 레지스트리 키를 추가 합니다.

  3. 디버그 메뉴에서 디버깅 시작을 클릭합니다.

    두 번째 인스턴스를 Visual Studio 를 엽니다.

  4. 실험적인 빌드에 솔루션 탐색기에서 파일을 두 번 sample.min.

    디자이너에서 파일을 엽니다.모델은 두 가지 요소, ExampleElement1 및 ExampleElement2, 및 이들 사이의 링크 되어 있습니다.

  5. 두 번째 Visual Studio 인스턴스를 닫습니다. 

  6. 솔루션을 저장 하 고 도메인 관련 언어 디자이너를 닫습니다.

사용자 정의 텍스트 템플릿 호스트 지시문 프로세서에 연결

지시문 프로세서를 생성 한 후에 만든 사용자 지정 텍스트 템플릿 호스트와 지시문 프로세서 연결 연습: 사용자 지정 텍스트 템플릿 호스트 만들기.

사용자 정의 텍스트 템플릿 호스트 생성 된 지시문 프로세서에 연결.

  1. CustomHost 솔루션을 엽니다.

  2. 프로젝트 메뉴에서 참조 추가를 클릭합니다.

    참조 추가 연결 프로그램 대화 상자에서 .NET 탭이 표시 됩니다.

  3. 다음 참조를 추가 합니다.

    • Microsoft.VisualStudio.Modeling.Sdk.11.0

    • Microsoft.VisualStudio.Modeling.Sdk.Diagrams.11.0

    • Microsoft.VisualStudio.TextTemplating.11.0

    • Microsoft.VisualStudio.TextTemplating.Interfaces.11.0

    • Microsoft.VisualStudio.TextTemplating.Modeling.11.0

    • Microsoft.VisualStudio.TextTemplating.VSHost.11.0

  4. Program.cs 또는 module1.vb의 맨 위에 있는 코드의 다음 줄을 추가 합니다.

    using Microsoft.Win32;
    
    Imports Microsoft.Win32
    
  5. 속성에 대 한 코드를 찾을 StandardAssemblyReferences를 클릭 하 고 다음 코드로 바꿉니다:

    [!참고]

    이 단계에서는 호스트를 지 원하는 생성 된 지시문 프로세서에서 필요한 어셈블리 참조를 추가 합니다.

    //the host can provide standard assembly references
    //the engine will use these references when compiling and
    //executing the generated transformation class
    //--------------------------------------------------------------
    public IList<string> StandardAssemblyReferences
    {
        get
        {
            return new string[]
            {
                //if this host searches standard paths and the GAC
                //we can specify the assembly name like this:
                //"System"
                //since this host only resolves assemblies from the 
                //fully qualified path and name of the assembly
                //this is a quick way to get the code to give us the
                //fully qualified path and name of the System assembly
                //---------------------------------------------------------
                typeof(System.Uri).Assembly.Location,
                            typeof(System.Uri).Assembly.Location,
                typeof(Microsoft.VisualStudio.Modeling.ModelElement).Assembly.Location,
                typeof(Microsoft.VisualStudio.Modeling.Diagrams.BinaryLinkShape).Assembly.Location,
                typeof(Microsoft.VisualStudio.TextTemplating.VSHost.ITextTemplating).Assembly.Location,
                typeof(Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation).Assembly.Location
    
            };
        }
    }
    
  6. 함수에 대 한 코드를 찾을 ResolveDirectiveProcessor를 클릭 하 고 다음 코드로 바꿉니다:

    중요중요

    이 코드에 하드 코드 된 연결 하려는 생성 된 지시문 프로세서의 이름에 대 한 참조가 포함 되어 있습니다.쉽게이 보다 일반적인 만들 수 있습니다, 그리고 레지스트리에 나열 하 고 일치 하는 것을 시도 모든 지시문 프로세서를 찾습니다.이 경우 호스트는 생성 된 지시문 프로세서와 함께 작동 합니다.

    //the engine calls this method based on the directives the user has 
            //specified it in the text template
            //this method can be called 0, 1, or more times
            //---------------------------------------------------------------------
            public Type ResolveDirectiveProcessor(string processorName)
            {
                //check the processor name, and if it is the name of the processor the 
                //host wants to support, return the type of the processor
                //---------------------------------------------------------------------
                if (string.Compare(processorName, "DSLMinimalTestDirectiveProcessor", StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    try
                    {
                        string keyName = @"Software\Microsoft\VisualStudio\10.0Exp_Config\TextTemplating\DirectiveProcessors\DSLMinimalTestDirectiveProcessor";
                        using (RegistryKey specificKey = Registry.CurrentUser.OpenSubKey(keyName))
                        {
                            if (specificKey != null)
                            {
                                List<string> names = new List<String>(specificKey.GetValueNames());
                                string classValue = specificKey.GetValue("Class") as string;
                                if (!string.IsNullOrEmpty(classValue))
                                {
                                    string loadValue = string.Empty;
                                    System.Reflection.Assembly processorAssembly = null;
                                    if (names.Contains("Assembly"))
                                    {
                                        loadValue = specificKey.GetValue("Assembly") as string;
                                        if (!string.IsNullOrEmpty(loadValue))
                                        {
                                            //the assembly must be installed in the GAC
                                            processorAssembly = System.Reflection.Assembly.Load(loadValue);
                                        }
                                    }
                                    else if (names.Contains("CodeBase"))
                                    {
                                        loadValue = specificKey.GetValue("CodeBase") as string;
                                        if (!string.IsNullOrEmpty(loadValue))
                                        {
                                            //loading local assembly
                                            processorAssembly = System.Reflection.Assembly.LoadFrom(loadValue);
                                        }
                                    }
                                    if (processorAssembly == null)
                                    {
                                        throw new Exception("Directive Processor not found");
                                    }
                                    Type processorType = processorAssembly.GetType(classValue);
                                    if (processorType == null)
                                    {
                                        throw new Exception("Directive Processor not found");
                                    }
                                    return processorType;
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        //if the directive processor can not be found, throw an error
                        throw new Exception("Directive Processor not found");
                    }
                }
    
                //if the directive processor is not one this host wants to support
                throw new Exception("Directive Processor not supported");
            }
    
  7. 파일 메뉴에서 모두 저장을 클릭합니다.

  8. 빌드 메뉴에서 솔루션 빌드를 클릭합니다.

사용자 지정 호스트와 지시문 프로세서를 테스트합니다.

먼저 사용자 지정 텍스트 템플릿 호스트 테스트 하려면 생성 된 지시문 프로세서를 호출 하는 텍스트 템플릿을 작성 해야 합니다.다음 텍스트 서식의 이름에 전달, 지시문이 올바르게 처리 확인 사용자 지정 호스트 실행 합니다.

텍스트 템플릿을 만들어 사용자 지정 호스트를 테스트하려면

  1. 텍스트 파일을 만들고 이름을 TestTemplateWithDP.tt.파일을 만들려면 메모장과 같은 텍스트 편집기를 사용할 수 있습니다.

  2. 텍스트 파일에 다음을 추가합니다.

    [!참고]

    텍스트 서식 파일의 프로그래밍 언어와 일치 하는 사용자 지정 호스트의 필요는 없습니다.

    Text Template Host Test
    
    <#@ template debug="true" inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" #>
    <# //this is the call to the examplemodel directive in the generated directive processor #>
    <#@ DSLMinimalTest processor="DSLMinimalTestDirectiveProcessor" requires="fileName='<Your Path>\Sample.min'" provides="ExampleModel=ExampleModel" #>
    <# //uncomment this line to test that the host allows the engine to set the extension #>
    <# //@ output extension=".htm" #>
    
    <# //uncomment this line if you want to see the generated transformation class #>
    <# //System.Diagnostics.Debugger.Break(); #>
    <# //this code uses the results of the examplemodel directive #>
    <#
        foreach ( ExampleElement box in this.ExampleModel.Elements ) 
        { 
            WriteLine("Box: {0}", box.Name);
    
            foreach (ExampleElement linkedTo in box.Targets)
            {
                WriteLine("Linked to: {0}", linkedTo.Name);
            }
    
            foreach (ExampleElement linkedFrom in box.Sources)
            {
                WriteLine("Linked from: {0}", linkedFrom.Name);
            }
    
            WriteLine("");
        } 
    #>
    
    Text Template Host Test
    
    <#@ template debug="true" language="VB" inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" #>
    
    <# 'this is the call to the examplemodel directive in the generated directive processor #>
    <#@ DSLMinimalTest processor="DSLMinimalTestDirectiveProcessor" requires="fileName='<Your Path>\Sample.min'" provides="ExampleModel=ExampleModel" #>
    
    <# 'Uncomment this line to test that the host allows the engine to set the extension. #>
    <# '@ output extension=".htm" #>
    
    <# 'Uncomment this line if you want to see the generated transformation class. #>
    <# 'System.Diagnostics.Debugger.Break() #>
    
    <# 'this code uses the results of the examplemodel directive #>
    
    <#    
       For Each box as ExampleElement In Me.ExampleModel.Elements 
    
           WriteLine("Box: {0}", box.Name)
    
            For Each LinkedTo as ExampleElement In box.Targets
                WriteLine("Linked to: {0}", LinkedTo.Name)
            Next
    
            For Each LinkedFrom as ExampleElement In box.Sources
                WriteLine("Linked from: {0}", LinkedFrom.Name)
            Next
    
            WriteLine("")
    
       Next 
    #>
    
  3. <를 패스 > 코드에서 바꾸기 디자인에 따라 언어에서 Sample.min 파일의 경로를 첫 번째 절차에서 만든.

  4. 파일을 저장한 후 닫습니다.

사용자 지정 호스트를 테스트하려면

  1. 명령 프롬프트 창을 엽니다.

  2. 사용자 지정 호스트에 대한 실행 가능한 파일의 경로를 입력하고 Enter 키를 누르지 않습니다.

    예를 들어 다음과 같이 입력합니다.

    <YOUR PATH>CustomHost\bin\Debug\CustomHost.exe

    [!참고]

    주소를 입력 하는 대신 CustomHost.exe 파일을 찾아볼 수 있습니다에서 Windows 탐색기, 다음 파일을 명령 프롬프트 창으로 끕니다.

  3. 공백을 입력합니다.

  4. 텍스트 템플릿 파일의 경로를 입력한 다음 Enter 키를 누릅니다.

    예를 들어 다음과 같이 입력합니다.

    <YOUR PATH>TestTemplateWithDP.txt

    [!참고]

    주소를 입력 하는 대신 TestTemplateWithDP.txt 파일을 찾아볼 수 있습니다에서 Windows 탐색기, 다음 파일을 명령 프롬프트 창으로 끕니다.

    사용자 지정 호스트 응용 프로그램이 실행 되 고 텍스트 템플릿 변환 프로세스를 시작 합니다.

  5. Windows 탐색기, TestTemplateWithDP.txt 파일에 포함 되어 있는 폴더를 찾습니다.

    폴더 TestTemplateWithDP1.txt 파일을 또한 포함 되어 있습니다.

  6. 이 파일을 열어 텍스트 템플릿 변환의 결과를 확인합니다.

    생성 된 텍스트 출력 결과가 표시 되 고 다음과 같습니다.

    Text Template Host Test
    
    
    Box: ExampleElement1
    Linked to: ExampleElement2
    
    Box: ExampleElement2
    Linked from: ExampleElement1
    

참고 항목

작업

연습: 사용자 지정 텍스트 템플릿 호스트 만들기