public override void ExecuteProfile(Parser parser)
        {
            string file = Path.Combine(Program.Configuration.Output, OutPutPath, GetRelativePath(parser.Filename),
                                       Path.GetFileNameWithoutExtension(parser.Filename));

            string moduleFile =
                parser.Fields.Where(entry => entry.Name == "MODULE").Select(entry => entry.Value).SingleOrDefault();

            var engine = new Engine();
            var host = new TemplateHost(TemplatePath);
            host.Session["Parser"] = parser;
            host.Session["Profile"] = this;
            string output = engine.ProcessTemplate(File.ReadAllText(TemplatePath), host);

            foreach (CompilerError error in host.Errors)
            {
                Console.WriteLine(error.ErrorText);
            }

            if (host.Errors.Count > 0)
                Program.Shutdown();

            File.WriteAllText(file + host.FileExtension, output);

            Console.WriteLine("Wrote {0}", file + host.FileExtension);
        }
Beispiel #2
0
        private void GoButton_Click(object sender, EventArgs e)
        {
            CustomCmdLineHost host = new CustomCmdLineHost();
            var session = new TextTemplatingSession();

            string templateFileName = TemplateList.SelectedItem.ToString();

            var sessionHost = (ITextTemplatingSessionHost)host;
            sessionHost.Session = session;

            foreach (string tableName in TableList.CheckedItems)
            {
                sessionHost.Session["tableName"] = tableName;
                //// Pass another value in CallContext:
                System.Runtime.Remoting.Messaging.CallContext.LogicalSetData("p2", "test");

                Engine engine = new Engine();
                host.TemplateFileValue = templateFileName;
                //Read the text template.
                string input = File.ReadAllText(templateFileName);
                //Transform the text template.
                string output = engine.ProcessTemplate(input, host);
                string outputFileName = tableName;
                outputFileName = Path.Combine(Path.GetDirectoryName(templateFileName), outputFileName);
                outputFileName = outputFileName + "1" + host.FileExtension;
                File.WriteAllText(outputFileName, output, host.FileEncoding);

                foreach (CompilerError error in host.Errors)
                {
                    Console.WriteLine(error.ToString());
                }
            }

            Console.ReadLine();
        }
        public override void ExecuteProfile(Parser parser)
        {
            string file = Path.Combine(Program.Configuration.Output, OutPutPath, GetRelativePath(parser.Filename), Path.GetFileNameWithoutExtension(parser.Filename));
            var xmlMessage = Program.Configuration.XmlMessagesProfile.SearchXmlPattern(Path.GetFileNameWithoutExtension(parser.Filename));

            if (xmlMessage == null)
                Program.Shutdown(string.Format("File {0} not found", file));

            var engine = new Engine();
            var host = new TemplateHost(TemplatePath);
            host.Session["Message"] = xmlMessage;
            host.Session["Profile"] = this;
            var output = engine.ProcessTemplate(File.ReadAllText(TemplatePath), host);

            foreach (CompilerError error in host.Errors)
            {
                Console.WriteLine(error.ErrorText);
            }

            if (host.Errors.Count > 0)
                Program.Shutdown();

            File.WriteAllText(file + host.FileExtension, output);

            Console.WriteLine("Wrote {0}", file);
        }
Beispiel #4
0
        public string GetTemplateContent(string templateName, TextTemplatingSession session)
        {
            string fullName        = this.Host.ResolvePath(templateName);
            string templateContent = File.ReadAllText(fullName);

            var sessionHost = this.Host as ITextTemplatingSessionHost;

            sessionHost.Session = session;

            var engine = new Microsoft.VisualStudio.TextTemplating.Engine();

            return(engine.ProcessTemplate(templateContent, this.Host));
        }
Beispiel #5
0
        public string GetTemplateContent(string templateName, TextTemplatingSession session)
        {
            string fullName        = Host.ResolvePath(templateName);
            string templateContent = File.ReadAllText(fullName);

            var sessionHost = Host as ITextTemplatingSessionHost;

            sessionHost.Session = session;

            Engine engine = new Engine();

            return(engine.ProcessTemplate(templateContent, Host));
        }
Beispiel #6
0
        void Exec()
        {
            //var arguments = new Dictionary<string, PropertyData>();

            //arguments.Add("ClassName", new PropertyData("MyClass", typeof(string)));
            //arguments.Add("TargetNamespace", new PropertyData("MyNameSpace", typeof(string)));
            //arguments.Add("HelloMessage", new PropertyData("HelloMessage", typeof(string)));

            //// Initialize GAX template host   
            //string currentDirectory = Directory.GetCurrentDirectory();
            //TemplateHost host = new TemplateHost(currentDirectory, arguments);
            //host.TemplateFile = Path.Combine(currentDirectory, "ServiceTemplate.tt");

            // Transform template   
            //string template = File.ReadAllText(host.TemplateFile);
            //ITextTemplatingEngine engine = new Engine();
            //string output = engine.ProcessTemplate(template, host);

            //// Save output   
            //string outputFile = Path.ChangeExtension(host.TemplateFile, ".txt");
            //File.WriteAllText(outputFile, output);   



            
            //TextTemplate tt = new TextTemplate();
            //tt.Source = "... code here, check example file above ...";
            //tt.Compile(); 
            //String output = tt.Generate(singleObjectParameter);
            CustomCmdLineHost host = new CustomCmdLineHost();
            host.TemplateFileValue = templateFileName;
           
            Engine engine = new Engine();
            
            //read the text template
            string input = File.ReadAllText(templateFileName);


            //transform the text template
            string output = engine.ProcessTemplate(input, host);

            
            string outputFileName = Path.GetFileNameWithoutExtension(templateFileName);
            outputFileName = Path.Combine(Path.GetDirectoryName(templateFileName), outputFileName);
            outputFileName = outputFileName + "1" + host.FileExtension;

                   

            
        }
