Exemple #1
0
        public static string ProcessTemplate(string templateFile, IMarshalProperties objProperties)
        {
            string fileOutput = null;

            Microsoft.VisualStudio.TextTemplating.Engine e = new Microsoft.VisualStudio.TextTemplating.Engine();
            using (TemplateGenerationHost host = new TemplateGenerationHost())
            {
                SetCallContextData(objProperties);
                host.TemplateFileValue = templateFile;

                string fileContents = File.ReadAllText(templateFile);
                fileOutput = e.ProcessTemplate(fileContents, host);

                if (host.Errors.HasErrors)
                {
                    fileOutput = string.Empty;

                    foreach (var err in host.Errors)
                    {
                        fileOutput += "\r\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n";
                        fileOutput += err;
                    }
                }

                //clear out the context data we used in the template
                SetCallContextData(objProperties, true);
            }
            return(fileOutput);
        }
        private string Render(string templateCode, string templateFile)
        {
            EnvDTE.DTE vs       = this.GetService <EnvDTE.DTE>(true);
            string     basePath = this.GetBasePath();

            Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngine engine = new Microsoft.VisualStudio.TextTemplating.Engine();
            IValueInfoService service = (IValueInfoService)this.GetService(typeof(IValueInfoService));
            Dictionary <string, PropertyData> arguments = new Dictionary <string, PropertyData>();

            foreach (string str2 in base.additionalArguments.Keys)
            {
                Type type = null;
                try
                {
                    type = service.GetInfo(str2).Type;
                }
                catch (ArgumentException)
                {
                    if (base.additionalArguments[str2] != null)
                    {
                        type = base.additionalArguments[str2].GetType();
                    }
                    else
                    {
                        continue;
                    }
                }
                PropertyData data = new PropertyData(base.additionalArguments[str2], type);
                arguments.Add(str2, data);
            }
            TemplateHost host = new TemplateHost(basePath, arguments);

            host.TemplateFile = templateFile;
            Helpers.LogMessage(vs, this, templateFile);

            string str3 = engine.ProcessTemplate(templateCode, host);

            if (host.Errors.HasErrors)
            {
                string errors = "";
                foreach (CompilerError error in host.Errors)
                {
                    Helpers.LogMessage(vs, this, error.ErrorText);
                    errors += error.ErrorText + Environment.NewLine;
                }
                throw new TemplateException(host.Errors);
            }
            if (host.Errors.HasWarnings)
            {
                StringBuilder builder = new StringBuilder();
                foreach (CompilerError error in host.Errors)
                {
                    builder.AppendLine(error.ErrorText);
                }
                //Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "CompilationWarnings", new object[] { templateFile, builder.ToString() }));
            }
            return(str3);
        }
