PageRenderTime 18ms CodeModel.GetById 13ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/ExpressInteropBinding/Microsoft.ServiceModel.Interop.ExtensionUtils/ConfigurationWizard/Service/T4Invoker.cs

#
C# | 124 lines | 58 code | 19 blank | 47 comment | 5 complexity | fcad347e80a919c1fd9a9668ab710cd1 MD5 | raw file
  1// <copyright file="T4Invoker.cs" company="Microsoft Corporation">
  2// Copyright (c) Microsoft Corporation.  All rights reserved.
  3// </copyright>
  4
  5namespace Microsoft.ServiceModel.Interop.ConfigurationWizard.Services
  6{
  7    using System;
  8    using System.Collections.Generic;
  9    using System.Globalization;
 10    using System.Text;
 11    using Microsoft.VisualStudio.TextTemplating;
 12    using Microsoft.VisualStudio.TextTemplating.VSHost;
 13
 14    /// <summary>
 15    /// T4Invoker provides a simple mechanism to invoke the T4 engine given
 16    /// a template file, a string/string Dictionary containing substitutions and
 17    /// returns the results and/or error messages
 18    /// </summary>
 19    public class T4Invoker : ITextTemplatingCallback
 20    {
 21        /// <summary>
 22        /// List of error messages (if any) resulting from the T4 transformation
 23        /// </summary>
 24        private List<string> errorMessages = new List<string>();
 25
 26        /// <summary>
 27        /// Errors are collected into a single string and returned in the result value
 28        /// </summary>
 29        private string errors = string.Empty;
 30
 31        /// <summary>
 32        /// Initializes a new instance of the T4Invoker class
 33        /// </summary>
 34        /// <param name="serviceProvider">IServiceProvider for Visual Studio.  You can use MEF to import this into your FeatureCommand or ValueProvider.</param>
 35        public T4Invoker(IServiceProvider serviceProvider)
 36        {
 37            this.ServiceProvider = serviceProvider;
 38        }
 39
 40        /// <summary>
 41        /// Gets and sets the VS Service Provider from which we find the ITextTemplating service
 42        /// </summary>
 43        internal IServiceProvider ServiceProvider { get; private set; }
 44
 45        /// <summary>
 46        /// Invokes T4 engine on provided file passing Dictionary values for substitution
 47        /// </summary>
 48        /// <param name="templateName">T4 template name</param>
 49        /// <param name="templateFileContent">T4 template content</param>
 50        /// <param name="fields">String/String Dictionary which T4 contents can use for substitutions</param>
 51        /// <returns>TextTransformationResult object with HasErrors, Content and Filename properties</returns>
 52        public TextTransformationResult TransformText(string templateName, string templateFileContent, IDictionary<string, string> fields)
 53        {
 54            if (fields == null)
 55            {
 56                throw new ArgumentNullException("fields");
 57            }
 58
 59            // Get the T4 engine from VS
 60            ITextTemplating textTemplating = this.ServiceProvider.GetService(typeof(STextTemplating)) as ITextTemplating;
 61
 62            this.errorMessages.Clear();
 63            textTemplating.BeginErrorSession();
 64
 65            // Initialize the T4 host so we can transfer the Dictionary contents
 66            // into the new app domain in which the host runs
 67            ITextTemplatingSessionHost host = textTemplating as ITextTemplatingSessionHost;
 68
 69            host.Session = host.CreateSession();
 70
 71            foreach (string s in fields.Keys)
 72            {
 73                host.Session[s] = fields[s];
 74            }
 75
 76            var content = textTemplating.ProcessTemplate(templateName, templateFileContent, this, null);
 77            textTemplating.EndErrorSession();
 78
 79            return new TextTransformationResult(content, content.StartsWith("ErrorGeneratingOutput", true, CultureInfo.InvariantCulture), String.Empty);
 80        }
 81
 82        /// <summary>
 83        /// Callback provided for T4 to report errors
 84        /// </summary>
 85        /// <param name="warning">True if error is a warning</param>
 86        /// <param name="message">Error text</param>
 87        /// <param name="line">Line number within the T4 that generated the error</param>
 88        /// <param name="column">Column number within the line that generated the error</param>
 89        public void ErrorCallback(bool warning, string message, int line, int column)
 90        {
 91            if (string.IsNullOrEmpty(message))
 92            {
 93                throw new ArgumentNullException("message");
 94            }
 95
 96            if (!warning && message.Contains(typeof(TextTransformationException).FullName))
 97            {
 98                throw new TextTransformationException(message);
 99            }
100
101            string s = string.Format(CultureInfo.InvariantCulture, "{0}: {1}. Line: {2} Column: {3}", warning ? "warning" : "error", message, line, column);
102            this.errors += "\r\n" + s;
103            this.errorMessages.Add(s);
104        }
105
106        /// <summary>
107        /// Required callback for T4.  Since we do not output a file, we do nothing here
108        /// </summary>
109        /// <param name="extension">Extension for output file</param>
110        public void SetFileExtension(string extension)
111        {
112        }
113
114        /// <summary>
115        /// Required callback for T4.  We do nothing with this.
116        /// </summary>
117        /// <param name="encoding">Encoding for output file</param>
118        /// <param name="fromOutputDirective">True if this is from an Output directive</param>
119        public void SetOutputEncoding(Encoding encoding, bool fromOutputDirective)
120        {
121        }
122    }
123}
124