Beispiel #7
0
        public static bool FormatedTemplate(string Modulepath, Dictionary <string, object> paraList, ref string outputCode)
        {
            try
            {
                // TODO: Implement Functionality Here
                CSTemplatingEngineHost host = new CSTemplatingEngineHost();
                Microsoft.VisualStudio.TextTemplating.Engine engine = new Microsoft.VisualStudio.TextTemplating.Engine();
                #region  这里的设置是为了动态的传递参数使用的
                host.Session = new Microsoft.VisualStudio.TextTemplating.TextTemplatingSession();
                // host.Session.Add("content", "世界你好");

                foreach (var item in paraList)
                {
                    host.Session.Add(item.Key, item.Value);
                }
                #endregion

                //获取当前路径
                string path2 = System.Environment.CurrentDirectory;

                host.TemplateFileValue = "sample.tt";

                string templateContent = System.IO.File.ReadAllText(Modulepath);


                outputCode = engine.ProcessTemplate(templateContent, host);
                Console.WriteLine(outputCode);

                string errorInfo = string.Empty;
                foreach (var element in host.Errors)
                {
                    errorInfo += element.ToString() + "\r\n";
                }
                if (!string.IsNullOrEmpty(errorInfo))
                {
                    outputCode = errorInfo;
                    return(false);
                }

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(false);
            //Console.Write("Press any key to continue . . . ");
            //Console.ReadKey(true);
        }
Beispiel #8
0
        static void ProcessTemplate(params string[] args)
        {
            string templateFileName = null;

            if (args.Length == 0)
            {
                throw new System.Exception("you must provide a text template file path");
            }

            templateFileName = args[0];

            if (templateFileName == null)
            {
                throw new ArgumentNullException("the file name cannot be null");
            }

            if (!File.Exists(templateFileName))
            {
                throw new FileNotFoundException("the file cannot be found");
            }

            CustomCmdLineHost host = new CustomCmdLineHost();
            Engine engine = new Engine();

            host.TemplateFileValue = templateFileName;

            //Read the text template.
            string input = File.ReadAllText(templateFileName);
            input = input.Replace(@"$(ProjectDir)\", "");
            //Transform the text template.
            string output = engine.ProcessTemplate(input, host);

            string outputFileName = Path.GetFileNameWithoutExtension(templateFileName);
            outputFileName = Path.Combine(Path.GetDirectoryName(templateFileName), outputFileName);
            outputFileName = outputFileName + "1" + host.FileExtension;

            File.WriteAllText(outputFileName, output, host.FileEncoding);

            foreach (CompilerError error in host.Errors)
            {
                Console.WriteLine(error.ToString());
            }
        }
Beispiel #9
0
        public static void GenerateFileAsDefault(ITextTemplatingEngineHost host, string templateFilePath, string outputFileName)
        {
            Assembly myAssembly = Assembly.GetExecutingAssembly();
            Stream myStream = myAssembly.GetManifestResourceStream(templateFilePath);

            if (myStream != null)
            {
                StreamReader reader = new StreamReader(myStream);
                string text = reader.ReadToEnd();

                Engine engine = new Engine();

                // use the engine to transfor the template
                string output = engine.ProcessTemplate(text, host);

                File.WriteAllText(outputFileName, output, Encoding.UTF8);
            }

            //throw new Exception("Wrong template file path");
        }
		public void InvokeHostWithModel()
		{
			Engine engine = new Engine();
			Store store = new Store(typeof(MockDomainModel));
			MockDomainModel domainModel = GetModel(store);

			using (Transaction t = store.TransactionManager.BeginTransaction())
			{
				ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition,string.Empty);
				TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel,null);
				string templateContent = GetStandardTemplateHeader() + @"
					<#= this.Model.DomainModelInfo.Id #>";

				string transformResult = engine.ProcessTemplate(
					templateContent,
					host);
				Assert.AreEqual(domainModel.DomainModelInfo.Id, new Guid(transformResult));
				t.Rollback();
			}
		}
Beispiel #11
0
        string GetFileName(ClassMapping clazz)
        {
            var T4   = new Microsoft.VisualStudio.TextTemplating.Engine();
            var host = new CustomHost()
            {
                TemplateFile = "config"
                ,
                Logger = log
            };

            CallContext.LogicalSetData("clazz", clazz);
            string fileName = T4.ProcessTemplate(GetTemplateForOutputName()
                                                 , host
                                                 ).Trim();

            if (host.HasError)
            {
                throw new Exception(); // errors are logged by the engine
            }
            return(fileName);
        }
