Пример #1
0
 private void GenerateAccessoryFile(string fileName, string templateFile, CslaObjectInfo objInfo, bool activeObjects, CslaGeneratorUnit unit)
 {
     // Create Inheritance file if it does not exist
     if (!File.Exists(fileName)) //&& objInfo.ObjectType != CslaObjectType.NameValueList)
     {
         // string tPath = this._fullTemplatesPath + objInfo.OutputLanguage.ToString() + "\\InheritFromBase.cst";
         string       tPath    = _fullTemplatesPath + objInfo.OutputLanguage + templateFile;
         CodeTemplate template = GetTemplate(objInfo, tPath);
         if (template != null)
         {
             template.SetProperty("ActiveObjects", activeObjects);
             template.SetProperty("CurrentUnit", unit);
             FileStream fs = File.Open(fileName, FileMode.Create);
             OnGenerationFileName(fileName);
             StreamWriter sw = new StreamWriter(fs);
             try
             {
                 template.Render(sw);
             }
             catch (Exception e)
             {
                 ShowExceptionInformation(e);
             }
             finally
             {
                 sw.Close();
             }
         }
     }
 }
Пример #2
0
        public static void Main()
        {
            string path   = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\StoredProcedures.cst");
            var    engine = new TemplateEngine(new DefaultEngineHost(System.IO.Path.GetDirectoryName(path)));

            CompileTemplateResult result = engine.Compile(path);

            if (result.Errors.Count == 0)
            {
                var         database = new DatabaseSchema(new SqlSchemaProvider(), @"Server=.;Database=PetShop;Integrated Security=True;");
                TableSchema table    = database.Tables["Inventory"];

                CodeTemplate template = result.CreateTemplateInstance();
                template.SetProperty("SourceTable", table);
                template.SetProperty("IncludeDrop", false);
                template.SetProperty("InsertPrefix", "Insert");

                template.Render(Console.Out);
            }
            else
            {
                foreach (var error in result.Errors)
                {
                    Console.Error.WriteLine(error.ToString());
                }
            }

            Console.WriteLine("\r\nPress any key to continue.");
            Console.ReadKey();
        }
Пример #3
0
 private string GenerateProcedure(CslaObjectInfo objInfo, Criteria crit, string templateName, string sprocName)
 {
     if (objInfo != null)
     {
         try
         {
             if (templateName != String.Empty)
             {
                 string       path     = _templatesDirectory + @"sprocs\" + templateName;
                 CodeTemplate template = GetTemplate(objInfo, path);
                 if (crit != null)
                 {
                     template.SetProperty("Criteria", crit);
                 }
                 template.SetProperty("IncludeParentProperties", objInfo.DataSetLoadingScheme);
                 if (template != null)
                 {
                     using (StringWriter sw = new StringWriter())
                     {
                         template.Render(sw);
                         sprocSuccess++;
                         return(sw.ToString());
                     }
                 }
             }
         }
         catch (Exception e)
         {
             sprocFailed++;
             throw (new Exception("Error generating " + GetFileNameWithoutExtension(templateName) + ": " + sprocName, e));
         }
     }
     return(String.Empty);
 }
Пример #4
0
 void GenerateInheritanceFile(string fileName, CslaObjectInfo objInfo, bool activeObjects, CslaGeneratorUnit unit)
 {
     // Create Inheritance file if it does not exist
     if (!File.Exists(fileName)) //&& objInfo.ObjectType != CslaObjectType.NameValueList)
     {
         string       tPath    = this._fullTemplatesPath + unit.GenerationParams.OutputLanguage.ToString() + "\\InheritFromBase.cst";
         CodeTemplate template = GetTemplate(objInfo, tPath);
         if (template != null)
         {
             template.SetProperty("ActiveObjects", activeObjects);
             template.SetProperty("CurrentUnit", unit);
             FileInfo fi = new FileInfo(fileName);
             using (FileStream fs = fi.Open(FileMode.Create))
             {
                 OnGenerationFileName(fi.FullName);
                 using (StreamWriter sw = new StreamWriter(fs))
                 {
                     try
                     {
                         template.Render(sw);
                     }
                     catch (Exception e)
                     {
                         ShowExceptionInformation(e);
                     }
                 }
             }
         }
     }
 }
