C# T4 文本模版代碼使用代碼生成

1.引用如下兩個dllide

Microsoft.VisualStudio.TextTemplating.10.0.dll

Microsoft.VisualStudio.TextTemplating.Interfaces.10.0.dll

實現ITextTemplatingEngineHost, ITextTemplatingSessionHost接口ui

[Serializable]
    public class CustomEngineHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost
    {
        #region ITextTemplatingEngineHost
        internal string TemplateFileValue;
        public string TemplateFile
        {
            get { return TemplateFileValue; }
        }

        private string fileExtensionValue = ".txt";
        public string FileExtension
        {
            get { return fileExtensionValue; }
        }

        private Encoding fileEncodingValue = Encoding.UTF8;
        public Encoding FileEncoding
        {
            get { return fileEncodingValue; }
        }
        private CompilerErrorCollection errorsValue;
        public CompilerErrorCollection Errors
        {
            get { return errorsValue; }
        }
        public IList<string> StandardAssemblyReferences
        {
            get
            {
                return new string[]
                {
                    typeof(System.Uri).Assembly.Location
                   
                };
            }
        }
        public IList<string> StandardImports
        {
            get
            {
                return new string[]
                {
                    //"System"

                };
            }
        }
        public bool LoadIncludeText(string requestFileName, out string content, out string location)
        {
            content = System.String.Empty;
            location = System.String.Empty;

            if (File.Exists(requestFileName))
            {
                content = File.ReadAllText(requestFileName);
                return true;
            }
            else
            {
                return false;
            }
        }

        public object GetHostOption(string optionName)
        {
            object returnObject;
            switch (optionName)
            {
                case "CacheAssemblies":
                    returnObject = true;
                    break;
                default:
                    returnObject = null;
                    break;
            }
            return returnObject;
        }

        public string ResolveAssemblyReference(string assemblyReference)
        {
            //if (File.Exists(assemblyReference))
            //{
            //    return assemblyReference;
            //}

            string candidate = Path.Combine(ApplicationEnvironments.Current.Server.MapPath("~/bin/"), assemblyReference);
            //if (assemblyReference.IndexOf("Microsoft.VisualStudio.TextTemplating.Interfaces.10.0") != -1)
            //{
            //    candidate = ApplicationEnvironments.Current.Server.MapPath("~/bin/") + "Microsoft.VisualStudio.TextTemplating.Interfaces.10.0.dll";
            //}
            if (File.Exists(candidate))
            {
                return candidate;
            }
            return "";
        }

        public Type ResolveDirectiveProcessor(string processorName)
        {
            if (string.Compare(processorName, "XYZ", StringComparison.OrdinalIgnoreCase) == 0)
            {
                //return typeof();
            }
            throw new Exception("Directive Processor not found");
        }

        public string ResolvePath(string fileName)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("the file name cannot be null");
            }
            if (File.Exists(fileName))
            {
                return fileName;
            }
            string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), fileName);
            if (File.Exists(candidate))
            {
                return candidate;
            }
            return fileName;
        }

        public string ResolveParameterValue(string directiveId, string processorName, string parameterName)
        {
            if (directiveId == null)
            {
                throw new ArgumentNullException("the directiveId cannot be null");
            }
            if (processorName == null)
            {
                throw new ArgumentNullException("the processorName cannot be null");
            }
            if (parameterName == null)
            {
                throw new ArgumentNullException("the parameterName cannot be null");
            }
            return String.Empty;
        }

        public void SetFileExtension(string extension)
        {
            fileExtensionValue = extension;
        }

        public void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective)
        {
            fileEncodingValue = encoding;
        }

        public void LogErrors(CompilerErrorCollection errors)
        {
            errorsValue = errors;
        }

        public AppDomain ProvideTemplatingAppDomain(string content)
        {
            //CreateDomain("Generation App Domain")
            return AppDomain.CurrentDomain;
        }

        #endregion

        #region ITextTemplatingSessionHost
        public ITextTemplatingSession CreateSession()
        {
            return Session;
        }

        public ITextTemplatingSession Session
        {
            get;
            set;
        }
        #endregion
    }

如下是調用代碼this

public static string Create(TemplateModel templateModel, string templatePath,ref string strError)
        {
            if (string.IsNullOrWhiteSpace(templatePath))
            {
                return "";
            }
            try
            {
                templatePath = ApplicationEnvironments.Current.Server.MapPath(templatePath);
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                return null;
            }
            if (!File.Exists(templatePath))
            {
                strError = "未找到Entity.tt,請修改配置文件!";
                return null;
            }
            CustomEngineHost host = new CustomEngineHost();
            host.TemplateFileValue = templatePath;
            string input = File.ReadAllText(templatePath);
            host.Session = new TextTemplatingSession();
            host.Session.Add("entity", templateModel);
         
            //host.Session.Add("entity", templateModel.ToJson());
            string output = new Engine().ProcessTemplate(input, host);

            StringBuilder errorWarn = new StringBuilder();
            foreach (CompilerError error in host.Errors)
            {
                errorWarn.Append(error.Line).Append(":").AppendLine(error.ErrorText);
            }
            if (!string.IsNullOrWhiteSpace(errorWarn.ToString()))
            {
                output = errorWarn.ToString();
            }
          
            //if (!File.Exists("Error.log"))
            //{
            //    File.Create("Error.log");
            //}
            // File.WriteAllText("Error.log", errorWarn.ToString());
            return output;
        }

T4模版樣例spa

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".txt" #>
<#@ assembly name="System.Data.dll" #>
<#@ assembly name="System.Core.dll" #>
<#@ assembly name="WHLORM.dll" #>
<#@ assembly name="WHLORM.Core.dll" #>
<#@ assembly name="WHLORM.Model.dll" #>
<#@ assembly name="WHLORM.BLL.dll" #>
<#@ assembly name="WHLORM.DataBase.Model.dll" #>
<#@ assembly name="WHLORM.Web.dll" #>
<#@ Import namespace="System" #>
<#@ Import namespace="WHLORM.DataBase.BLL" #>
<#@ parameter type="WHLORM.DataBase.BLL.TemplateModel" name="entity" #>

下面就是你的內容 模版下引用使用linq 不知道爲何
相關文章
相關標籤/搜索