Beispiel #12
0
        public override void Render(string savedToPackage, string savedToClass, ClassMapping classMapping, IDictionary class2classmap, StreamWriter writer)
        {
            Microsoft.VisualStudio.TextTemplating.Engine T4;
            CallContext.LogicalSetData("clazz", classMapping);
            CallContext.LogicalSetData("savedToClass", savedToClass);
            CallContext.LogicalSetData("class2classmap", class2classmap);
            T4 = new Microsoft.VisualStudio.TextTemplating.Engine();
            string res = T4.ProcessTemplate(CustomHost.GetTemplateCode(template)
                                            , new CustomHost()
            {
                TemplateFile = template
                , Logger     = log
            }
                                            );

            log.Debug("Generated File:\n" + res);
            writer.Write(res);
            writer.Flush();
            if (writer.BaseStream is FileStream)
            {
                log.Info("Flushed file:" + (writer.BaseStream as FileStream).Name);
            }
        }
        private void GenerateOutput(string templateFileName, System.Collections.IList tables)
        {
            var host = new T4Host();
            var session = new TextTemplatingSession();
            var sessionHost = (ITextTemplatingSessionHost)host;
            sessionHost.Session = session;

            foreach (Table table in tables)
            {
                LogUpdate("Processing table {0}", table.Name);
                sessionHost.Session["table"] = new SqlTable { Name = table.Name, Schema = table.Schema };
                sessionHost.Session["tableName"] = table.Name;
                sessionHost.Session["namespace"] = NamespaceParameter.Text;
                //// Pass another value in CallContext:
                System.Runtime.Remoting.Messaging.CallContext.LogicalSetData("p2", "test");

                Engine engine = new Engine();
                host.TemplateFile = templateFileName;
                //Read the text template.
                string input = File.ReadAllText(templateFileName);
                //Transform the text template.
                string output = engine.ProcessTemplate(input, host);
                string outputFileName = table.Name;
                outputFileName = Path.Combine(Path.GetDirectoryName(templateFileName) ?? "", outputFileName);
                outputFileName = outputFileName + "1" + host.FileExtension;
                File.WriteAllText(outputFileName, output, host.FileEncoding);
                LogUpdate("Saved to file {0}", outputFileName);
                StringBuilder sb = new StringBuilder();
                foreach (CompilerError error in host.Errors)
                {
                    sb.AppendLine(error.ToString());
                }
                if (sb.Length > 0) LogUpdate( "Errors: " + sb.ToString());
            }

            LogUpdate("Done.");
        }
 static CompilerErrorCollection ProcessTemplate(string args, string schema, string table)
 {
     string templateFileName = null;
     if (args == null)
     {
         throw new Exception("you must provide a text template file path");
     }
     templateFileName = args;
     if (templateFileName == null)
     {
         throw new ArgumentNullException("the file name cannot be null");
     }
     if (!File.Exists(templateFileName))
     {
         throw new FileNotFoundException("the file cannot be found");
     }
     SQLViewsHost host = new SQLViewsHost();
     Engine engine = new Engine();
     host.TemplateFileValue = templateFileName;
     //Read the text template.
     TextTemplatingSession session = new TextTemplatingSession();
     session["SchemaName"] = schema;
     session["TableName"] = table;
     session["ViewName"] = String.Format("v{0}", table);
     session["Username"] = "******";
     var sessionHost = (ITextTemplatingSessionHost)host;
     sessionHost.Session = session;
     string input = File.ReadAllText(templateFileName);
     //Transform the text template.
     string output = engine.ProcessTemplate(input, host);
     string outputFileName = Path.GetFileNameWithoutExtension(String.Format("v{0}", table));
     outputFileName = Path.Combine(Path.GetDirectoryName(String.Format("v{0}", table)), outputFileName);
     outputFileName = outputFileName + host.FileExtension;
     File.WriteAllText(outputFileName, output, host.FileEncoding);
     return host.Errors;
 }
Beispiel #15
0
 string GetFileName(ClassMapping clazz)
 {
     var T4 = new Microsoft.VisualStudio.TextTemplating.Engine();
     var host = new CustomHost()
     {
         TemplateFile = "config"
         ,
         Logger = log
     };
     CallContext.LogicalSetData("clazz", clazz);
     string fileName = T4.ProcessTemplate(GetTemplateForOutputName()
                                 , host
                                 ).Trim();
     if (host.HasError)
         throw new Exception(); // errors are logged by the engine
     return fileName;
 }