Пример #5
0
    /// <summary>
    /// 生成数据仓库代码
    /// </summary>
    /// <param name="tables"></param>
    /// <returns></returns>
    public int GenerateBusinessRepositoryClasses(ViewSchemaCollection views)
    {
        if (views == null || views.Count <= 0)
        {
            return(0);
        }
        int          tempIntTableNum            = 0;
        CodeTemplate BusinessRepositoryTemplate = GetCodeTemplate("ViewBusinessRepository.cst");

        foreach (ViewSchema view in views)
        {
            BusinessRepositoryTemplate.SetProperty("TargetView", view);
            BusinessRepositoryTemplate.SetProperty("CommonNamespace", CommonNamespace);
            BusinessRepositoryTemplate.SetProperty("BusinessRepositoryNamespace", BusinessRepositoryNamespace);
            BusinessRepositoryTemplate.SetProperty("EntityNamespace", EntityNamespace);
            BusinessRepositoryTemplate.SetProperty("DBUtilityNamespace", DBUtilityNamespace);
            BusinessRepositoryTemplate.SetProperty("CreatePerson", CreatePerson);
            BusinessRepositoryTemplate.SetProperty("CompanyName", CompanyName);
            BusinessRepositoryTemplate.SetProperty("BusinessRepositorySuffix", BusinessRepositorySuffix);
            BusinessRepositoryTemplate.SetProperty("FileDesc", "表[" + view.Name + "]的 数据仓库代码");
            string tempFilePath = string.Format(@"{0}{1}\{2}", this.OutputDirectory, BusinessRepositoryNamespace, BusinessRepositoryTemplate.GetFileName());
            BusinessRepositoryTemplate.RenderToFile(tempFilePath, true);
            WriteInfo("成功在路径[" + this.OutputDirectory + BusinessRepositoryNamespace + "] 生成 BusinessReposity 层代码文件:" + BusinessRepositoryTemplate.GetFileName() + "");
            tempIntTableNum++;
        }
        WriteInfo("-----成功在路径[" + this.OutputDirectory + BusinessRepositoryNamespace + "] 生成:" + tempIntTableNum + " 个 BusinessReposity 层代码文件-----");
        return(tempIntTableNum);
    }
Пример #6
0
        /// <summary>
        /// 通用根据模板生成文件方法
        /// </summary>
        /// <param name="isRender"></param>
        /// <param name="templatePath"></param>
        /// <param name="directory"></param>
        /// <param name="Tables"></param>
        /// <param name="fileName"></param>
        public void RenderToFileByTablesFixFileName(bool isRender, string templatePath, string directory, TableSchemaCollection Tables, string fileName = null)
        {
            if (isRender)
            {
                if (directory.IndexOf("{dbname}") >= 0)
                {
                    directory = directory.Replace("{dbname}", Tables[0].Database.Name);
                }
                if (string.IsNullOrWhiteSpace(fileName))
                {
                    fileName = Tables[0].Database.Name;
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(fileName) && fileName.IndexOf("{dbname}") >= 0)
                    {
                        fileName = fileName.Replace("{dbname}", Tables[0].Database.Name);
                    }
                }
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                //载入子模板
                CodeTemplate template = GetCodeTemplate(templatePath);

                //CopyPropertiesTo(template);

                template.SetProperty("Tables", Tables);

                template.RenderToFile(directory + fileName, true);

                Response.WriteLine(templatePath + "代码生成完毕!");
            }
        }
Пример #7
0
        public static void RunTableTemplate(CodeTemplate Parent, TableSchema SourceTable, string Path, string Template, string Output, bool debug)
        {
            // admin datamodel
            try
            {
                PreserveRegionsMergeStrategy strategy = new PreserveRegionsMergeStrategy("^[ \t]*(?i:Custom)", "C#");
                CodeTemplate template = null;
                if (!debug)
                {
                    template = Parent.GetCodeTemplateInstance(Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Template);
                }
                else
                {
                    template = CompileTemplate(Parent, Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Template);
                }

                if (template != null)
                {
                    template.SetProperty("SourceTable", SourceTable);
                    template.RenderToFile(Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Output, strategy);
                    Parent.Response.WriteLine("File: " + Output + " Created Successfully");
                }
                else
                {
                    Parent.Response.WriteLine("Template is null: " + Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Template);
                }
            }
            catch (Exception ex)
            {
                Parent.Response.WriteLine("Template: " + Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Template);
                Parent.Response.WriteLine("Error: " + ex.Message);
                Parent.Response.WriteLine("StackTrace: " + ex.StackTrace);
            }
        }
Пример #8
0
        public void RenderTesting()
        {
            TemplateEngine        engine = new TemplateEngine(System.IO.Path.GetDirectoryName(path));
            CompileTemplateResult result = engine.Compile(path);

            if (!result.Errors.HasErrors)
            {
                CodeTemplate template = result.CreateTemplateInstance();
                template.SetProperty("SampleStringProperty", "frank");
                string render = template.RenderToString();
                Assert.AreEqual("hello world frank", render);
            }
        }