Exemple #3
0
        public static string ProcessTemplate(string templateFile, List <KeyValuePair <string, string> > templateProperties)
        {
            string fileOutput = null;

            Microsoft.VisualStudio.TextTemplating.Engine e = new Microsoft.VisualStudio.TextTemplating.Engine();
            using (TemplateGenerationHost host = new TemplateGenerationHost())
            {
                foreach (var tp in templateProperties)
                {
                    if (tp.Value != null)
                    {
                        CallContext.LogicalSetData(tp.Key.ToString(), tp.Value.ToString());
                    }
                }

                host.TemplateFileValue = templateFile;

                string fileContents = File.ReadAllText(templateFile);
                fileOutput = e.ProcessTemplate(fileContents, host);

                if (host.Errors.HasErrors)
                {
                    fileOutput = string.Empty;

                    foreach (var err in host.Errors)
                    {
                        fileOutput += "\r\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n";
                        fileOutput += err;
                    }
                }

                //clear out the context data we used in the template
                //SetCallContextData(objProperties, true);
            }
            return(fileOutput);
        }
        private string Render(string templateCode, string templateFile)
        {
            DTE vs = this.GetService<DTE>(true);
              string basePath = this.GetBasePath();
              Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngine engine = new Microsoft.VisualStudio.TextTemplating.Engine();
              IValueInfoService service = (IValueInfoService)this.GetService(typeof(IValueInfoService));
              Dictionary<string, PropertyData> arguments = new Dictionary<string, PropertyData>();
              foreach (string str2 in base.additionalArguments.Keys)
              {
            Type type = null;
            try
            {
              type = service.GetInfo(str2).Type;
            }
            catch (ArgumentException)
            {
              if (base.additionalArguments[str2] != null)
              {
                type = base.additionalArguments[str2].GetType();
              }
              else
              {
                continue;
              }
            }
            PropertyData data = new PropertyData(base.additionalArguments[str2], type);
            arguments.Add(str2, data);
              }
              TemplateHost host = new TemplateHost(basePath, arguments);
              host.TemplateFile = templateFile;
              Helpers.LogMessage(vs, this, templateFile);

              string str3 = engine.ProcessTemplate(templateCode, host);
              if (host.Errors.HasErrors)
              {
            string errors = "";
            foreach (CompilerError error in host.Errors)
            {
              Helpers.LogMessage(vs, this, error.ErrorText);
              errors += error.ErrorText + Environment.NewLine;
            }
            throw new TemplateException(host.Errors);
              }
              if (host.Errors.HasWarnings)
              {
            StringBuilder builder = new StringBuilder();
            foreach (CompilerError error in host.Errors)
            {
              builder.AppendLine(error.ErrorText);
            }
            //Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "CompilationWarnings", new object[] { templateFile, builder.ToString() }));
              }
              return str3;
        }
        /// <summary>
        /// /
        /// </summary>
        /// <param name="dte"></param>
        /// <param name="templateFileName"></param>
        /// <param name="resolver"></param>
        /// <returns></returns>
        public static Tuple<string, VisualStudioTextTemplateHost> ProcessTemplateInMemory(DTE2 dte, string templateFileName, IVariableResolver resolver)
        {
            if (dte == null)
            {
                throw new ArgumentNullException("dte");
            }
            if (string.IsNullOrEmpty(templateFileName) || !File.Exists(templateFileName))
            {
                throw new ArgumentException(Resources.Program_ProcessTemplateInMemory_String_is_null_or_empty_or_file_doesn_t_exist_, templateFileName);
            }

            //// This would be WAY more elegant, but it spawns a confirmation box...
            ////printfn "Transforming templates..."
            ////dte.ExecuteCommand("TextTransformation.TransformAllTemplates")

            Source.TraceEvent(TraceEventType.Information, 0, Resources.Program_ProcessTemplate_Processing___0_____, templateFileName);

            var templateDir = Path.GetDirectoryName(templateFileName);
            Debug.Assert(templateDir != null, "templateDir != null, don't expect templateFileName to be a root directory.");
            //  Setup Environment
            var oldDir = Environment.CurrentDirectory;
            try
            {
                Environment.CurrentDirectory = templateDir;

                // Setup NamespaceHint in CallContext
                var templateFileItem = dte.Solution.FindProjectItem(templateFileName);
                var project = templateFileItem.ContainingProject;
                var projectDir = Path.GetDirectoryName(project.FullName);
                Debug.Assert(projectDir != null, "projectDir != null, don't expect project.FullName to be a root directory.");
                string defaultNamespace = project.Properties.Item("DefaultNamespace").Value.ToString();
                var templateFileNameUpper = templateFileName.ToUpperInvariant();
                var projectDirUpper = projectDir.ToUpperInvariant();
                Debug.Assert(templateFileNameUpper.StartsWith(projectDirUpper, StringComparison.Ordinal), "Template file-name is not within the project directory.");

                var finalNamespace = defaultNamespace;
                if (templateDir.Length != projectDir.Length)
                {
                    var relativeNamespace =
                        templateDir.Substring(projectDir.Length + 1)
                            // BUG? Handle all namespace relevant characters
                            .Replace("\\", ".").Replace("/", ".");
                    finalNamespace =
                        string.Format(CultureInfo.InvariantCulture, "{0}.{1}", defaultNamespace, relativeNamespace);
                }

                using (new LogicalCallContextChange("NamespaceHint", finalNamespace))
                {

                    var host = new VisualStudioTextTemplateHost(templateFileName, dte, resolver);
                    var engine = new Engine();
                    var input = File.ReadAllText(templateFileName);
                    var output = engine.ProcessTemplate(input, host);
                    return Tuple.Create(output, host);
                }
            }
            finally
            {
                Environment.CurrentDirectory = oldDir;
            }
        }
        private void GenerateTemplate()
        {
            tabControl1.TabPages.Clear();

            Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngine engine = new Microsoft.VisualStudio.TextTemplating.Engine();
            Dictionary<string, PropertyData> arguments = new Dictionary<string, PropertyData>();

            PropertyData data = new PropertyData(bcsModel, typeof(BCSModel));
            arguments.Add("BCSModel", data);

            arguments.Add("ProjectNamespace", new PropertyData("BBS.Project1", typeof(String)));
            arguments.Add("BCSModelName", new PropertyData("Model1", typeof(String)));
            arguments.Add("BCSDatabase", new PropertyData("BCSTest", typeof(String)));
            arguments.Add("BCSModelDisplayName", new PropertyData("Model 1", typeof(String)));
            arguments.Add("BCSModelIsCached", new PropertyData(false, typeof(Boolean)));
            arguments.Add("BCSPermissions", new PropertyData("contoso\\Administrator", typeof(String)));
            arguments.Add("BCSServer", new PropertyData("demo2010a", typeof(String)));
            arguments.Add("BCSModelVersion", new PropertyData("1.0.0.0", typeof(String)));
            arguments.Add("BCSEstimatedCount", new PropertyData("10000", typeof(String)));
            arguments.Add("ProjectAssemblyName", new PropertyData("BCS.Test.Model", typeof(String)));
            arguments.Add("GeneratedFileName", new PropertyData("OutputFileName", typeof(String)));
            arguments.Add("CopyrightCompanyName", new PropertyData("Company", typeof(String)));

            arguments.Add("BCSType", new PropertyData("Wcf", typeof(String)));

            foreach (string templateFile in checkedListBox1.CheckedItems)
            {
                tabControl1.TabPages.Add(templateFile, templateFile);
                TextBox txtbox = new TextBox();
                txtbox.Multiline = true;
                txtbox.ScrollBars = ScrollBars.Both;
                txtbox.Dock = DockStyle.Fill;
                txtbox.WordWrap = false;
                tabControl1.TabPages[templateFile].Controls.Add(txtbox);

                string templateCode = File.ReadAllText(@"F:\TFS\SPSF\Dev\Source\SPALM.SPSF\Templates\Text\BCS\" + templateFile);
                StringBuilder templateCodeLines = new StringBuilder();
                StringReader reader = new StringReader(templateCode);
                string line = "";
                bool headerinserted = false;
                while ((line = reader.ReadLine()) != null)
                {
                    templateCodeLines.AppendLine(line);

                    if (!headerinserted)
                    {
                        headerinserted = true;
                        templateCodeLines.AppendLine("<#@ assembly name=\"System.dll\" #>");
                        templateCodeLines.AppendLine("<#@ assembly name=\"SPALM.SPSF.Library.dll\" #>");
                        templateCodeLines.AppendLine("<#@ import namespace=\"SPALM.SPSF.Library\" #>");
                        foreach (string argument in arguments.Keys)
                        {
                            templateCodeLines.AppendLine("<#@ property processor=\"PropertyProcessor\" name=\"" + argument + "\" #>");
                        }
                    }
                }

                templateCode = templateCodeLines.ToString();

                TemplateHost host = new TemplateHost(@"F:\TFS\SPSF\Dev\Source\SPALM.SPSF\", arguments);
                host.TemplateFile = @"Templates\Text\BCS\BCSModel_SQL.bdcm.t4";
                string str3 = engine.ProcessTemplate(templateCode, host);

                foreach (CompilerError error in host.Errors)
                {
                    txtbox.Text += error.ErrorText + "(" + error.Line + ")";
                }

                if (!host.Errors.HasErrors)
                {
                    if (str3.Contains("<?xml"))
                    {
                        XmlDocument result = new XmlDocument();
                        result.LoadXml(str3);

                        XmlWriterSettings wSettings = new XmlWriterSettings();
                        wSettings.Indent = true;
                        wSettings.NewLineOnAttributes = false;
                        wSettings.IndentChars = "\t";

                        string path = Path.GetTempFileName();

                        XmlWriter xw = XmlWriter.Create(path, wSettings);
                        result.Save(xw);
                        xw.Flush();
                        xw.Close();

                        txtbox.Text += File.ReadAllText(path);
                    }
                    else
                    {
                        txtbox.Text += str3;
                    }
                }
            }
        }
Exemple #7
0
        private void GenerateTemplate()
        {
            tabControl1.TabPages.Clear();

            Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngine engine = new Microsoft.VisualStudio.TextTemplating.Engine();
            Dictionary <string, PropertyData> arguments = new Dictionary <string, PropertyData>();

            PropertyData data = new PropertyData(bcsModel, typeof(BCSModel));

            arguments.Add("BCSModel", data);

            arguments.Add("ProjectNamespace", new PropertyData("BBS.Project1", typeof(String)));
            arguments.Add("BCSModelName", new PropertyData("Model1", typeof(String)));
            arguments.Add("BCSDatabase", new PropertyData("BCSTest", typeof(String)));
            arguments.Add("BCSModelDisplayName", new PropertyData("Model 1", typeof(String)));
            arguments.Add("BCSModelIsCached", new PropertyData(false, typeof(Boolean)));
            arguments.Add("BCSPermissions", new PropertyData("contoso\\Administrator", typeof(String)));
            arguments.Add("BCSServer", new PropertyData("demo2010a", typeof(String)));
            arguments.Add("BCSModelVersion", new PropertyData("1.0.0.0", typeof(String)));
            arguments.Add("BCSEstimatedCount", new PropertyData("10000", typeof(String)));
            arguments.Add("ProjectAssemblyName", new PropertyData("BCS.Test.Model", typeof(String)));
            arguments.Add("GeneratedFileName", new PropertyData("OutputFileName", typeof(String)));
            arguments.Add("CopyrightCompanyName", new PropertyData("Company", typeof(String)));

            arguments.Add("BCSType", new PropertyData("Wcf", typeof(String)));

            foreach (string templateFile in checkedListBox1.CheckedItems)
            {
                tabControl1.TabPages.Add(templateFile, templateFile);
                TextBox txtbox = new TextBox();
                txtbox.Multiline  = true;
                txtbox.ScrollBars = ScrollBars.Both;
                txtbox.Dock       = DockStyle.Fill;
                txtbox.WordWrap   = false;
                tabControl1.TabPages[templateFile].Controls.Add(txtbox);

                string        templateCode      = File.ReadAllText(@"F:\TFS\SPSF\Dev\Source\SPALM.SPSF\Templates\Text\BCS\" + templateFile);
                StringBuilder templateCodeLines = new StringBuilder();
                StringReader  reader            = new StringReader(templateCode);
                string        line           = "";
                bool          headerinserted = false;
                while ((line = reader.ReadLine()) != null)
                {
                    templateCodeLines.AppendLine(line);

                    if (!headerinserted)
                    {
                        headerinserted = true;
                        templateCodeLines.AppendLine("<#@ assembly name=\"System.dll\" #>");
                        templateCodeLines.AppendLine("<#@ assembly name=\"SPALM.SPSF.Library.dll\" #>");
                        templateCodeLines.AppendLine("<#@ import namespace=\"SPALM.SPSF.Library\" #>");
                        foreach (string argument in arguments.Keys)
                        {
                            templateCodeLines.AppendLine("<#@ property processor=\"PropertyProcessor\" name=\"" + argument + "\" #>");
                        }
                    }
                }

                templateCode = templateCodeLines.ToString();

                TemplateHost host = new TemplateHost(@"F:\TFS\SPSF\Dev\Source\SPALM.SPSF\", arguments);
                host.TemplateFile = @"Templates\Text\BCS\BCSModel_SQL.bdcm.t4";
                string str3 = engine.ProcessTemplate(templateCode, host);

                foreach (CompilerError error in host.Errors)
                {
                    txtbox.Text += error.ErrorText + "(" + error.Line + ")";
                }

                if (!host.Errors.HasErrors)
                {
                    if (str3.Contains("<?xml"))
                    {
                        XmlDocument result = new XmlDocument();
                        result.LoadXml(str3);

                        XmlWriterSettings wSettings = new XmlWriterSettings();
                        wSettings.Indent = true;
                        wSettings.NewLineOnAttributes = false;
                        wSettings.IndentChars         = "\t";

                        string path = Path.GetTempFileName();

                        XmlWriter xw = XmlWriter.Create(path, wSettings);
                        result.Save(xw);
                        xw.Flush();
                        xw.Close();

                        txtbox.Text += File.ReadAllText(path);
                    }
                    else
                    {
                        txtbox.Text += str3;
                    }
                }
            }
        }
        /// <summary>
        /// /
        /// </summary>
        /// <param name="dte"></param>
        /// <param name="templateFileName"></param>
        /// <param name="resolver"></param>
        /// <returns></returns>
        public static Tuple <string, VisualStudioTextTemplateHost> ProcessTemplateInMemory(DTE2 dte, string templateFileName, IVariableResolver resolver)
        {
            if (dte == null)
            {
                throw new ArgumentNullException("dte");
            }
            if (string.IsNullOrEmpty(templateFileName) || !File.Exists(templateFileName))
            {
                throw new ArgumentException(Resources.Program_ProcessTemplateInMemory_String_is_null_or_empty_or_file_doesn_t_exist_, templateFileName);
            }

            //// This would be WAY more elegant, but it spawns a confirmation box...
            ////printfn "Transforming templates..."
            ////dte.ExecuteCommand("TextTransformation.TransformAllTemplates")

            Source.TraceEvent(TraceEventType.Information, 0, Resources.Program_ProcessTemplate_Processing___0_____, templateFileName);

            var templateDir = Path.GetDirectoryName(templateFileName);

            Debug.Assert(templateDir != null, "templateDir != null, don't expect templateFileName to be a root directory.");
            //  Setup Environment
            var oldDir = Environment.CurrentDirectory;

            try
            {
                Environment.CurrentDirectory = templateDir;

                // Setup NamespaceHint in CallContext
                var templateFileItem = dte.Solution.FindProjectItem(templateFileName);
                var project          = templateFileItem.ContainingProject;
                var projectDir       = Path.GetDirectoryName(project.FullName);
                Debug.Assert(projectDir != null, "projectDir != null, don't expect project.FullName to be a root directory.");
                string defaultNamespace      = project.Properties.Item("DefaultNamespace").Value.ToString();
                var    templateFileNameUpper = templateFileName.ToUpperInvariant();
                var    projectDirUpper       = projectDir.ToUpperInvariant();
                Debug.Assert(templateFileNameUpper.StartsWith(projectDirUpper, StringComparison.Ordinal), "Template file-name is not within the project directory.");

                var finalNamespace = defaultNamespace;
                if (templateDir.Length != projectDir.Length)
                {
                    var relativeNamespace =
                        templateDir.Substring(projectDir.Length + 1)
                        // BUG? Handle all namespace relevant characters
                        .Replace("\\", ".").Replace("/", ".");
                    finalNamespace =
                        string.Format(CultureInfo.InvariantCulture, "{0}.{1}", defaultNamespace, relativeNamespace);
                }

                using (new LogicalCallContextChange("NamespaceHint", finalNamespace))
                {
                    var host   = new VisualStudioTextTemplateHost(templateFileName, dte, resolver);
                    var engine = new Engine();
                    var input  = File.ReadAllText(templateFileName);
                    var output = engine.ProcessTemplate(input, host);
                    return(Tuple.Create(output, host));
                }
            }
            finally
            {
                Environment.CurrentDirectory = oldDir;
            }
        }