public void DoGenerateDbContext(DTE2 Dte, ITextTemplating textTemplating, string templatePath, string DestinationNameSpace, string DestinationClassName) { this.GenerateText = ""; this.GenerateError = ""; OnPropertyChanged("GenerateText"); OnPropertyChanged("GenerateError"); ITextTemplatingSessionHost textTemplatingSessionHost = (ITextTemplatingSessionHost)textTemplating; textTemplatingSessionHost.Session = textTemplatingSessionHost.CreateSession(); TPCallback tpCallback = new TPCallback(); textTemplatingSessionHost.Session["DestinationNameSpace"] = DestinationNameSpace; textTemplatingSessionHost.Session["DestinationClassName"] = DestinationClassName; if (string.IsNullOrEmpty(GenText)) { this.GenerateText = textTemplating.ProcessTemplate(templatePath, File.ReadAllText(templatePath), tpCallback); } else { this.GenerateText = textTemplating.ProcessTemplate(templatePath, GenText, tpCallback); } FileExtension = tpCallback.FileExtension; if (tpCallback.ProcessingErrors != null) { foreach (TPError tpError in tpCallback.ProcessingErrors) { this.GenerateError = tpError.ToString() + "\n"; } } OnPropertyChanged("GenerateText"); OnPropertyChanged("GenerateError"); IsReady.DoNotify(this, string.IsNullOrEmpty(this.GenerateError)); }
public void DoGenerateViewModel(DTE2 Dte, ITextTemplating textTemplating, SelectedItem DestinationSelectedItem, string T4TempatePath, ModelView modelView) { this.GenerateText = ""; this.GenerateError = ""; GeneratedModelView = new ModelViewSerializable(); modelView.ModelViewAssingTo(GeneratedModelView); ITextTemplatingSessionHost textTemplatingSessionHost = (ITextTemplatingSessionHost)textTemplating; textTemplatingSessionHost.Session = textTemplatingSessionHost.CreateSession(); TPCallback tpCallback = new TPCallback(); textTemplatingSessionHost.Session["Model"] = GeneratedModelView; if (string.IsNullOrEmpty(GenText)) { this.GenerateText = textTemplating.ProcessTemplate(T4TempatePath, File.ReadAllText(T4TempatePath), tpCallback); } else { this.GenerateText = textTemplating.ProcessTemplate(T4TempatePath, GenText, tpCallback); } FileExtension = tpCallback.FileExtension; if (tpCallback.ProcessingErrors != null) { foreach (TPError tpError in tpCallback.ProcessingErrors) { this.GenerateError = tpError.ToString() + "\n"; } } IsReady.DoNotify(this, string.IsNullOrEmpty(this.GenerateError)); }
public static GeneratorBatchStep DoGenerateViewModel(DTE2 Dte, ITextTemplating textTemplating, string T4TempatePath, DbContextSerializable SerializableDbContext, ModelViewSerializable model, string defaultProjectNameSpace = null) { GeneratorBatchStep result = new GeneratorBatchStep() { GenerateText = "", GenerateError = "", FileExtension = "", T4TempatePath = T4TempatePath, }; if ((model == null) || (SerializableDbContext == null)) { result.GenerateError = "Model and/or Context is not defined"; return(result); } ITextTemplatingSessionHost textTemplatingSessionHost = (ITextTemplatingSessionHost)textTemplating; textTemplatingSessionHost.Session = textTemplatingSessionHost.CreateSession(); TPCallback tpCallback = new TPCallback(); textTemplatingSessionHost.Session["Model"] = model; textTemplatingSessionHost.Session["Context"] = SerializableDbContext; textTemplatingSessionHost.Session["DefaultProjectNameSpace"] = string.IsNullOrEmpty(defaultProjectNameSpace) ? "" : defaultProjectNameSpace; result.GenerateText = textTemplating.ProcessTemplate(T4TempatePath, File.ReadAllText(result.T4TempatePath), tpCallback); result.FileExtension = tpCallback.FileExtension; if (tpCallback.ProcessingErrors != null) { foreach (TPError tpError in tpCallback.ProcessingErrors) { result.GenerateError += tpError.ToString() + "\n"; } } return(result); }
public string Process([NotNull] string templateFileName) { Assert.ArgumentNotNull(templateFileName, nameof(templateFileName)); ITextTemplating t4 = null; ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); t4 = SitecorePackage.Instance.GetService <STextTemplating>() as ITextTemplating; }); var sessionHost = t4 as ITextTemplatingSessionHost; if (sessionHost == null) { return("// Failed to instantiate Text Templating Engine"); } var templateContents = AppHost.Files.ReadAllText(templateFileName); sessionHost.Session = sessionHost.CreateSession(); // sessionHost.Session["fileCodeModel"] = new FileCodeModel(fileCodeModel); return(t4.ProcessTemplate(templateFileName, templateContents)); }
public string GeneratePrimKeyStatement() { ITextTemplatingSessionHost textTemplatingSessionHost = (ITextTemplatingSessionHost)textTemplating; textTemplatingSessionHost.Session = textTemplatingSessionHost.CreateSession(); TPCallback tpCallback = new TPCallback(); List <string> primKeyProperties = new List <string>(); foreach (FluentAPIExtendedProperty itm in this.PrimaryKeyProperties) { primKeyProperties.Add(itm.PropName); } string tempatePath = Path.Combine(TemplateFolder, SelectedTemplate); textTemplatingSessionHost.Session["PrimKeyProperties"] = primKeyProperties; string result = textTemplating.ProcessTemplate(tempatePath, T4TempateText, tpCallback); if (tpCallback.ProcessingErrors != null) { if (tpCallback.ProcessingErrors.Count > 0) { string GenerateError = "Error: "; foreach (TPError tpError in tpCallback.ProcessingErrors) { GenerateError = GenerateError + tpError.ToString() + "\n"; } MessageBox.Show(GenerateError, "Error", MessageBoxButton.OK, MessageBoxImage.Error); return(null); } } return(result); }
public static string ProcessTemplateCore(string templatePath, string templateContent, Context context, out string extension) { extension = null; // Get the text template service: ITextTemplating t4 = Package.GetGlobalService(typeof(STextTemplating)) as ITextTemplating; ITextTemplatingSessionHost sessionHost = t4 as ITextTemplatingSessionHost; // Create a Session in which to pass parameters: sessionHost.Session = sessionHost.CreateSession(); sessionHost.Session["Context"] = context; // string templateContent = System.IO.File.ReadAllText(templatePath); Callback cb = new Callback(); // Process a text template: string result = t4.ProcessTemplate(templatePath, templateContent, cb); // If there was an output directive in the TemplateFile, then cb.SetFileExtension() will have been called. if (!string.IsNullOrWhiteSpace(cb.FileExtension)) { extension = cb.FileExtension; } // Append any error messages: if (cb.ErrorMessages.Count > 0) { result = cb.ErrorMessages.ToString(); } return(result); }
public static string ProcessTextTemplate( string tt_filepath, Dictionary <string, Object> parameters ) { // Get a service provider - how you do this depends on the context: ServiceProvider serviceProvider = new ServiceProvider( ExtContext.Instance.Dte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider); ITextTemplating t4 = serviceProvider.GetService(typeof(STextTemplating)) as ITextTemplating; ITextTemplatingSessionHost host = t4 as ITextTemplatingSessionHost; // Create a Session in which to pass parameters: host.Session = host.CreateSession(); // Add parameter values to the Session: foreach (var parm in parameters) { host.Session[parm.Key] = parm.Value; } var output = ExtContext.Instance.GetOutputPane(); output.OutputStringThreadSafe("Invoking text template processor...\n"); // Process a text template: string result = t4.ProcessTemplate(tt_filepath, System.IO.File.ReadAllText(tt_filepath)); output.OutputStringThreadSafe("Template processing completed.\n"); return(result); }
private string ProcessTemplate(string inputFile, TextTemplatingCallback handler) { var output = _host.ProcessTemplate( inputFile, File.ReadAllText(inputFile), handler); foreach (CompilerError error in handler.Errors) { var builder = new StringBuilder(); if (!string.IsNullOrEmpty(error.FileName)) { builder.Append(error.FileName); if (error.Line > 0) { builder .Append("(") .Append(error.Line); if (error.Column > 0) { builder .Append(",") .Append(error.Line); } builder.Append(")"); } builder.Append(" : "); } builder .Append(error.IsWarning ? "warning" : "error") .Append(" ") .Append(error.ErrorNumber) .Append(": ") .AppendLine(error.ErrorText); if (error.IsWarning) { _reporter.WriteWarning(builder.ToString()); } else { _reporter.WriteError(builder.ToString()); } } if (handler.OutputEncoding != Encoding.UTF8) { _reporter.WriteWarning(DesignStrings.EncodingIgnored(handler.OutputEncoding.WebName)); } return(output); }
public string GenerateForeignKeyStatement() { if ((EntityNonScalarPropertiesIndex < 0) || (EntityNonScalarProperties.Count <= EntityNonScalarPropertiesIndex)) { return(null); } if ((PrincipalNonScalarPropertiesIndex < 0) || (PrincipalNonScalarProperties.Count <= PrincipalNonScalarPropertiesIndex)) { return(null); } if ((ForeignKeyTypesIndex < 0) || (ForeignKeyTypes.Count <= ForeignKeyTypesIndex)) { return(null); } ITextTemplatingSessionHost textTemplatingSessionHost = (ITextTemplatingSessionHost)textTemplating; textTemplatingSessionHost.Session = textTemplatingSessionHost.CreateSession(); TPCallback tpCallback = new TPCallback(); List <string> foreignKeyProperties = new List <string>(); foreach (FluentAPIExtendedProperty itm in this.ForeignKeyProperties) { foreignKeyProperties.Add(itm.PropName); } string tempatePath = ""; //Path.Combine(TemplateFolder, SelectedTemplate); textTemplatingSessionHost.Session["MasterClassFullName"] = masterCodeClassFullName; textTemplatingSessionHost.Session["IsRequired"] = (ForeignKeyTypes[ForeignKeyTypesIndex] == NavigationTypeEnum.OneToMany) || (ForeignKeyTypes[ForeignKeyTypesIndex] == NavigationTypeEnum.OneToOne); textTemplatingSessionHost.Session["WillCascadeOnDelete"] = IsCascadeOnDelete; textTemplatingSessionHost.Session["NavigationName"] = EntityNonScalarProperties[EntityNonScalarPropertiesIndex]; textTemplatingSessionHost.Session["InverseNavigationName"] = PrincipalNonScalarProperties[PrincipalNonScalarPropertiesIndex].PropName; textTemplatingSessionHost.Session["ForeignKeyProperties"] = foreignKeyProperties; string result = textTemplating.ProcessTemplate(tempatePath, T4TempateText, tpCallback); if (tpCallback.ProcessingErrors != null) { if (tpCallback.ProcessingErrors.Count > 0) { string GenerateError = "Error: "; foreach (TPError tpError in tpCallback.ProcessingErrors) { GenerateError = GenerateError + tpError.ToString() + "\n"; } MessageBox.Show(GenerateError, "Error", MessageBoxButton.OK, MessageBoxImage.Error); return(null); } } return(result); }
public static async Task AddGeneratedCodeAsync( ConnectedServiceHandlerContext context, Project project, string templateFileName, string outputDirectory, Func <ITextTemplatingSessionHost, IEnumerable <ITextTemplatingSession> > getSessions, Func <IPreprocessedT4Template> getPreprocessedT4Template, Func <ITextTemplatingSession, string> getArtifactName) { string templatePath = Path.Combine( RegistryHelper.GetCurrentUsersVisualStudioLocation(), "Templates\\ConnectedServiceTemplates\\Visual C#\\Salesforce", templateFileName + ".tt"); bool useCustomTemplate = File.Exists(templatePath); SalesforceConnectedServiceInstance salesforceInstance = (SalesforceConnectedServiceInstance)context.ServiceInstance; salesforceInstance.TelemetryHelper.TrackCodeGeneratedEvent(salesforceInstance, templateFileName, useCustomTemplate); ITextTemplating textTemplating = GeneratedCodeHelper.TextTemplating; ITextTemplatingSessionHost sessionHost = (ITextTemplatingSessionHost)textTemplating; Func <ITextTemplatingSession, string> generateText; if (useCustomTemplate) { // The current user has a customized template, process and use it. string customTemplate = File.ReadAllText(templatePath); generateText = (session) => { sessionHost.Session = session; return(textTemplating.ProcessTemplate(templatePath, customTemplate)); }; } else { // No customized template exists for the current user, use the preprocessed one for increased performance. generateText = (session) => { IPreprocessedT4Template t4Template = getPreprocessedT4Template(); t4Template.Session = session; t4Template.Initialize(); return(t4Template.TransformText()); }; } foreach (ITextTemplatingSession session in getSessions(sessionHost)) { string generatedText = generateText(session); string tempFileName = GeneratedCodeHelper.CreateTempFile(generatedText); string targetPath = Path.Combine(outputDirectory, getArtifactName(session) + ".cs"); await context.HandlerHelper.AddFileAsync(tempFileName, targetPath); } }
protected internal virtual void TransformTemplateToFile(ITextTemplatingSession session, ProjectItem groupDirectoryProjectItem, string templatePath, string templateContent, string typeName) { string directoryPath = _solutionManager.GetProjectItemFullPath(groupDirectoryProjectItem); _textTemplatingSessionHost.Session = session; string transformedTemplate = _textTemplating.ProcessTemplate(templatePath, templateContent); string newFilePath = WriteToFile(directoryPath, typeName, transformedTemplate); _solutionManager.AddFileToDirectoryProjectItem(groupDirectoryProjectItem, newFilePath); }
public static async System.Threading.Tasks.Task GenerateCodeFromTemplateAndAddToProject( ConnectedServiceHandlerContext context, string templateFileName, string targetPath, IDictionary <string, object> parameters) { ITextTemplating t4 = TextTemplating; ITextTemplatingSessionHost sessionHost = (ITextTemplatingSessionHost)t4; sessionHost.Session = sessionHost.CreateSession(); if (parameters != null) { foreach (string key in parameters.Keys) { sessionHost.Session[key] = parameters[key]; } } await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Opening the template '{0}'", templateFileName); //Stream templateStream = File.OpenRead( // string.Format(@"Content\{0}.tt", templateFileName) // ); Stream templateStream = Assembly.GetAssembly(typeof(GeneratedCodeHelper)) .GetManifestResourceStream( string.Format("AspNet.WebHooks.ConnectedService.Content.{0}.tt", templateFileName) ); if (templateStream == null) { throw new Exception("Could not find code generation template"); } string templateContent = new StreamReader(templateStream).ReadToEnd(); await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Generating code from template '{0}'", templateFileName); string generatedCode = t4.ProcessTemplate("", templateContent, new T4Callback(context)); string tempFile = CreateTempFile(generatedCode); await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding code generated from template '{0}' as new file {1}", templateFileName, targetPath); await context.HandlerHelper.AddFileAsync(tempFile, targetPath); }
public void DoGenerateFeature(DTE2 Dte, ITextTemplating textTemplating, string T4TempatePath, DbContextSerializable SerializableDbContext, FeatureContextSerializable SerializableFeatureContext, FeatureSerializable feature, AllowedFileTypesSerializable AllowedFileTypes, string defaultProjectNameSpace = null) { this.GenerateText = ""; this.GenerateError = ""; IsReady.DoNotify(this, false); if ((feature == null) || (SerializableDbContext == null) || (SerializableFeatureContext == null)) { return; } GeneratedFeature = feature; ITextTemplatingSessionHost textTemplatingSessionHost = (ITextTemplatingSessionHost)textTemplating; textTemplatingSessionHost.Session = textTemplatingSessionHost.CreateSession(); TPCallback tpCallback = new TPCallback(); textTemplatingSessionHost.Session["AllowedFileTypes"] = AllowedFileTypes; textTemplatingSessionHost.Session["Feature"] = GeneratedFeature; textTemplatingSessionHost.Session["FeatureContext"] = SerializableFeatureContext; textTemplatingSessionHost.Session["Context"] = SerializableDbContext; textTemplatingSessionHost.Session["DefaultProjectNameSpace"] = string.IsNullOrEmpty(defaultProjectNameSpace) ? "" : defaultProjectNameSpace; if (string.IsNullOrEmpty(GenText)) { this.GenerateText = textTemplating.ProcessTemplate(T4TempatePath, File.ReadAllText(T4TempatePath), tpCallback); } else { this.GenerateText = textTemplating.ProcessTemplate(T4TempatePath, GenText, tpCallback); } FileExtension = tpCallback.FileExtension; if (tpCallback.ProcessingErrors != null) { foreach (TPError tpError in tpCallback.ProcessingErrors) { this.GenerateError += tpError.ToString() + "\n"; } } IsReady.DoNotify(this, string.IsNullOrEmpty(this.GenerateError)); }
public static string ProcessTemplate(string templatePath, Context context) { // Get the text template service: ITextTemplating t4 = Package.GetGlobalService(typeof(STextTemplating)) as ITextTemplating; ITextTemplatingSessionHost sessionHost = t4 as ITextTemplatingSessionHost; // Create a Session in which to pass parameters: sessionHost.Session = sessionHost.CreateSession(); sessionHost.Session["Context"] = context; string templateContent = System.IO.File.ReadAllText(templatePath); Callback cb = new Callback(); // Process a text template: string result = t4.ProcessTemplate(templatePath, templateContent, cb); string OutputFullPath; if (!string.IsNullOrWhiteSpace(cb.FileExtension)) { // If there was an output directive in the TemplateFile, then cb.SetFileExtension() will have been called. OutputFullPath = System.IO.Path.ChangeExtension(templatePath, cb.FileExtension); } else { OutputFullPath = System.IO.Path.ChangeExtension(templatePath, ".cs"); } // Write the processed output to file: // UpdateStatus("Writing......", true); System.IO.File.WriteAllText(OutputFullPath, result, cb.OutputEncoding); // Append any error messages: if (cb.ErrorMessages.Count > 0) { System.IO.File.AppendAllLines(OutputFullPath, cb.ErrorMessages.Select(x => x.Message)); } string errroMessage = null; if (cb.ErrorMessages.Count > 0) { errroMessage = "Unable to generate file see " + OutputFullPath + " for more details "; } return(errroMessage); }
public void ProcessFileWithTemplate(string name, string fullPathToScript) { if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(fullPathToScript)) { return; } try { ITextTemplating textTemplatingService = ServiceProvider.GlobalProvider.GetService(typeof(STextTemplating)) as ITextTemplating; if (textTemplatingService != null) { var templatingComponents = (ITextTemplatingComponents)textTemplatingService; DefineSessionParametrs(name, textTemplatingService); var output = textTemplatingService.ProcessTemplate(fullPathToScript, File.ReadAllText(fullPathToScript), this, templatingComponents.Hierarchy); Clipboard.SetText(output); } } catch (Exception) { Debug.WriteLine("Can't ProcessFileWithTemplate( {0} , {1} )", name, fullPathToScript); } }
private void GenerateMVCItems(VSProject vsProj) { if (string.IsNullOrEmpty(WizardForm.ConnectionStringForModel)) { return; } if (WizardForm.SelectedTables == null || WizardForm.SelectedTables.Count == 0) { return; } #if CLR4 || NET_40_OR_GREATER IServiceProvider serviceProvider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)Dte); ITextTemplating t4 = serviceProvider.GetService(typeof(STextTemplating)) as ITextTemplating; ITextTemplatingSessionHost sessionHost = t4 as ITextTemplatingSessionHost; var controllerClassPath = string.Empty; var IndexFilePath = string.Empty; var fileExtension = string.Empty; Version productVersion = Assembly.GetExecutingAssembly().GetName().Version; var version = String.Format("{0}.{1}.{2}", productVersion.Major, productVersion.Minor, productVersion.Build); double visualStudioVersion = double.Parse(WizardForm.Wizard.GetVisualStudioVersion()); if (Language == LanguageGenerator.CSharp) { controllerClassPath = Path.GetFullPath(@"..\IDE\Extensions\Oracle\MySQL for Visual Studio\" + version + @"\T4Templates\CSharp\CSharpControllerClass.tt"); IndexFilePath = Path.GetFullPath(@"..\IDE\Extensions\Oracle\MySQL for Visual Studio\" + version + @"\T4Templates\CSharp\CSharpIndexFile.tt"); fileExtension = "cs"; } else { controllerClassPath = Path.GetFullPath(@"..\IDE\Extensions\Oracle\MySQL for Visual Studio\" + version + @"\T4Templates\VisualBasic\VisualBasicControllerClass.tt"); IndexFilePath = Path.GetFullPath(@"..\IDE\Extensions\Oracle\MySQL for Visual Studio\" + version + @"\T4Templates\VisualBasic\VisualBasicIndexFile.tt"); fileExtension = "vb"; } StringBuilder catalogs = new StringBuilder(); catalogs = new StringBuilder("<h3> Catalog list</h3>"); catalogs.AppendLine(); foreach (var table in TablesIncludedInModel) { catalogs.AppendLine(string.Format(@"<div> @Html.ActionLink(""{0}"",""Index"", ""{0}"")</div>", table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1))); } string indexPath = Language == LanguageGenerator.CSharp ? (string)(FindProjectItem(FindProjectItem(FindProjectItem(vsProj.Project.ProjectItems, "Views").ProjectItems, "Home").ProjectItems, "Index.cshtml").Properties.Item("FullPath").Value) : (string)(FindProjectItem(FindProjectItem(FindProjectItem(vsProj.Project.ProjectItems, "Views").ProjectItems, "Home").ProjectItems, "Index.vbhtml").Properties.Item("FullPath").Value); string contents = File.ReadAllText(indexPath); contents = contents.Replace("$catalogList$", catalogs.ToString()); File.WriteAllText(indexPath, contents); try { foreach (var table in TablesIncludedInModel) { // creating controller file sessionHost.Session = sessionHost.CreateSession(); sessionHost.Session["namespaceParameter"] = string.Format("{0}.Controllers", ProjectNamespace); sessionHost.Session["applicationNamespaceParameter"] = string.Format("{0}.Models", ProjectNamespace); sessionHost.Session["controllerClassParameter"] = string.Format("{0}Controller", table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1)); if ((WizardForm.DEVersion == DataEntityVersion.EntityFramework6 && Language == LanguageGenerator.VBNET) || Language == LanguageGenerator.CSharp) { sessionHost.Session["modelNameParameter"] = string.Format("{0}Entities", WizardForm.ConnectionStringNameForModel); } else if (WizardForm.DEVersion == DataEntityVersion.EntityFramework5 && Language == LanguageGenerator.VBNET) { sessionHost.Session["modelNameParameter"] = string.Format("{1}.{0}Entities", WizardForm.ConnectionStringNameForModel, ProjectNamespace); } sessionHost.Session["classNameParameter"] = table.Key; sessionHost.Session["entityNameParameter"] = table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1); sessionHost.Session["entityClassNameParameter"] = table.Key; if ((visualStudioVersion < 12.0 && Language == LanguageGenerator.VBNET) || Language == LanguageGenerator.CSharp) { sessionHost.Session["entityClassNameParameterWithNamespace"] = string.Format("{0}.{1}", ProjectNamespace, table.Key); } else if (Language == LanguageGenerator.VBNET && visualStudioVersion >= 12.0) { if (WizardForm.DEVersion == DataEntityVersion.EntityFramework5) { sessionHost.Session["entityClassNameParameterWithNamespace"] = string.Format("{0}.{0}.{1}", ProjectNamespace, table.Key); } else if (WizardForm.DEVersion == DataEntityVersion.EntityFramework6) { sessionHost.Session["entityClassNameParameterWithNamespace"] = string.Format("{0}.{1}", ProjectNamespace, table.Key); } } T4Callback cb = new T4Callback(); StringBuilder resultControllerFile = new StringBuilder(t4.ProcessTemplate(controllerClassPath, File.ReadAllText(controllerClassPath), cb)); string controllerFilePath = ProjectPath + string.Format(@"\Controllers\{0}Controller.{1}", table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1), fileExtension); File.WriteAllText(controllerFilePath, resultControllerFile.ToString()); if (cb.errorMessages.Count > 0) { File.AppendAllLines(controllerFilePath, cb.errorMessages); } vsProj.Project.ProjectItems.AddFromFile(controllerFilePath); var viewPath = Path.GetFullPath(ProjectPath + string.Format(@"\Views\{0}", table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1))); Directory.CreateDirectory(viewPath); string resultViewFile = t4.ProcessTemplate(IndexFilePath, File.ReadAllText(IndexFilePath), cb); File.WriteAllText(string.Format(viewPath + @"\Index.{0}html", fileExtension), resultViewFile); if (cb.errorMessages.Count > 0) { File.AppendAllLines(controllerFilePath, cb.errorMessages); } vsProj.Project.ProjectItems.AddFromFile(string.Format(viewPath + @"\Index.{0}html", fileExtension)); } } catch { InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ErrorTitle, Resources.ItemTemplatesBaseWebWizard_GenerateMvcItemsError)); } #endif }
public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress) { if (bstrInputFileContents == null) { throw new ArgumentException(bstrInputFileContents); } Status.Clear(); var originalFile = GetOriginalFile(wszInputFilePath); PromptToRefreshEntities(); if (context == null) { DTE2 dte = Package.GetGlobalService(typeof(SDTE)) as EnvDTE80.DTE2; settings = ConfigurationFile.ReadFromJsonFile(dte); Login m = new Login(dte, settings); m.ShowDialog(); context = m.Context; ConfigurationFile.WriteToJsonFile(dte, m.settings); m = null; if (context == null) { // TODO pGenerateProgress.GeneratorError(1, (uint)1, "Code generation for CRM Template aborted", uint.MaxValue, uint.MaxValue); if (originalFile == null) { SaveOutputContent(rgbOutputFileContents, out pcbOutput, ""); } else { // http://social.msdn.microsoft.com/Forums/vstudio/en-US/d8d72da3-ddb9-4811-b5da-2a167bbcffed/ivssinglefilegenerator-cancel-code-generation // I don't think a login failure would be considered a invalid model, so we'll restore what was there SaveOutputContent(rgbOutputFileContents, out pcbOutput, System.IO.File.ReadAllText(originalFile)); } return(VSConstants.S_OK); } } Status.Update("Generating code from template... "); ITextTemplating t4 = Package.GetGlobalService(typeof(STextTemplating)) as ITextTemplating; ITextTemplatingSessionHost sessionHost = t4 as ITextTemplatingSessionHost; context.Namespace = wszDefaultNamespace; sessionHost.Session = sessionHost.CreateSession(); sessionHost.Session["Context"] = context; Callback cb = new Callback(); t4.BeginErrorSession(); string content = t4.ProcessTemplate(wszInputFilePath, bstrInputFileContents, cb); t4.EndErrorSession(); // If there was an output directive in the TemplateFile, then cb.SetFileExtension() will have been called. if (!string.IsNullOrWhiteSpace(cb.FileExtension)) { extension = cb.FileExtension; } Status.Update("Writing code to disk... "); SaveOutputContent(rgbOutputFileContents, out pcbOutput, content); // Append any error/warning to output window foreach (var err in cb.ErrorMessages) { // The templating system (eg t4.ProcessTemplate) will automatically add error/warning to the ErrorList Status.Update("[" + (err.Warning == true ? "WARN" : "ERROR") + "] " + err.Message + " " + err.Line + "," + err.Column); } if (cb.ErrorMessages.Any(em => em.Warning == false)) { Configuration.Instance.DTE.ExecuteCommand("View.ErrorList"); } else { Status.Update("Done!"); } return(VSConstants.S_OK); }
string ProcessTemplate(ITextTemplating t4, string template) { var templateFile = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(GetType()).Location), "Templates", template); return(t4.ProcessTemplate(templateFile, File.ReadAllText(templateFile))); }
protected virtual string ProcessTemplate(string inputFileName, string inputFileContent, ITextTemplating processor, IVsHierarchy hierarchy) { return(processor.ProcessTemplate(inputFileName, inputFileContent, this, hierarchy)); }