Пример #9
0
    /// <summary>
    /// 生成数据实体代码
    /// </summary>
    /// <param name="tables"></param>
    /// <returns></returns>
    public int GenerateEntityClasses(ViewSchemaCollection views)
    {
        if (views == null || views.Count <= 0)
        {
            return(0);
        }
        int          tempIntTableNum = 0;
        CodeTemplate EntityTemplate  = GetCodeTemplate("ViewEntity.cst");

        foreach (ViewSchema view in views)
        {
            EntityTemplate.SetProperty("TargetView", view);
            EntityTemplate.SetProperty("EntityNamespace", EntityNamespace);
            EntityTemplate.SetProperty("CreatePerson", CreatePerson);
            EntityTemplate.SetProperty("CompanyName", CompanyName);
            EntityTemplate.SetProperty("FileDesc", "表[" + view.Name + "] 数据库实体代码");
            string tempFilePath = string.Format(@"{0}{1}\{2}", this.OutputDirectory, EntityNamespace, EntityTemplate.GetFileName());
            EntityTemplate.RenderToFile(tempFilePath, true);
            WriteInfo("成功在路径[" + this.OutputDirectory + EntityNamespace + "] 生成 Entity 层代码文件:" + EntityTemplate.GetFileName() + "");
            tempIntTableNum++;
        }
        WriteInfo("-----成功在路径[" + this.OutputDirectory + EntityNamespace + "] 生成 " + tempIntTableNum + " 个 Entity 层代码文件-----");
        return(tempIntTableNum);
    }
Пример #10
0
        private CodeTemplate GetTemplate(CslaObjectInfo objInfo, string templatePath)
        {
            CodeTemplateCompiler compiler;

            if (!templates.ContainsKey(templatePath))
            {
                if (!File.Exists(templatePath))
                {
                    throw new ApplicationException("The specified template could not be found: " + templatePath);
                }

                compiler = new CodeTemplateCompiler(templatePath);
                compiler.Compile();
                templates.Add(templatePath, compiler);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < compiler.Errors.Count; i++)
                {
                    sb.Append(compiler.Errors[i].ToString());
                    sb.Append(Environment.NewLine);
                }
                if (compiler.Errors.Count > 0)
                {
                    throw new Exception(String.Format(
                                            "Template {0} failed to compile. Objects of the same type will be ignored.",
                                            templatePath) + Environment.NewLine + sb.ToString());
                }
            }
            else
            {
                compiler = (CodeTemplateCompiler)templates[templatePath];
            }
            if (compiler.Errors.Count > 0)
            {
                return(null);
            }

            CodeTemplate template = compiler.CreateInstance();

            template.SetProperty("Info", objInfo);
            return(template);
        }
Пример #11
0
        /// <summary>
        /// 通用根据模板生成文件方法
        /// </summary>
        public void RenderToFileByTables(bool isRender, string templatePath, string directory, TableSchemaCollection tables, Func <TableSchema, string> className = null)
        {
            if (isRender)
            {
                if (directory.IndexOf("{dbname}") >= 0)
                {
                    directory = directory.Replace("{dbname}", tables[0].Database.Name);
                }
                //载入子模板
                CodeTemplate template = GetCodeTemplate(templatePath);
                foreach (var tab in tables)
                {
                    //CopyPropertiesTo(template);
                    template.SetProperty("SourceTable", tab);

                    RenderToFile(directory, className, template, tab);
                }
                Response.WriteLine(templatePath + "代码生成完毕!");
            }
        }
Пример #12
0
        public static string GenerateString(string fullTemplateFileName, Dictionary <string, object> args)
        {
            string                code   = "";
            DefaultEngineHost     host   = new DefaultEngineHost(Path.GetDirectoryName(fullTemplateFileName));
            TemplateEngine        engine = new TemplateEngine(System.IO.Path.GetDirectoryName(fullTemplateFileName));
            CompileTemplateResult result = engine.Compile(fullTemplateFileName);

            if (!result.Errors.HasErrors)
            {
                CodeTemplate template = result.CreateTemplateInstance();
                foreach (var key in args.Keys)
                {
                    PropertyInfo info  = template.GetPropertyInfo(key, false);
                    object       value = args[key];
                    if (info.PropertyType != value.GetType())
                    {
                        string json = JsonHelper.Serialize(value);
                        value = JsonHelper.Deserialize(json, info.PropertyType);
                    }
                    template.SetProperty(key, value);
                }
                code = template.RenderToString();
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                foreach (var e in result.Errors)
                {
                    if (e.IsError)
                    {
                        sb.AppendFormat("{0}\r\n", e.Description);
                    }
                }
                if (sb.Length > 0)
                {
                    throw new Exception(string.Format("编译模板时发生错误。\r\n{0}", sb.ToString()));
                }
            }
            return(code);
        }
