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 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 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 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 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); }
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); }
private static IEnumerable <ITextTemplatingSession> GetServiceT4Sessions(ITextTemplatingSessionHost host, GeneratedService generatedService) { ITextTemplatingSession session = host.CreateSession(); session["generatedService"] = generatedService; yield return(session); }
public TemplateService(ITextTemplatingSessionHost textTemplatingSessionHost, ITextTemplatingEngineHost textTemplatingEngineHost, ITextTemplating textTemplating) { TextTemplatingSessionHost = textTemplatingSessionHost; TextTemplatingEngineHost = textTemplatingEngineHost; TextTemplating = textTemplating; }
private static IEnumerable <ITextTemplatingSession> GetObjectT4Sessions(ITextTemplatingSessionHost host, IEnumerable <GeneratedObject> generatedObjects) { foreach (GeneratedObject generatedObject in generatedObjects) { ITextTemplatingSession session = host.CreateSession(); session["generatedObject"] = generatedObject; yield return(session); } }
public TemplateExecutor() { textTemplatingService = Package.GetGlobalService(typeof(STextTemplating)) as ITextTemplating; infoUtils = new InfoUtils(); klasaInfo = infoUtils.GetKlasaInfo(); TTUtils = new TTSettingsUtils(); host = textTemplatingService as ITextTemplatingSessionHost; host.Session = host.CreateSession(); }
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 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 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); } }
public CodeGenerator(ITextTemplatingEngineHost host, ITextTemplatingSessionHost textTemplatingSessionHost, ITextTemplating textTemplating, ISolutionManager solutionManager, string rosMessagesProjectName, string rosMessageTypeAttributeName, string rosMessageTypeAttributeNamespace) { if (null == host) { throw new ArgumentNullException(nameof(host)); } if (null == textTemplatingSessionHost) { throw new ArgumentNullException(nameof(textTemplatingSessionHost)); } if (null == textTemplating) { throw new ArgumentNullException(nameof(textTemplating)); } if (null == solutionManager) { throw new ArgumentNullException(nameof(solutionManager)); } if (string.IsNullOrWhiteSpace(rosMessagesProjectName)) { throw new ArgumentException("Parameter cannot be empty!", nameof(rosMessagesProjectName)); } if (string.IsNullOrWhiteSpace(rosMessageTypeAttributeName)) { throw new ArgumentException("Parameter cannot be empty!", nameof(rosMessageTypeAttributeName)); } if (string.IsNullOrWhiteSpace(rosMessageTypeAttributeNamespace)) { throw new ArgumentException("Parameter cannot be empty!", nameof(rosMessageTypeAttributeNamespace)); } _textTemplatingEngineHost = host; _textTemplating = textTemplating; _textTemplatingSessionHost = textTemplatingSessionHost; _solutionManager = solutionManager; _rosMessageTypeAttributeName = rosMessageTypeAttributeName; _rosMessageTypeAttributeNamespace = rosMessageTypeAttributeNamespace; _defaultNamespace = rosMessagesProjectName; _rosMessageCodeGenerationTemplatePath = _textTemplatingEngineHost.ResolvePath(ROS_MESSAGE_CODE_GENERATION_TEMPLATE_RELATIVE_PATH); _rosMessageCodeGenerationTemplateContent = ReadAllTextFromFile(_rosMessageCodeGenerationTemplatePath); _customTimeDataTemplatePath = _textTemplatingEngineHost.ResolvePath(CUSTOM_TIME_DATA_TEMPLATE_RELATIVE_PATH); _solutionManager.Initialize(); }
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 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 string ProcessTemplateToFile(TemplateInfoRecord template) { TTSettingsDictionary settingsDictionary = template.SettingsDictionary; string templateFilePath = template.Path; ITextTemplatingSessionHost host = textTemplatingService as ITextTemplatingSessionHost; host.Session["klasaInfo"] = klasaInfo; //host.Session["ustawienia"] = settingsDictionary; string templateContent = TTUtils.GetClearTemplate(templateFilePath); T4Callback cb = new T4Callback(); string result = textTemplatingService.ProcessTemplate(templateFilePath, templateContent, cb); result = ArrangeUsingRoslyn(result); //Format code string fileName = klasaInfo.Nazwa; ImmutableSetting fileNameSetting = template.ImmutableSettings.Find(x => x.Name.Contains("NazwaPliku")); if (fileNameSetting != null) { if (fileNameSetting.Value != null) { fileName = fileNameSetting.Value; } } string resultFileName = Path.Combine(Path.GetDirectoryName(templateFilePath), fileName + Path.GetFileNameWithoutExtension(templateFilePath)) + cb.fileExtension; // Writing the processed output to file: File.WriteAllText(resultFileName, result, cb.outputEncoding); // Append any error messages: if (cb.errorMessages.Count > 0) { File.AppendAllLines(resultFileName, cb.errorMessages); } return(resultFileName); }
/// <summary> /// Creates the MVC item and add it to the MVC project. /// </summary> /// <param name="vsProj">The Visual Studio project.</param> private void GenerateMVCItems(VSProject vsProj) { if (string.IsNullOrEmpty(_connectionString)) { return; } if (_selectedTables == null || _selectedTables.Count == 0) { return; } #if CLR4 || NET_40_OR_GREATER IServiceProvider serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte); Microsoft.VisualStudio.TextTemplating.VSHost.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.TryParse(ItemTemplateUtilities.GetVisualStudioVersion(dte), out visualStudioVersion); if (_language == LanguageGenerator.CSharp) { controllerClassPath = Path.GetFullPath(string.Format("{0}{1}{2}", T4Templates_Path, version, cSharpControllerClass_FileName)); IndexFilePath = Path.GetFullPath(string.Format("{0}{1}{2}", T4Templates_Path, version, cSharpIndexFile_FileName)); fileExtension = "cs"; } else { controllerClassPath = Path.GetFullPath(string.Format("{0}{1}{2}", T4Templates_Path, version, vbControllerClass_FileName)); IndexFilePath = Path.GetFullPath(string.Format("{0}{1}{2}", T4Templates_Path, version, vbIndexFile_FileName)); 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))); } 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 ((_dataAccessTechnology == DataAccessTechnology.EntityFramework6 && _language == LanguageGenerator.VBNET) || _language == LanguageGenerator.CSharp) { sessionHost.Session["modelNameParameter"] = _connectionName; } else if (_dataAccessTechnology == DataAccessTechnology.EntityFramework5 && _language == LanguageGenerator.VBNET) { sessionHost.Session["modelNameParameter"] = string.Format("{1}.{0}", _connectionName, _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 (_dataAccessTechnology == DataAccessTechnology.EntityFramework5) { sessionHost.Session["entityClassNameParameterWithNamespace"] = string.Format("{0}.{0}.{1}", _projectNamespace, table.Key); } else if (_dataAccessTechnology == DataAccessTechnology.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 = string.Format(@"{0}\Controllers\{1}Controller.{2}", _projectPath, 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 (Exception ex) { SendToGeneralOutputWindow(string.Format("An error occurred: {0}\n\n {1}", ex.Message, ex.StackTrace)); InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ErrorTitle, Resources.ItemTemplatesBaseWebWizard_GenerateMvcItemsError)); } #endif }
private static IEnumerable<ITextTemplatingSession> GetServiceT4Sessions(ITextTemplatingSessionHost host, GeneratedService generatedService) { ITextTemplatingSession session = host.CreateSession(); session["generatedService"] = generatedService; yield return session; }
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); }
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 }
private static IEnumerable<ITextTemplatingSession> GetObjectT4Sessions(ITextTemplatingSessionHost host, IEnumerable<GeneratedObject> generatedObjects) { foreach (GeneratedObject generatedObject in generatedObjects) { ITextTemplatingSession session = host.CreateSession(); session["generatedObject"] = generatedObject; yield return session; } }