Beispiel #16
0
        private void DoBuild()
        {
            int finish = 0;
            int total = listBox2.Items.Count;

            //遍历选中的表,一张表对应生成一个代码文件
            foreach (object item in listBox2.Items)
            {
                SOTable table = item as SOTable;
                string className = table.Name;
                if (cbDeleteTablePrifix.Checked)className = table.Name.RemovePrefix(tablePrefix, prefixLevel).Replace(" ", "");
                if (cbClassNamePascal.Checked) className = className.InitialToUpperMulti();
                if (cbClassNameRemovePlural.Checked) className = className.EndsWith("s") ? className.TrimEnd('s') : className.Trim();
                if (cbAddSuffix.Checked) className = txtClassPrefix.Text.Trim() + className + txtClassSuffix.Text.Trim();

                templateFile = gbTemplateFile.Text;

                List<SOColumn> columnList = table.ColumnList;//可能传入的是从PDObject对象转换过来的SODatabase对象
                if (columnList == null || columnList.Count == 0) columnList = DbSchemaHelper.Instance.CurrentSchema.GetTableColumnList(table);

                //生成代码文件
                TableHost host = new TableHost();
                host.Table = table;
                host.ColumnList = columnList;
                host.TemplateFile = templateFile;
                host.SetValue("NameSpace", nameSpace);
                host.SetValue("ClassName", className);
                host.SetValue("TablePrefix", tablePrefix);
                //host.SetValue("ColumnPrefix", columnPrefix);
                host.SetValue("PrefixLevel", prefixLevel);

                Engine engine = new Engine();

                string outputContent = engine.ProcessTemplate(File.ReadAllText(templateFile), host);
                //string outputFile = Path.Combine(outputPath, string.Format("{0}.cs", className));
                string outputFile = Path.Combine(outputPath, string.Format("{0}{1}", table.Name, host.FileExtention));
                if(cbClassNameIsFileName.Checked)outputFile = Path.Combine(outputPath, string.Format("{0}{1}", className, host.FileExtention));

                StringBuilder sb = new StringBuilder();
                if (host.ErrorCollection.HasErrors)
                {
                    foreach (CompilerError err in host.ErrorCollection)
                    {
                        sb.AppendLine(err.ToString());
                    }
                    outputContent = outputContent + Environment.NewLine + sb.ToString();
                    outputFile = outputFile + ".error";
                }

                if (Directory.Exists(outputPath) == false) Directory.CreateDirectory(outputPath);
                File.WriteAllText(outputFile, outputContent, Encoding.UTF8);

                finish = finish + 1;
                int percent = ConvertUtil.ToInt32(finish * 100 / total, 0);

                backgroundWorker1.ReportProgress(percent, table);
            }//end build code foreach
        }
		public void CanAddProjectReference()
		{
			Engine engine = new Engine();
			Store store = new Store(typeof(MockDomainModel));
			MockDomainModel domainModel = GetModel(store);

			using (Transaction t = store.TransactionManager.BeginTransaction())
			{
				ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition, "test");
				serviceModel.ObjectExtender = new MockObjectExtender();
				TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel, serviceModel);
				host.StandardAssemblyReferences.Add(typeof(Microsoft.Practices.Modeling.ExtensionProvider.Extension.ObjectExtender<ExtensibleMockModelElement>).Assembly.FullName);
				
				string transformResult = engine.ProcessTemplate(
					GetStandardTemplateHeader() + @"
					<# AddProjectReference(CurrentExtender.ArtifactLink); #>",
					host);
				Assert.AreEqual(1, host.ProjectReferences.Count);
				t.Rollback();
			}
		}
        private object Render(string templateCode, string template)
        {
            string basePath = GetBasePath();
            var additionalArguments = new Dictionary<string, string>();
            ITextTemplatingEngine engine = new Engine();
            var service = (IValueInfoService)GetService(typeof(IValueInfoService));
            var arguments = new Dictionary<string, PropertyData>();

            additionalArguments.Add("StoreNamespace", string.Empty);
            additionalArguments.Add("StoreSelectedProxyType", ProxyTypes.NoProxy);
            additionalArguments.Add("StoreProxyApi", string.Empty);
            additionalArguments.Add("StoreSelectedExtends", GlobalConstants.FlatStore);
            additionalArguments.Add("StoreSelectedModel", "." + ModelNamespace + ModelClassName);
            additionalArguments.Add("StoreProxyParams", string.Empty);
            additionalArguments.Add("StoreClassName", ModelClassName + "s");

            foreach (string str2 in additionalArguments.Keys)
            {
                Type type = null;
                if (additionalArguments[str2] != null)
                {
                    type = additionalArguments[str2].GetType();
                }
                else
                {
                    continue;
                }
                var data = new PropertyData(additionalArguments[str2], type);
                arguments.Add(str2, data);
            }
            var host = new TemplateHost(basePath, arguments)
            {
                TemplateFile = template
            };
            string str3 = engine.ProcessTemplate(templateCode, host);
            if (host.Errors.HasErrors)
            {
                throw new TemplateException(host.Errors);
            }
            if (host.Errors.HasWarnings)
            {
                var builder = new StringBuilder();
                foreach (CompilerError error in host.Errors)
                {
                    builder.AppendLine(error.ToString());
                }
            }
            return str3;
        }
		public void InvokeHostSimpleTemplate()
		{
			Engine engine = new Engine();
			string result = engine.ProcessTemplate("Hello World", new TextTemplateHost(null, null, null));
			Assert.AreEqual("Hello World", result);
		}
		private string IsValid(bool expectedValue)
		{
			Engine engine = new Engine();
			Store store = new Store(typeof(MockDomainModel));
			MockDomainModel domainModel = GetModel(store);

			using (Transaction t = store.TransactionManager.BeginTransaction())
			{
				ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition, string.Empty);
				MockCodeGenerationService cgs = new MockCodeGenerationService(expectedValue);
				TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel, serviceModel, cgs);
				string transformResult = engine.ProcessTemplate(
					GetStandardTemplateHeader().Replace("/n","") + @"<#= this.IsValid(CurrentElement.InvalidArtifactLink).ToString()#>",
					host);
				t.Rollback();
				return transformResult.Trim();
			}
		}
