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)); }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> /// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param> /// <param name="progress">A provider for progress updates.</param> /// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns> protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { // When initialized asynchronously, the current thread may be a background thread at this point. // Do any initialization that requires the UI thread after switching to the UI thread. await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); // Query service asynchronously from the UI thread //var dte = await GetServiceAsync(typeof(EnvDTE.DTE)) as EnvDTE.DTE; ITextTemplating textTemplating = null; EnvDTE80.DTE2 dte2 = null; IVsThreadedWaitDialogFactory dialogFactory = null; dte2 = await GetServiceAsync(typeof(SDTE)) as EnvDTE80.DTE2; textTemplating = await GetServiceAsync(typeof(STextTemplating)) as ITextTemplating; dialogFactory = await GetServiceAsync(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory; await CS2REACTJS.Commands.CrtDbContextCommand.InitializeAsync(this, dte2, textTemplating, dialogFactory); await CS2REACTJS.Commands.CrtViewModelCommand.InitializeAsync(this, dte2, textTemplating, dialogFactory); await CS2REACTJS.Commands.CrtWebApiServiceCommand.InitializeAsync(this, dte2, textTemplating, dialogFactory); await CS2REACTJS.Commands.CrtJavaScriptsCommand.InitializeAsync(this, dte2, textTemplating, dialogFactory); await CS2REACTJS.Commands.CrtFeatureScriptsCommand.InitializeAsync(this, dte2, textTemplating, dialogFactory); }
public async System.Threading.Tasks.Task InitializeAsync(Microsoft.VisualStudio.Shell.IAsyncServiceProvider serviceProvider) { ServiceProvider = serviceProvider; Host = await serviceProvider.GetServiceAsync(typeof(SDTE)) as DTE; TextTemplating = await Dte.Instance.ServiceProvider.GetServiceAsync(typeof(STextTemplating)) as ITextTemplating; }
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 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 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 BatchProcessingViewModel(DTE2 dte, ITextTemplating textTemplating, IVsThreadedWaitDialogFactory dialogFactory, string t4RootFolder, string batchRootFolder) { this.Dte = dte; this.TextTemplating = textTemplating; this.T4RootFolder = t4RootFolder; this.BatchRootFolder = batchRootFolder; this.DialogFactory = dialogFactory; }
public TemplateService(ITextTemplatingSessionHost textTemplatingSessionHost, ITextTemplatingEngineHost textTemplatingEngineHost, ITextTemplating textTemplating) { TextTemplatingSessionHost = textTemplatingSessionHost; TextTemplatingEngineHost = textTemplatingEngineHost; TextTemplating = textTemplating; }
public TextTemplatingModelGenerator( ModelCodeGeneratorDependencies dependencies, ITextTemplating textTemplatingService, IOperationReporter reporter) : base(dependencies) { _host = textTemplatingService; _reporter = reporter; }
protected virtual ITextTemplating GetTextTemplating() { ITextTemplating processor = ThreadHelper.JoinableTaskFactory.Run <ITextTemplating>(async() => { return(await GetServiceAsync <SSubSonicTemplatingService, ITextTemplating>()); }); return(processor); }
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(); }
/// <summary> /// Initializes a new instance of the <see cref="TextTemplateUriProvider"/> class. /// </summary> public TextTemplateUriProvider(ITextTemplating templating, IModelBus modelBus, Lazy <IUriReferenceService> uriService) { Guard.NotNull(() => templating, templating); Guard.NotNull(() => modelBus, modelBus); Guard.NotNull(() => uriService, uriService); this.templating = templating; this.modelBus = modelBus; this.uriService = uriService; }
public MainWindowVm2WebApi(DTE2 dte, ITextTemplating textTemplating, IVsThreadedWaitDialogFactory dialogFactory) : base(dte, textTemplating, dialogFactory) { InvitationViewModel InvitationVM = new InvitationViewModel(); InvitationVM.WizardName = "#3 WebApi Wizard"; InvitationVM.IsReady.IsReadyEvent += InvitationViewModel_IsReady; this.InvitationUC = new UserControlInvitation(InvitationVM); this.CurrentUserControl = this.InvitationUC; InvitationVM.DoAnalise(dte); }
public CreatePrimaryKeyViewModel(DTE2 dte, ITextTemplating textTemplating) : base() { this.Dte = dte; this.textTemplating = textTemplating; EntityProperties = new ObservableCollection <FluentAPIExtendedProperty>(); PrimaryKeyProperties = new ObservableCollection <FluentAPIExtendedProperty>(); Templates = new ObservableCollection <string>(); TemplateExtention = "*.t4"; InvitationCaption = "Create(Modify) primary key settings"; }
public SelectFolderViewModel(DTE2 dte, ITextTemplating textTemplating, IVsThreadedWaitDialogFactory dialogFactory, SolutionCodeElement selectedDbContext, string rootFolder, string JavaScriptsTmplst, string BatchJavaScriptsTmplst) : base() { this.T4Folders = new ObservableCollection <string>(); this.Dte = dte; this.SelectedDbContext = selectedDbContext; this.DialogFactory = dialogFactory; this.TextTemplating = textTemplating; this.T4RootFolder = Path.Combine(rootFolder, JavaScriptsTmplst); this.BatchRootFolder = Path.Combine(rootFolder, BatchJavaScriptsTmplst); this.OnContextChanged = new ContextChangedService(); }
public MainWindowEf2Vm(DTE2 dte, ITextTemplating textTemplating, IVsThreadedWaitDialogFactory dialogFactory) : base(dte, textTemplating, dialogFactory) { Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); InvitationViewModel InvitationVM = new InvitationViewModel(); InvitationVM.WizardName = "#2 View Wizard"; InvitationVM.IsReady.IsReadyEvent += InvitationViewModel_IsReady; this.InvitationUC = new UserControlInvitation(InvitationVM); this.CurrentUserControl = this.InvitationUC; InvitationVM.DoAnalise(dte); }
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 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 CreateForeignKeyViewModel(DTE2 dte, ITextTemplating textTemplating) : base() { this.Dte = dte; this.textTemplating = textTemplating; EntityProperties = new ObservableCollection <FluentAPIExtendedProperty>(); ForeignKeyProperties = new ObservableCollection <FluentAPIExtendedProperty>(); EntityNonScalarProperties = new ObservableCollection <string>(); Templates = new ObservableCollection <string>(); PrimaryKeyProperties = new ObservableCollection <FluentAPIExtendedProperty>(); PrincipalNonScalarProperties = new ObservableCollection <FluentAPINavigationProperty>(); ForeignKeyTypes = new ObservableCollection <NavigationTypeEnum>(); TemplateExtention = "*.t4"; InvitationCaption = "Create(Modify) Foreign key settings for:"; }
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(); }
/// <summary> /// Initializes the singleton instance of the command. /// </summary> /// <param name="package">Owner package, not null.</param> public static async Task InitializeAsync(AsyncPackage package, DTE2 dTE2, ITextTemplating textTemplating, IVsThreadedWaitDialogFactory dialogFactory) { // Switch to the main thread - the call to AddCommand in CrtDbContextCommand's constructor requires // the UI thread. await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken); OleMenuCommandService commandService = await package.GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService; Instance = new CrtDbContextCommand(package, commandService); Instance.uiShell = (IVsUIShell)(await package.GetServiceAsync(typeof(SVsUIShell))); Instance.dTE2 = dTE2; Instance.TextTemplating = textTemplating; Instance.DialogFactory = dialogFactory; }
public MainWindowBase(DTE2 dte, ITextTemplating textTemplating, IVsThreadedWaitDialogFactory dialogFactory) { CancelClicked = new ButtonClickedNotificationService(); this.Dte = dte; this.TextTemplating = textTemplating; this.DialogFactory = dialogFactory; try { DefineDestinationProject(); } catch { ; } }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> /// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param> /// <param name="progress">A provider for progress updates.</param> /// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns> protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { // When initialized asynchronously, the current thread may be a background thread at this point. // Do any initialization that requires the UI thread after switching to the UI thread. await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); // Query service asynchronously from the UI thread //var dte = await GetServiceAsync(typeof(EnvDTE.DTE)) as EnvDTE.DTE; ITextTemplating textTemplating = null; EnvDTE80.DTE2 dte2 = null; IVsThreadedWaitDialogFactory dialogFactory = null; dte2 = await GetServiceAsync(typeof(SDTE)) as EnvDTE80.DTE2; textTemplating = await GetServiceAsync(typeof(STextTemplating)) as ITextTemplating; dialogFactory = await GetServiceAsync(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory; // ITextTemplatingSessionHost textTemplatingSessionHost = (ITextTemplatingSessionHost)textTemplating; // textTemplatingSessionHost.Session = textTemplatingSessionHost.CreateSession(); //foreach (KeyValuePair<string, object> templateParameter in templateParameters) //{ // if (templateParameter.Value == null) // { // throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.NullValueNotAllowedAsTemplateParameter, templateParameter.Key, templatePath)); // } // textTemplatingSessionHost.Session[templateParameter.Key] = templateParameter.Value; //} //TPCallback textTemplatingCallback = new TPCallback(); //templateProcessingResult.GeneratedText = textTemplating.ProcessTemplate(templatePath, File.ReadAllText(templatePath), textTemplatingCallback); //templateProcessingResult.ProcessingErrors = textTemplatingCallback.ProcessingErrors; //templateProcessingResult.TemplateFileExtension = textTemplatingCallback.FileExtension; //return templateProcessingResult; await CS2ANGULAR.Commands.CrtDbContextCommand.InitializeAsync(this, dte2, textTemplating, dialogFactory); await CS2ANGULAR.Commands.CrtViewModelCommand.InitializeAsync(this, dte2, textTemplating, dialogFactory); await CS2ANGULAR.Commands.CrtWebApiServiceCommand.InitializeAsync(this, dte2, textTemplating, dialogFactory); await CS2ANGULAR.Commands.CrtJavaScriptsCommand.InitializeAsync(this, dte2, textTemplating, dialogFactory); await CS2ANGULAR.Commands.CrtFeatureScriptsCommand.InitializeAsync(this, dte2, textTemplating, dialogFactory); }
/// <summary> /// Initializes a new instance of the <see cref="TextTemplate"/> class. /// </summary> public TextTemplate(ITextTemplating templating, IModelBus modelBus, string templateFile) { Guard.NotNull(() => templating, templating); Guard.NotNull(() => modelBus, modelBus); Guard.NotNullOrEmpty(() => templateFile, templateFile); if (!File.Exists(templateFile)) { throw new FileNotFoundException(Resources.TextTemplate_FileNotFound, templateFile); } this.templating = templating; this.modelBus = modelBus; this.templateFile = templateFile; this.templateContent = ReplaceTemplatePathVariable(File.ReadAllText(templateFile)); }
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 TestInitialize() { UIThreadDispatcher.Invoke(delegate { this.templatingService = (ITextTemplating)ServiceProvider.GetService(typeof(STextTemplating)); this.templatingHost = (ITextTemplatingEngineHost)this.templatingService; this.provider = (ITransformationContextProvider)ServiceProvider.GetService(typeof(ITransformationContextProvider)); this.project = this.CreateTestProject(); this.folder = this.project.ProjectItems.AddFolder(Path.GetRandomFileName()); this.input = this.CreateTestProjectItem(this.folder.ProjectItems, TextFileItemTemplate); this.output = new OutputFile { File = Path.GetRandomFileName() + ".txt" }; this.output.Content.Append(TestText); this.SimulateTransformation(); }); }
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)); }
private static void DefineSessionParametrs(string name, ITextTemplating textTemplatingService) { var fileParser = new ProcessFileToElements(name); var host = textTemplatingService as ITextTemplatingSessionHost; if (host != null) { host.Session = host.CreateSession(); if (fileParser.Classes.Any()) { host.Session["codeClass"] = fileParser.Classes.First(); host.Session["codeClasses"] = fileParser.Classes; } if (fileParser.Interfaces.Any()) { host.Session["codeInterface"] = fileParser.Interfaces.First(); host.Session["codeInterfaces"] = fileParser.Interfaces; } if (fileParser.Structs.Any()) { host.Session["codeStruct"] = fileParser.Structs.First(); host.Session["codeStructs"] = fileParser.Structs; } if (fileParser.Enums.Any()) { host.Session["codeEnum"] = fileParser.Enums.First(); host.Session["codeEnums"] = fileParser.Enums; } } else { Debug.WriteLine("Can't get ITextTemplatingSessionHost"); } }
public void Initialize() { this.templating = VsIdeTestHostContext.ServiceProvider.GetService<STextTemplating, ITextTemplating>(); this.modelBus = VsIdeTestHostContext.ServiceProvider.GetService<SModelBus, IModelBus>(); this.solution = VsIdeTestHostContext.ServiceProvider.GetService<ISolution>(); }
/// <summary> /// Returns a collection of <see cref="CustomToolParameter"/> objects representing parameters defined in a text template. /// </summary> public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { this.templatingService = (ITextTemplating)this.serviceProvider.GetService(typeof(STextTemplating)); this.templatingHost = (ITextTemplatingEngineHost)this.templatingService; string templateFileName; if (this.ResolveTemplate(out templateFileName)) { string templateContent = File.ReadAllText(templateFileName, EncodingHelper.GetEncoding(templateFileName)); this.templatingService.PreprocessTemplate(templateFileName, templateContent, null, "TemporaryClass", "T4Toolbox", out this.assemblyReferences); for (int i = 0; i < this.assemblyReferences.Length; i++) { this.assemblyReferences[i] = this.templatingHost.ResolveAssemblyReference(this.assemblyReferences[i]); } var parameters = new List<CustomToolParameter>(); this.ParseParameters(templateContent, parameters); return new PropertyDescriptorCollection(parameters.Cast<PropertyDescriptor>().ToArray()); } return PropertyDescriptorCollection.Empty; }