示例#1
0
        // Generates file from template
        // Returns generated file path
        public string ProcessTemplateToString(TemplateInfoRecord template)
        {
            TTSettingsDictionary settingsDictionary = template.SettingsDictionary;
            string templateFilePath = template.Path;

            host.Session["klasaInfo"] = klasaInfo;
            //host.Session["ustawienia"] = settingsDictionary;

            string templateContent = File.ReadAllText(templateFilePath);

            T4Callback cb     = new T4Callback();
            string     result = textTemplatingService.ProcessTemplate(templateFilePath, templateContent, cb);

            return(result);
        }
示例#2
0
        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);
        }
        // Engine to generate the T4 item
        protected void GenerateT4Item(ProjectItem projectItem, object viewData, Type ParamType)
        {
            // csitem = projectItem.ContainingProject.
            IServiceProvider serviceProvider = new ServiceProvider(projectItem.DTE as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);

            ITextTemplating t4 = serviceProvider.GetService(typeof(STextTemplating)) as ITextTemplating;
            ITextTemplatingSessionHost sessionHost = t4 as ITextTemplatingSessionHost;
            T4Callback cb = new T4Callback();
            // Create a Session in which to pass parameters:
            sessionHost.Session = sessionHost.CreateSession();
            sessionHost.Session["templateData"] = viewData;

            string fileName = projectItem.Properties.Item("FullPath").Value;
            string fileContent = string.Format("<#@parameter type=\"{0}\" name=\"templateData\"#>", ParamType.ToString()) + File.ReadAllText(fileName);
          
            string result = t4.ProcessTemplate("", fileContent, cb);
            File.WriteAllText(fileName, result, cb.outputEncoding);

            if (cb.errorMessages.Count > 0)
            {
                File.AppendAllLines(fileName, cb.errorMessages);
            }
        }
        /// <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
        }