Beispiel #21
0
        public void DoBuildCode()
        {
            textEditorControl1.SaveFile(gbTemplateFile.Text);

            TableHost host = new TableHost();
            host.Table = this.Table;
            host.TemplateFile = gbTemplateFile.Text;

            List<SOColumn> columnList = new List<SOColumn>();

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Cells[0].FormattedValue.ToString().ToLower() == "true")
                {
                    SOColumn c = row.DataBoundItem as SOColumn;
                    columnList.Add(c);
                }
            }

            host.ColumnList = columnList;
            Engine engine = new Engine();
            string outputContent = engine.ProcessTemplate(File.ReadAllText(host.TemplateFile), host);

            StringBuilder sb = new StringBuilder();
            if (host.ErrorCollection.HasErrors)
            {
                foreach (CompilerError err in host.ErrorCollection)
                {
                    sb.AppendLine(err.ToString());
                }
                outputContent = outputContent + Environment.NewLine + sb.ToString();
            }

            textEditorControl2.Text = outputContent;
            tabControl1.SelectedTab = tabPage2;
            textEditorControl2.Refresh();
        }
		public void HostReturnsWarningsFromLogCall()
		{
			Engine engine = new Engine();
			Store store = new Store(typeof(MockDomainModel));
			MockDomainModel domainModel = GetModel(store);

			const string LogMessage = "Message1";
			const string LogTitle = "Title1";

			using (Transaction t = store.TransactionManager.BeginTransaction())
			{
				ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition, string.Empty);
				TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel, null);
				string transformResult = engine.ProcessTemplate(
					GetStandardTemplateHeader() + @"
					<# LogWarning(""" + LogMessage + @""",""" + LogTitle + @"""); #>",
					host);
				Assert.AreEqual<int>(1, host.CompilerErrors.Count);
				Assert.IsTrue(host.CompilerErrors[0].IsWarning);
				Assert.IsTrue(host.CompilerErrors[0].ErrorNumber.Contains(LogMessage), "Could not find expected error in compiler errors.");
				Assert.IsTrue(host.CompilerErrors[0].ErrorText.Contains(LogTitle), "Could not find expected error in compiler errors.");

				t.Rollback();
			}
		}
		public void HostReturnsErrorsInCollection()
		{
			Engine engine = new Engine();
			Store store = new Store(typeof(MockDomainModel));
			MockDomainModel domainModel = GetModel(store);

			using (Transaction t = store.TransactionManager.BeginTransaction())
			{
				ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition, string.Empty);
				TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel, null);
				string transformResult = engine.ProcessTemplate(
					GetStandardTemplateHeader() + @"
					<# throw new global::System.Exception(""TestException""); #>",
					host);

				Assert.AreEqual<int>(2, host.CompilerErrors.Count);
				Assert.IsTrue(host.CompilerErrors[1].ErrorText.Contains("TestException"),"Could not find expected exception in compiler errors."); 

				t.Rollback();
			}
		}
		public void CanGetCSharpTypeOutput()
		{
			Engine engine = new Engine();
			Store store = new Store(typeof(MockDomainModel));
			MockDomainModel domainModel = GetModel(store);

			using (Transaction t = store.TransactionManager.BeginTransaction())
			{
				ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition, string.Empty);
				TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel, null);
				string transformResult = engine.ProcessTemplate(
					GetStandardTemplateHeader() + @"
					<#= Utility.GetCSharpTypeOutput(""System.String"") #>",
					host);
				Assert.IsTrue(transformResult.Contains("string"));
				t.Rollback();
			}
		}
        void ProcessTemplate(string templateFileName, string outputFileName)
        {
            CustomTextTemplateHost host = new CustomTextTemplateHost();
            Engine engine = new Engine();

            host._TemplateFileValue = templateFileName;

            //Read the text template.
            string input = File.ReadAllText(templateFileName);

            //Transform the text template.
            string output = engine.ProcessTemplate(input, host);

            outputFileName = outputFileName + host.FileExtension;

            if (!Directory.Exists(Path.GetDirectoryName(outputFileName)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(outputFileName));
            }

            File.WriteAllText(outputFileName, output, host.FileEncoding);

            foreach (CompilerError error in host.Errors)
            {
                this.Log.LogError(error.ToString());
            }
        }
Beispiel #26
0
 public override void Render(string savedToPackage, string savedToClass, ClassMapping classMapping, IDictionary class2classmap, StreamWriter writer)
 {
     Microsoft.VisualStudio.TextTemplating.Engine T4;
     CallContext.LogicalSetData("clazz", classMapping);
     CallContext.LogicalSetData("savedToClass", savedToClass);
     CallContext.LogicalSetData("class2classmap", class2classmap);
     T4 = new Microsoft.VisualStudio.TextTemplating.Engine();
     string res = T4.ProcessTemplate(CustomHost.GetTemplateCode(template)
                                     , new CustomHost()
                                     {
                                         TemplateFile=template
                                         ,Logger=log
                                     }
                                     );
     log.Debug("Generated File:\n"+res);
     writer.Write(res);
     writer.Flush();
     if (writer.BaseStream is FileStream)
     {
         log.Info("Flushed file:"+(writer.BaseStream as FileStream).Name);
     }
 }
        private Stream ExecuteT4Template(string templateContent, Dictionary<string, string> propertyBag)
        {
            var host = new CustomTemplateHost();
            var engine = new Engine();
            host.TemplateFileValue = "c:\\foo.t4";
            //string input = templateContent;

            var session = host.CreateSession();
            foreach (var property in propertyBag)
            {
                session.Add(property.Key, property.Value);
            }

            string output = engine.ProcessTemplate(templateContent, host);

            var stream = new MemoryStream();
            var streamWriter = new StreamWriter(stream);
            streamWriter.Write(output);
            streamWriter.Flush();
            stream.Position = 0L;

            if (!host.Errors.HasErrors)
                return stream;

            var exception = new T4TemplateException("T4 compilation error");

            foreach (var error in host.Errors)
            {
                exception.AddError(error.ToString());
            }

            throw exception;
        }