Пример #13
0
        private void GenerateUtilityFile(string utilityFilename, CslaObjectInfo objInfo, TargetFramework framework, CslaGeneratorUnit unit)
        {
            _fileSuccess.Add(utilityFilename, null);

            // only implement this for more recent frameworks);
            if (framework != TargetFramework.CSLA40)
            {
                return;
            }

            // base directory of project
            string fullFilename = _targetDirectory + @"\";

            if (unit.GenerationParams.SeparateNamespaces)
            {
                // check whether to use namespace as folder
                fullFilename += unit.GenerationParams.UtilitiesNamespace.Replace(".", @"\") + @"\";
            }
            else if (!unit.GenerationParams.UtilitiesFolder.Equals(String.Empty))
            {
                // output folder inside directory
                fullFilename += unit.GenerationParams.UtilitiesFolder + @"\";
            }

            CheckDirectory(fullFilename);

            // filename w/o extension
            fullFilename += utilityFilename;

            // extension
            if (objInfo.OutputLanguage == CodeLanguage.CSharp)
            {
                fullFilename += ".cs";
            }
            else if (objInfo.OutputLanguage == CodeLanguage.VB)
            {
                fullFilename += ".vb";
            }

            // Create utility class file if it does not exist
            if (!File.Exists(fullFilename))
            {
                string       tPath    = _fullTemplatesPath + objInfo.OutputLanguage + "\\" + utilityFilename + ".cst";
                CodeTemplate template = GetTemplate(objInfo, tPath);
                if (template != null)
                {
                    template.SetProperty("FileName", utilityFilename);
                    template.SetProperty("CurrentUnit", unit);
                    FileStream fs = File.Open(fullFilename, FileMode.Create);
                    OnGenerationInformation(utilityFilename + " file:");
                    OnGenerationFileName(fullFilename);
                    StreamWriter sw = new StreamWriter(fs);
                    try
                    {
                        template.Render(sw);
                        _fileSuccess[utilityFilename] = true;
                    }
                    catch (Exception e)
                    {
                        ShowExceptionInformation(e);
                        _fileSuccess[utilityFilename] = false;
                    }
                    finally
                    {
                        sw.Close();
                    }
                }
            }
        }
Пример #14
0
        private void GenerateObject(CslaObjectInfo objInfo, CslaGeneratorUnit unit)
        {
            Metadata.GenerationParameters generationParams = unit.GenerationParams;
            string fileName             = GetBaseFileName(objInfo, false, generationParams.SeparateBaseClasses, generationParams.SeparateNamespaces, generationParams.BaseFilenameSuffix, generationParams.ExtendedFilenameSuffix, generationParams.ClassCommentFilenameSuffix, false, false);
            string baseFileName         = GetBaseFileName(objInfo, true, generationParams.SeparateBaseClasses, generationParams.SeparateNamespaces, generationParams.BaseFilenameSuffix, generationParams.ExtendedFilenameSuffix, generationParams.ClassCommentFilenameSuffix, false, false);
            string classCommentFileName = string.Empty;

            if (!string.IsNullOrEmpty(generationParams.ClassCommentFilenameSuffix))
            {
                classCommentFileName = GetBaseFileName(objInfo, false, generationParams.SeparateBaseClasses, generationParams.SeparateNamespaces, generationParams.BaseFilenameSuffix, generationParams.ExtendedFilenameSuffix, generationParams.ClassCommentFilenameSuffix, true, generationParams.SeparateClassComment);
            }
            FileStream   fsBase = null;
            StreamWriter swBase = null;
            StreamWriter sw     = null;

            try
            {
                string       tPath    = this._fullTemplatesPath + objInfo.OutputLanguage.ToString() + @"\" + GetTemplateName(objInfo);
                CodeTemplate template = GetTemplate(objInfo, tPath);
                if (template != null)
                {
                    StringBuilder errorsOutput   = new StringBuilder();
                    StringBuilder warningsOutput = new StringBuilder();
                    template.SetProperty("ActiveObjects", generationParams.ActiveObjects);
                    template.SetProperty("Errors", errorsOutput);
                    template.SetProperty("Warnings", warningsOutput);
                    template.SetProperty("CurrentUnit", unit);
                    template.SetProperty("DataSetLoadingScheme", objInfo.DataSetLoadingScheme);
                    if (generationParams.BackupOldSource && File.Exists(baseFileName))
                    {
                        FileInfo oldFile = new FileInfo(baseFileName);
                        if (File.Exists(baseFileName + ".old"))
                        {
                            File.Delete(baseFileName + ".old");
                        }
                        oldFile.MoveTo(baseFileName + ".old");
                    }
                    fsBase = File.Open(baseFileName, FileMode.Create);
                    OnGenerationFileName(baseFileName);
                    swBase = new StreamWriter(fsBase);
                    template.Render(swBase);
                    errorsOutput   = (StringBuilder)template.GetProperty("Errors");
                    warningsOutput = (StringBuilder)template.GetProperty("Warnings");
                    if (errorsOutput.Length > 0)
                    {
                        objFailed++;
                        OnGenerationInformation("Failed:" + Environment.NewLine + errorsOutput);
                    }
                    else
                    {
                        if (warningsOutput != null)
                        {
                            if (warningsOutput.Length > 0)
                            {
                                objectWarnings++;
                                OnGenerationInformation("Warning:" + Environment.NewLine + warningsOutput);
                            }
                        }
                        objSuccess++;
                        //OnGenerationInformation("Success");
                    }
                }
                GenerateInheritanceFile(fileName, objInfo, generationParams.ActiveObjects, unit);
                if (!string.IsNullOrEmpty(generationParams.ClassCommentFilenameSuffix))
                {
                    GenerateClassCommentFile(classCommentFileName, objInfo, generationParams.ActiveObjects, unit);
                }
            }
            catch (Exception e)
            {
                objFailed++;
                ShowExceptionInformation(e);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
                if (swBase != null)
                {
                    swBase.Close();
                }
            }
        }
Пример #15
0
        private void GenerateObject(CslaObjectInfo objInfo, CslaGeneratorUnit unit)
        {
            Metadata.GenerationParameters generationParams = unit.GenerationParams;
            string fileName     = GetFileName(objInfo, generationParams.SeparateNamespaces, generationParams.OutputLanguage);
            string baseFileName = GetBaseFileName(objInfo, generationParams.SeparateBaseClasses, generationParams.SeparateNamespaces, generationParams.UseDotDesignerFileNameConvention, generationParams.OutputLanguage);

            try
            {
                GenerateInheritanceFile(fileName, objInfo, generationParams.ActiveObjects, unit);
                string       tPath    = this._fullTemplatesPath + generationParams.OutputLanguage.ToString() + @"\" + GetTemplateName(objInfo);
                CodeTemplate template = GetTemplate(objInfo, tPath);
                if (template != null)
                {
                    StringBuilder errorsOutput   = new StringBuilder();
                    StringBuilder warningsOutput = new StringBuilder();
                    template.SetProperty("ActiveObjects", generationParams.ActiveObjects);
                    template.SetProperty("Errors", errorsOutput);
                    template.SetProperty("Warnings", warningsOutput);
                    template.SetProperty("CurrentUnit", unit);
                    template.SetProperty("DataSetLoadingScheme", objInfo.DataSetLoadingScheme);
                    if (generationParams.BackupOldSource && File.Exists(baseFileName))
                    {
                        FileInfo oldFile = new FileInfo(baseFileName);
                        if (File.Exists(baseFileName + ".old"))
                        {
                            File.Delete(baseFileName + ".old");
                        }
                        oldFile.MoveTo(baseFileName + ".old");
                    }
                    FileInfo fi = new FileInfo(baseFileName);
                    using (FileStream fs = fi.Open(FileMode.Create))
                    {
                        OnGenerationFileName(fi.FullName);
                        using (StreamWriter swBase = new StreamWriter(fs))
                        {
                            template.Render(swBase);
                            errorsOutput   = (StringBuilder)template.GetProperty("Errors");
                            warningsOutput = (StringBuilder)template.GetProperty("Warnings");
                            if (errorsOutput.Length > 0)
                            {
                                objFailed++;
                                OnGenerationInformation("Failed:" + Environment.NewLine +
                                                        errorsOutput.ToString(), 2);
                            }
                            else
                            {
                                if (warningsOutput != null)
                                {
                                    if (warningsOutput.Length > 0)
                                    {
                                        objectWarnings++;
                                        OnGenerationInformation("Warning:" + Environment.NewLine + warningsOutput, 2);
                                    }
                                }
                                objSuccess++;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                objFailed++;
                ShowExceptionInformation(e);
            }
        }