Beispiel #28
0
        private void GenerateFile(ThreadStateObject threadStateObject)
        {
            try
            {
                SetLabelText(string.Format("正在生成 {0} ", threadStateObject.TemplateName.ToString()), threadStateObject.LblTip);
                string templateFolder = string.Format(@"{0}\Templates\", Environment.CurrentDirectory);
                TextTemplatingSession session = new TextTemplatingSession();
                session.Add("t4Parameter", T4Parameters.Default);

                CustomCmdLineHost host = new CustomCmdLineHost();
                host.TemplateFileValue = threadStateObject.TemplateName.ToString();
                host.Session = session;
                Engine engine = new Engine();
                //Read the text template.
                string input = File.ReadAllText(templateFolder + threadStateObject.TemplateName);
                input = input.Replace(@"$(ProjectDir)\", "");
                //Transform the text template.
                string output = engine.ProcessTemplate(input, host);
                foreach (CompilerError error in host.Errors)
                {
                    Console.WriteLine(error.ToString());
                }
            }
            catch
            {

            }
            lock (synObj)
            {
                taskFinishedCount = taskFinishedCount + 1;
            }
        }
Beispiel #29
0
        public MainWindow()
        {
            InitializeComponent();
            ViewModel viewModel = null;
            if ((App.Current as App).ViewModel == null)
            {
               
                viewModel = new ViewModel();
                viewModel.ControllerDefinition = new ControllerDefinition(viewModel);
                viewModel.RepositoryDefinition = new RepositoryDefinition(viewModel);
                viewModel.ServiceDefinition = new ServiceDefinition(viewModel);
                viewModel.ViewDefinition = new ViewDefinition(viewModel);
                viewModel.ViewModelDefinition = new ViewModelDefinition(viewModel);
            }
            else
                viewModel = (App.Current as App).ViewModel;
 
            Engine engine = new Engine();
            TextTemplateHost host;
            
            viewModel.Ler = new ActionCommand(
                a => {
                    if(Directory.Exists(a as string))
                        Directory.GetFiles(a as string, "*.hbm.xml").ToList().ForEach(c =>
                        {
                            XDocument doc = XDocument.Load(c);
                        
                            viewModel.Entidades.Add(new EntityViewModel 
                            { 
                                FilePath = c,
                                Nome = doc.Descendants().Where(it=>it.Name.LocalName == "class").FirstOrDefault().Attribute("name").Value
                            });
                        });
                },
                a =>  true
            );

            viewModel.Gerar = new ActionCommand(
                c => {
                    var entities = new List<EntityModel>();
                    string filecontent = "";
                    string template = "";
                   
                    viewModel.Entidades.Where(it => it.Ativo).ToList().ForEach(it => 
                    {
                        XDocument doc = XDocument.Load(it.FilePath);
                        var entity = new EntityModel()
                        {
                            ClassName = it.Nome.Contains(",") ? it.Nome.Split(',')[0].Contains(".") ? it.Nome.Split(',')[0].Substring(it.Nome.Split(',')[0].LastIndexOf(".")+1) : it.Nome.Split(',')[0] : it.Nome,
                            Properties = doc.Descendants()
                                            .Where(d => d.Name.LocalName == "property" || d.Name.LocalName == "many-to-one" || d.Name.LocalName =="set")
                                            .Select(d => new PropertyModel()
                                            {
                                                Nome = d.Attribute("name").Value,
                                                Required = d.Attribute("not-null") == null ? false : d.Attribute("not-null").Value == "true",
                                                DataType = d.Attribute("type") ==null ? d.Attribute("name").Value : d.Attribute("type").Value,
                                                ColumnName = d.Attribute("column") == null ? null : d.Attribute("column").Value.Replace("`", ""),
                                                Length = d.Attribute("length") == null ? null : (int?)Int32.Parse(d.Attribute("length").Value.Replace("`", "")),
                                                DisplayName = d.Attribute("name").Value
                                            }).ToList()
                        };
                        entities.Add(entity);    
                        
                    });

                    foreach (LayerDefinition item in viewModel.Layers.Where(it=>it.Ativo  ))
                    {
                        foreach (var typedef in item.TypesDefinitions)
                        {
                            host = new TextTemplateHost() { TemplateFile = typedef.TemplatePath };
                            template = File.ReadAllText(typedef.TemplatePath);

                            foreach (EntityModel entity in entities)
                            {
                                host.Model = entity;
                                host.TypeDefinition = typedef;

                                filecontent = engine.ProcessTemplate(template, host);
                                

                                if (!Directory.Exists(typedef.OutputDir + "\\" + (typedef.DirectoryPerEntity ? "\\" + entity.ClassName + "\\" : "")))
                                    Directory.CreateDirectory(typedef.OutputDir + "\\" + (typedef.DirectoryPerEntity ? "\\" + entity.ClassName + "\\" : ""));
                               
                                if(host.Errors.HasErrors)
                                    File.WriteAllText(typedef.OutputDir + "\\" + (typedef.DirectoryPerEntity ? "\\" + entity.ClassName + "\\" : "") + typedef.Prefix + entity.ClassName + typedef.Sufix + ".cs", host.Errors.ToString());
                                else
                                    File.WriteAllText(typedef.OutputDir + "\\" + (typedef.DirectoryPerEntity ? "\\" + entity.ClassName + "\\" : "") + typedef.Prefix + entity.ClassName + typedef.Sufix + ".cs", filecontent);
                                
                            }
                        }
                        
                    }
                   
                },
                c => true);

            DataContext = viewModel;
        }
		public void HostReturnsEmptyContentOnCancelOutput()
		{
			Engine engine = new Engine();
			Store store = new Store(typeof(MockDomainModel));
			MockDomainModel domainModel = GetModel(store);

			using (Transaction t = store.TransactionManager.BeginTransaction())
			{
				ExtensibleMockModelElement serviceModel = new ExtensibleMockModelElement(store.DefaultPartition, string.Empty);
				TextTemplateHost host = new TextTemplateHost(domainModel, serviceModel, null);
				string templateContent = GetStandardTemplateHeader() + @"<# CancelOutput(); #>";

				string transformResult = engine.ProcessTemplate(templateContent, host);

				Assert.AreEqual<int>(0, host.CompilerErrors.Count);
				Assert.IsFalse(host.GenerateOutput);

				t.Rollback();
			}
		}
        /// <summary>
        /// Generate a default extension(".cs") file without renaming
        /// </summary>
        /// <param name="host"></param>
        /// <param name="engine"></param>
        /// <param name="fileName"></param>
        /// <param name="aliasName"></param>
        /// <param name="extension"></param>
        private void GenerateFileAsDefault(CustomerHost host, Engine engine, string fileName, string aliasName, string extension, int retryCount)
        {
            // if the extension is not null, then specify the output file extension
            // else use the default value(.cs) as the output file extension
            host.TemplateFileValue = fileName;
            if(extension != null)
            {
                host.SetFileExtension(extension);
            }

            string inputFileStreamName = fileName.Replace(templateRootDirection, "").TrimStart('\\').Replace('\\', '.');

            // if the aliasName is not null, then specify the output file as the alias name
            // else use the input file name(exclude the extension) as the fileName
            string outputFileName = aliasName ?? Path.GetFileNameWithoutExtension(fileName);

            // how to determine the output file's direction?
            // if the text template exists in the Assertion folder,then put the
            // output file to the Assertion folder, and if it exists in LTS folder,
            // put the output file to LTS folder, and so on
            // if the input file direction is null, then we define it ""
            string inputFileDirection = Path.GetDirectoryName(fileName)??string.Empty;

            string outputFileDirection;
            if (inputFileDirection.EndsWith("Main"))
            {
                outputFileDirection = solutionMainDirection;
            }
            else if (inputFileDirection.Contains("Main\\Properties"))
            {
                outputFileDirection = solutionMainPropertiesDirection;
            }
            else if (inputFileDirection.Contains("Properties"))
            {
                outputFileDirection = solutionPropertiesDirection;
            }
            else if (fileName.Contains("Assertions"))
            {
                // the assertions direction
                outputFileDirection = solutionAssertionDirection;
            }
            else if (fileName.Contains("Sample"))
            {
                // the LTS direction
                outputFileDirection = solutionLtsSampleDirection;
            }
            else if (fileName.Contains("LTS"))
            {
                // the LTS direction
                outputFileDirection = solutionLtsDirection;
            }
            else if (fileName.Contains("Ultility"))
            {
                // the ultility direction
                outputFileDirection = solutionUltilityDirection;
            }
            else if (fileName.EndsWith("PAT3 Source.ptt"))
            {
                // the ultility direction
                outputFileDirection = solutionRootDirection;
            }
            else
            {
                // if none of above, then put the output file to the home direction
                outputFileDirection = solutionHomeDirection;
            }

            outputFileName = Path.Combine(outputFileDirection, outputFileName) + host.FileExtension;

            Assembly myAssembly = Assembly.GetExecutingAssembly();
            Stream myStream = myAssembly.GetManifestResourceStream("PAT.GUI.Docs.Template." + inputFileStreamName);

            if (extension == "resources")
            {
                byte[] buf = new byte[myStream.Length];  //declare arraysize
                myStream.Read(buf, 0, buf.Length); // read from stream to byte array

                File.WriteAllBytes(outputFileName, buf);
            }
            else
            {
                StreamReader reader = new StreamReader(myStream);
                string text = reader.ReadToEnd();

                // use the engine to transfor the template
                string output = engine.ProcessTemplate(text, host);

                // write the generated file into the output file specified before
                // use the encoding style set in host
                File.WriteAllText(outputFileName, output, host.FileEncoding);

            }

            // after the generate, add the classes in the local classes field which will be used to
            // generate the .csproj file
            if (!inputFileDirection.Contains("\\Main") && !fileName.EndsWith("PAT3 Source.ptt") && retryCount == 1)
            {
                solutionClasses += outputFileName.Replace(solutionHomeDirection, "").TrimStart('\\') + "|";
            }

            // reset the host extension property
            host.ResetFileExtension();

            if (host.Errors.Count > 0)
            {
                if (retryCount <= RetryBound)
                {
                    GenerateFileAsDefault(host, engine, fileName, aliasName, extension, retryCount + 1);
                }
                else
                {
                    foreach (var error in host.Errors)
                    {
                        MessageBox.Show(
                            string.Format("File[{0}] is Generated unsuccessfully for: {1}", outputFileName, error),
                            Common.Utility.Utilities.APPLICATION_NAME, MessageBoxButtons.OK);
                    }
                }
            }
        }
Beispiel #32
0
        private void ProcessTemplate(params string[] args)
        {
            string templateFileName = null;

            if (args.Length == 0)
            {
                throw new System.Exception("you must provide a text template file path");
            }

            templateFileName = args[0];

            if (templateFileName == null)
            {
                throw new ArgumentNullException("the file name cannot be null");
            }

            if (!File.Exists(templateFileName))
            {
                throw new FileNotFoundException("the file cannot be found");
            }

            OnShowWorkInfoEventHandler(this, new WorkEventArgs(WorkStage.InitializeWork, string.Format("processing template: {0}", Path.GetFileName(templateFileName))));

            TextTemplatingSession session = new TextTemplatingSession();
            session.Add("t4Parameter", T4Parameters.Default);
            CustomCmdLineHost host = new CustomCmdLineHost();
            host.TemplateFileValue = templateFileName;
            host.Session = session;
            Engine engine = new Engine();
            //Read the text template.
            string input = File.ReadAllText(templateFileName);
            input = input.Replace(@"$(ProjectDir)\", "");
            //Transform the text template.
            string output = engine.ProcessTemplate(input, host);
            foreach (CompilerError error in host.Errors)
            {
                Console.WriteLine(error.ToString());
            }

            lock (synObject)
            {
                int prograssBarValue = OnGetValueEventHandler(this, null);
                prograssBarValue++;
                OnDoWorkEventHandler(this, new WorkEventArgs(WorkStage.DoWork, string.Format("{0} has been processed...", templateFileName), prograssBarValue){ TemplateName=Path.GetFileName(templateFileName)});
            }
        }
        private void BuildCodeByTableSchema(object item)
        {
            SOTable table = item as SOTable;
            List<SOColumn> columnList = table.ColumnList;//可能传入的是从PDObject对象转换过来的SODatabase对象
            if (columnList == null || columnList.Count == 0) columnList = DbSchemaHelper.Instance.CurrentSchema.GetTableColumnList(table);

            //生成代码文件
            TableHost host = new TableHost();
            host.Table = table;
            host.ColumnList = columnList;
            host.TemplateFile = templateFile;

            foreach (object obj in listBox3.Items)
            {
                string[] ss = obj.ToString().Split('|');

                host.SetValue(ss[0], ss[1].Replace("[<->]", "|"));
            }

            Engine engine = new Engine();

            string fileName = string.Empty;
            string separator = txtFileNamePrefix.Text.Trim();
            if (separator != "")
            {
                fileName = string.Format("{0}{1}", table.Name.RemovePrefix(separator,10), host.FileExtention);
            }
            else
            {
                fileName = string.Format("{0}{1}", table.Name, host.FileExtention);
            }

            string outputContent = engine.ProcessTemplate(File.ReadAllText(templateFile), host);
            string outputFile = Path.Combine(outputPath, fileName);

            StringBuilder sb = new StringBuilder();
            if (host.ErrorCollection.HasErrors)
            {
                foreach (CompilerError err in host.ErrorCollection)
                {
                    sb.AppendLine(err.ToString());
                }
                outputContent = outputContent + Environment.NewLine + sb.ToString();
                outputFile = outputFile + ".error";
            }

            if (Directory.Exists(outputPath) == false) Directory.CreateDirectory(outputPath);
            File.WriteAllText(outputFile, outputContent, Encoding.UTF8);
        }
Beispiel #34
0
        public void TestMethod1()
        {
            var templateString = @"
            <#@ template debug=""false"" hostspecific=""false"" language=""C#"" #>
            <#@ parameter name=""Column"" type=""Kooboo.CMS.Content.Models.Column"" #>
            <input name=""{0}"" type=""{1}"" value=""<%= Model["" <#= Column.Name #>""] %>"" />";

            Engine engine = new Engine();

            var host = new CustomCmdLineHost();
            host.Session = new TextTemplatingSession();
            host.Session["Column"] = new Column() { Name = "Column1" };
            string output = engine.ProcessTemplate(templateString, host);

            foreach (CompilerError item in host.Errors)
            {
                Console.WriteLine(item.ToString());
            }
            Console.WriteLine(output);
        }
        private void BuildCodeBySPSchema(object item)
        {
            SOCommand sp = item as SOCommand;
            //List<SOCommandParameter> paramList = DbSchemaHelper.Instance.CurrentSchema.GetCommandParameterList(sp);

            //生成代码文件
            CommandHost host = new CommandHost();
            host.SP = sp;
            //host.ParamList = paramList;
            host.TemplateFile = templateFile;

            foreach (object obj in listBox3.Items)
            {
                string[] ss = obj.ToString().Split('|');

                host.SetValue(ss[0], ss[1].Replace("[<->]", "|"));
            }

            Engine engine = new Engine();

            string fileName = string.Empty;
            string separator = txtFileNamePrefix.Text.Trim();
            if (separator != "")
            {
                fileName = string.Format("{0}{1}", sp.Name.RemovePrefix(separator, 10), host.FileExtention);
            }
            else
            {
                fileName = string.Format("{0}{1}", sp.Name, host.FileExtention);
            }

            string outputContent = engine.ProcessTemplate(File.ReadAllText(templateFile), host);
            string outputFile = Path.Combine(outputPath, fileName);

            StringBuilder sb = new StringBuilder();
            if (host.ErrorCollection.HasErrors)
            {
                foreach (CompilerError err in host.ErrorCollection)
                {
                    sb.AppendLine(err.ToString());
                }
                outputContent = outputContent + Environment.NewLine + sb.ToString();
                outputFile = outputFile + ".error";
            }

            if (Directory.Exists(outputPath) == false) Directory.CreateDirectory(outputPath);
            File.WriteAllText(outputFile, outputContent, Encoding.UTF8);
        }