/// <summary>
 ///
 /// </summary>
 /// <param name="codeGenParameters"></param>
 /// <remarks>The client data types should better be generated through SvcUtil.exe with the DC option. The client namespace will then be the original namespace plus suffix ".client". </remarks>
 public ControllersClientApiGen(CodeGenSettings codeGenParameters)
 {
     this.CodeGenParameters = codeGenParameters ?? throw new System.ArgumentNullException(nameof(codeGenParameters));
     TargetUnit             = new CodeCompileUnit();
     //SharedContext = new SharedContext();
     poco2CsGen = new Poco2CsGen(TargetUnit);
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Renders templates based on the database schema
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="tables">A collection of tables and columns used to generate code</param>
        /// <param name="projects">A collection of projects, the Dynamic Classes will be added to this collection</param>
        /// <returns>A collection of projects with rendered content added</returns>
        public static List <IVisualStudioProject> GenerateDynamicClasses(CodeGenSettings settings, List <DatabaseTable> tables, List <IVisualStudioProject> projects)
        {
            IProjectFileRender fileRender = new DynamicProjectFiles();

            projects = Generate <ICompiledTemplate, DatabaseTable>("ICompiledTemplate", settings, projects, fileRender, tables);
            return(projects);
        }
Ejemplo n.º 3
0
        public override GenerationArtifact RenderTemplate(DatabaseTable table, CodeGenSettings settings)
        {
            //retrieve the embedded template
            string contents = Core.ResourceFileHelper.ConvertStreamResourceToUTF8String(typeof(Model), "Chucksoft.Templates.Templates.StoredProcedure.template");

            _content = contents.Trim();

            //Check for expected content, if not found, badness has happen.
            if (string.IsNullOrEmpty(contents))
            {
                throw new ContentNotFound("Can't find embeddedResource \"Chucksoft.Templates.Templates.Enity.template\"");
            }

            List <string> prodecures     = GetProcedures(table, settings);
            StringBuilder contentBuilder = new StringBuilder();

            //append the procedures together and seperate them with a seperator
            foreach (string prodecure in prodecures)
            {
                contentBuilder.AppendLine(prodecure);
                contentBuilder.AppendLine(Environment.NewLine + "-----------------------------------------------------------" + Environment.NewLine);
            }

            //set the Generator object and return to calling method.
            GenerationArtifact artifact = new GenerationArtifact {
                FileName = string.Format("{0}.sql", table.Name), Content = contentBuilder.ToString()
            };

            return(artifact);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Renders static content ie. base classes, CSS Files. These files don't require the database schemea.
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="projects">A collection of projects, the Dynamic Classes will be added to this collection</param>
        /// <returns>A collection of projects with rendered content added</returns>
        public static List <IVisualStudioProject> GenerateStaticClasses(CodeGenSettings settings, List <IVisualStudioProject> projects)
        {
            IProjectFileRender fileRender = new StaticProjectFiles();

            projects = Generate <IStaticAsset, string>("IStaticAsset", settings, projects, fileRender, null);
            return(projects);
        }
        private void GenerateInsertMethods(DatabaseTable table, CodeGenSettings settings)
        {
            //<%[InsertMethod]%> -- Token
            string        makePararmeterList = GetMakeParameters(table, false);
            StringBuilder builder            = new StringBuilder();

            builder.AppendLine("\t\t\tList<DbParameter> parameters = new List<DbParameter> ");
            builder.AppendLine("\t\t\t{");
            builder.AppendLine(makePararmeterList);
            builder.AppendLine("\t\t\t};");

            if (settings.ReturnIdentityFromInserts)
            {
                builder.AppendLine("\r\n \t\t\tparameters.SelectIdentity();");
            }

            if (!settings.ReturnIdentityFromInserts)
            {
                builder.AppendLine(string.Format("\r\n \t\t\treturn _database.NonQuery(\"{0}_Insert\", parameters);", table.Name));
            }
            else
            {
                builder.AppendLine(string.Format("\r\n \t\t\t_database.NonQuery(\"{0}_Insert\", parameters); \r\n \t\t\t return parameters.Identity<int>(); ", table.Name));
            }

            _content = _content.Replace("<%[InsertMethod]%>", builder.ToString());
        }
Ejemplo n.º 6
0
 public JSOutput(CodeGenSettings settings, string jsPath, bool asModule)
 {
     this.ApiSelections = settings.ApiSelections;
     this.CamelCase     = settings.ClientApiOutputs.CamelCase;
     this.JSPath        = jsPath;
     this.AsModule      = asModule;
     this.ContentType   = settings.ClientApiOutputs.ContentType;
 }
        private static List <T> RetrieveTemplates <T>(CodeGenSettings settings, string interfaceName)
        {
            List <Assembly> assemblies = ReflectionHelper <T> .LoadAssemblies(settings.CompiledTemplateLocation);

            List <T> templates = ReflectionHelper <T> .LoadTemplates(assemblies, interfaceName);

            return(templates);
        }
Ejemplo n.º 8
0
 public CodeGen(CodeGenSettings settings)
 {
     if (settings == null)
     {
         settings = new CodeGenSettings();
     }
     m_settings = settings;
 }
Ejemplo n.º 9
0
        public void SerializeTest()
        {
            CodeGenSettings      settings = this.GetSettings();
            XmlSerializerService service  = new XmlSerializerService();

            string actualXml = service.ToXml(settings);

            Assert.AreEqual(Resources.CodeGenSettingsSerializeTestXml, actualXml);
        }
Ejemplo n.º 10
0
        public static IVisualStudioProject SetProjectProperties(CodeGenSettings settings, IClassMetadata classmeta, IVisualStudioProject projectFile, string projectDirectory)
        {
            //Set project properties
            projectFile.ProjectDirectory = projectDirectory;
            projectFile.RootNamespace    = settings.SolutionNamespace;
            projectFile.ProjectNamespace = classmeta.ProjectNamespace;

            return(projectFile);
        }
Ejemplo n.º 11
0
 public JSOutput(CodeGenSettings settings, string jsPath, bool asModule)
 {
     this.ApiSelections = settings.ApiSelections;
     this.CamelCase     = settings.ClientApiOutputs.CamelCase;
     this.JSPath        = jsPath;
     this.AsModule      = asModule;
     this.ContentType   = string.IsNullOrEmpty(settings.ClientApiOutputs.ContentType) ? "application/json" : settings.ClientApiOutputs.ContentType;
     this.NGVersion     = settings.ClientApiOutputs.NGVersion.HasValue ? settings.ClientApiOutputs.NGVersion.Value : 6;
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Renders the template.
        /// </summary>
        /// <param name="table">The table.</param>
        /// <param name="settings">The settings.</param>
        /// <returns></returns>
        public override string RenderTemplate(DatabaseTable table, CodeGenSettings settings)
        {
            IGenerateMethods generateMethods = new DynamicDbParametersResources();

            if (!settings.UseDynamicParameters)
            {
                generateMethods = new StaticDbParametersResources();
            }

            return(generateMethods.Render(table, settings));
        }
        private static List <IVisualStudioProject> GenerateClasses(CodeGenSettings settings, List <DatabaseTable> tables)
        {
            List <IVisualStudioProject> vsProjects = new List <IVisualStudioProject>();

            vsProjects = ClassesLogic.GenerateDynamicClasses(settings, tables, vsProjects);
            vsProjects = ClassesLogic.GenerateStaticClasses(settings, vsProjects);

            //Renders projects and the added files.
            ClassesLogic.RenderProjects(vsProjects);

            return(vsProjects);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="excludedControllerNames">Excluse some Api Controllers from being exposed to the client API. Each item should be fully qualified class name but without the assembly name.</param>
        /// <remarks>The client data types should better be generated through SvcUtil.exe with the DC option. The client namespace will then be the original namespace plus suffix ".client". </remarks>
        public ControllersClientApiGen(CodeGenSettings codeGenParameters)
        {
            if (codeGenParameters == null)
            {
                throw new System.ArgumentNullException("codeGenParameters");
            }

            this.codeGenParameters = codeGenParameters;
            targetUnit             = new CodeCompileUnit();
            sharedContext          = new SharedContext();
            poco2CsGen             = new Poco2CsGen(targetUnit);
        }
Ejemplo n.º 15
0
        public override string RenderTemplate(DatabaseTable table, CodeGenSettings settings)
        {
            string contents = Core.ResourceFileHelper.ConvertStreamResourceToUTF8String(typeof(Model), "Chucksoft.Templates.Templates.Enity.template");

            //Check for expected content, if not found, badness has happen.
            if (string.IsNullOrEmpty(contents))
            {
                throw new ContentNotFound("Can't find embeddedResource \"Chucksoft.Templates.Templates.Enity.template\"");
            }

            contents = contents.Replace("<%[Properties]%>", RenderProperties(table.Columns));
            return(contents);
        }
        public IHttpActionResult TriggerCodeGen(CodeGenSettings settings)
        {
            if (settings == null)
            {
                return(BadRequest("No settings"));
            }

            if (settings.ClientApiOutputs == null)
            {
                return(BadRequest("No settings/ClientApiOutputs"));
            }

            string webRootPath = System.Web.Hosting.HostingEnvironment.MapPath("~");

            Fonlow.Web.Meta.WebApiDescription[] apiDescriptions;
            try
            {
                apiDescriptions = Configuration.Services.GetApiExplorer().ApiDescriptions.Select(d => Fonlow.Web.Meta.MetaTransform.GetWebApiDescription(d)).OrderBy(d => d.ActionDescriptor.ActionName).ToArray();
            }
            catch (Fonlow.Web.Meta.CodeGenException e)
            {
                var msg = e.Message + (string.IsNullOrEmpty(e.Description) ? string.Empty : (" : " + e.Description));
                System.Diagnostics.Trace.TraceError(msg);
                return(BadRequest(msg));
            }
            catch (System.InvalidOperationException e)
            {
                System.Diagnostics.Trace.TraceWarning(e.Message);
                return(InternalServerError(e));
            }

            if (!settings.ClientApiOutputs.CamelCase.HasValue)
            {
                var camelCase = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver is Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver;
                settings.ClientApiOutputs.CamelCase = camelCase;
            }

            try
            {
                CodeGen.GenerateClientAPIs(webRootPath, settings, apiDescriptions);
            }
            catch (Fonlow.Web.Meta.CodeGenException e)
            {
                var msg = e.Message + (string.IsNullOrEmpty(e.Description) ? string.Empty : (" : " + e.Description));
                System.Diagnostics.Trace.TraceError(msg);
                return(BadRequest(msg));
            }

            return(Ok("Done"));
        }
Ejemplo n.º 17
0
        public ActionResult TriggerCodeGen([FromBody] CodeGenSettings settings)
        {
            if (settings == null)
            {
                return(BadRequest("No settings"));
            }

            if (settings.ClientApiOutputs == null)
            {
                return(BadRequest("No settings/ClientApiOutputs"));
            }

            Fonlow.Web.Meta.WebApiDescription[] apiDescriptions;
            try
            {
                var descriptions = ApiExplorerHelper.GetApiDescriptions(apiExplorer);
                apiDescriptions = descriptions.Select(d => Fonlow.Web.Meta.MetaTransform.GetWebApiDescription(d)).OrderBy(d => d.ActionDescriptor.ActionName).ToArray();
            }
            catch (Fonlow.Web.Meta.CodeGenException e)
            {
                System.Diagnostics.Trace.TraceWarning(e.Message);
                return(StatusCode((int)HttpStatusCode.InternalServerError, e.Message));
            }
            catch (System.InvalidOperationException e)
            {
                System.Diagnostics.Trace.TraceWarning(e.Message);
                return(StatusCode((int)HttpStatusCode.InternalServerError, e.Message));
            }

            if (!settings.ClientApiOutputs.CamelCase.HasValue)
            {
                settings.ClientApiOutputs.CamelCase = true;
            }

            try
            {
                CodeGen.GenerateClientAPIs(this.webRootPath, settings, apiDescriptions);
                System.IO.File.WriteAllText(@"c:\temp\mygen.json", Newtonsoft.Json.JsonConvert.SerializeObject(apiDescriptions, Newtonsoft.Json.Formatting.Indented));
            }
            catch (Fonlow.Web.Meta.CodeGenException e)
            {
                var msg = e.Message + (string.IsNullOrEmpty(e.Description) ? string.Empty : (" : " + e.Description));
                System.Diagnostics.Trace.TraceError(msg);
                return(BadRequest(msg));
            }

            return(Ok("Done"));
        }
Ejemplo n.º 18
0
        public string TriggerCodeGen(CodeGenSettings settings)
        {
            if (settings == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    ReasonPhrase = "parametersNull"
                });
            }

            string webRootPath = System.Web.Hosting.HostingEnvironment.MapPath("~");

            Fonlow.Web.Meta.WebApiDescription[] apiDescriptions;
            try
            {
                apiDescriptions = Configuration.Services.GetApiExplorer().ApiDescriptions.Select(d => Fonlow.Web.Meta.MetaTransform.GetWebApiDescription(d)).ToArray();
            }
            catch (System.InvalidOperationException e)
            {
                System.Diagnostics.Trace.TraceWarning(e.Message);
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    ReasonPhrase = "CodeGenNotReady"
                });
            }

            if (!settings.ClientApiOutputs.CamelCase.HasValue)
            {
                var camelCase = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver is Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver;
                settings.ClientApiOutputs.CamelCase = camelCase;
            }

            try
            {
                CodeGen.GenerateClientAPIs(webRootPath, settings, apiDescriptions);
            }
            catch (Fonlow.Web.Meta.CodeGenException e)
            {
                System.Diagnostics.Trace.TraceError(e.Message + " : " + e.Description);
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    ReasonPhrase = e.Message,
                    Content      = String.IsNullOrEmpty(e.Description) ? null : new StringContent(e.Description, System.Text.Encoding.UTF8, "text/plain"),
                });
            }

            return("OK");
        }
        public static void Generate(CodeGenSettings settings, List <DatabaseTable> tables)
        {
            //generate project files (classes, static assets)
            List <IVisualStudioProject> projects = GenerateClasses(settings, tables);

            //Add projects to the solution
            VisualStudioSolution solution = new VisualStudioSolution {
                Projects = projects
            };

            solution.Render(settings.CodeGenerationDirectory, settings.SolutionNamespace);

            //generate solution assets (Database scripts, thirdparty assemblies)...
            GenerateStaticSolutionAssets(settings);
            GenerateDynamicSolutionAssets(settings, tables);
        }
Ejemplo n.º 20
0
        public void Execute(
            CodeGenSettings config,
            List <EntityMetadata> entitMetadatas,
            Dictionary <string, PicklistAttributeMetadata> picklists,
            Dictionary <string, string> referencedEntities
            )
        {
            var provider             = new Microsoft.CSharp.CSharpCodeProvider();
            var codeGeneratorOptions = new CodeGeneratorOptions();

            var ns = CreateNameSpace(config.Namespace);

            foreach (var entitMetadata in entitMetadatas.OrderBy(p => p.SchemaName))
            {
                MakeEntity(entitMetadata, ns, picklists, referencedEntities);
            }

            var generatedOptionsets = new List <string>();

            foreach (var picklist in picklists.Values.OrderBy(p => p.LogicalName))
            {
                if (generatedOptionsets.Contains(picklist.OptionSet.Name))
                {
                    continue;
                }
                generatedOptionsets.Add(picklist.OptionSet.Name);
                MakOptionSet(picklist, ns);
            }

            var cu = new CodeCompileUnit();

            cu.Namespaces.Add(ns);

            codeGeneratorOptions.BlankLinesBetweenMembers = false;
            codeGeneratorOptions.BracingStyle             = "C";
            codeGeneratorOptions.IndentString             = "   ";

            var code         = new StringBuilder();
            var stringWriter = new StringWriter(code);

            provider.GenerateCodeFromCompileUnit(cu, stringWriter, codeGeneratorOptions);

            var result = code.ToString().Replace("PowerAppsWebApiUtils.Entities.", "");

            System.IO.File.WriteAllText(config.FileName, result);
        }
        public IVisualStudioProject Render <T>(CodeGenSettings settings, object template, IEnumerable <T> collection, IVisualStudioProject projectFile)
        {
            IStaticAsset         asset           = (IStaticAsset)template;
            List <StaticContent> renderedAssests = asset.Render();


            IClassMetadata classmeta = asset;

            string projectNamespace = string.Format("{0}.{1}", settings.SolutionNamespace, classmeta.ProjectNamespace);
            string projectDirectory = string.Format(@"{0}\{1}", settings.CodeGenerationDirectory, projectNamespace);

            projectFile = ClassesLogic.SetProjectProperties(settings, classmeta, projectFile, projectDirectory);

            //create Directory if it doesn't exists
            if (!File.Exists(projectDirectory))
            {
                Directory.CreateDirectory(projectDirectory);
            }

            //Set File properties... optional Namespace, and the full file path.
            string fullProjectNamespace = projectNamespace + ClassesLogic.AddFolderNamespaces(classmeta);


            foreach (StaticContent content in renderedAssests)
            {
                string filePath         = string.Format(@"{0}\{1}{2}", projectDirectory, classmeta.ClassFilePath, content.FileName);
                string projectClassPath = (string.IsNullOrEmpty(classmeta.ClassFilePath)
                               ? content.FileName
                               : classmeta.ClassFilePath + content.FileName);

                ProjectArtifact artifact = new ProjectArtifact(projectClassPath, content.CreateGeneratedCounterpart);
                projectFile.Classes.Add(artifact);

                StaticContent _content = content;
                if (content.SetNamespace)
                {
                    _content.Content = SetNamespaceAndClass(content.Content.ToString(), fullProjectNamespace);
                }

                SaveContent(classmeta, projectDirectory, content, _content, fullProjectNamespace, filePath);
            }

            return(projectFile);
        }
        private static void GenerateDynamicSolutionAssets(CodeGenSettings settings, IEnumerable <DatabaseTable> tables)
        {
            List <IDynamicSolutionAsset> dynamicTemplates = RetrieveTemplates <IDynamicSolutionAsset>(settings, "IDynamicSolutionAsset");

            foreach (IDynamicSolutionAsset asset in dynamicTemplates)
            {
                foreach (DatabaseTable table in tables)
                {
                    GenerationArtifact content      = asset.RenderTemplate(table, settings);
                    string             dirPath      = string.Format("{0}\\{1}", settings.CodeGenerationDirectory, asset.FolderName);
                    string             fullFilePath = string.Format("{0}\\{1}", dirPath, content.FileName);

                    if (!File.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath);
                    }

                    File.WriteAllText(fullFilePath, content.Content.ToString());
                }
            }
        }
        private void GenerateInsertMethods(DatabaseTable table, CodeGenSettings settings)
        {
            StringBuilder builder = new StringBuilder();

            if (settings.ReturnIdentityFromInserts)
            {
                builder.AppendLine(string.Format("\t\t\tList<DbParameter> parameters = database.GetParameters({0});", table.Name));
                builder.AppendLine("\r\n \t\t\tparameters.SelectIdentity();");
            }

            if (!settings.ReturnIdentityFromInserts)
            {
                builder.Append(string.Format("\t\t\treturn _database.NonQuery(\"{0}_Insert\", {1});", table.Name, table.Name.ToLower()));
            }
            else
            {
                builder.Append(string.Format("\r\n \t\t\t_database.NonQuery(\"{0}_Insert\", parameters); \r\n \t\t\t return parameters.Identity<int>(); ", table.Name));
            }

            _content = _content.Replace("<%[InsertMethod]%>", builder.ToString());
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Generates the InsertStatements
        /// </summary>
        /// <param name="table"></param>

        /// <returns>A complete insert statement</returns>
        private string GenerateInsertStatement(DatabaseTable table, CodeGenSettings settings)
        {
            List <DatabaseColumn> columns = table.Columns.Where(c => !c.IsPrimaryKey).ToList();

            string procedureName    = table.Name + "_Insert";
            string insertColumns    = GetColumns(columns, false);
            string insertParameters = GetColumns(columns, true);

            string outIdentity = string.Empty;


            //build the insert statement
            string procedureStatement = string.Format("\tINSERT INTO [dbo].[{0}] ({1}) \r\n\tVALUES ({2})", table.Name, insertColumns, insertParameters);

            if (settings.ReturnIdentityFromInserts)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine("\r\n\t@Identity INT OUTPUT = null");

                outIdentity = builder.ToString();

                StringBuilder builder1 = new StringBuilder(procedureStatement);
                const string  newLine  = "\r\n\t";

                const string sql = newLine + newLine + "IF @Identity IS NOT NULL" +
                                   newLine + "BEGIN" +
                                   newLine + "\tSet @Identity = SELECT SCOPE_IDENTITY()" +
                                   newLine + "END";

                builder1.AppendLine(sql);
                procedureStatement = builder1.ToString();
            }

            string insertStatementSignatureParameters = GenerateParameterList(table, false, outIdentity);

            //replace tokens in the stored procedure template
            string content = ProcedureTokenReplacement(procedureName, procedureStatement, insertStatementSignatureParameters);

            return(content);
        }
Ejemplo n.º 25
0
        public ActionResult TriggerCodeGen([FromBody] CodeGenSettings settings)
        {
            if (settings == null || settings.ClientApiOutputs == null)
            {
                return(new BadRequestResult());
            }

            string webRootPath = hostingEnvironment.WebRootPath;

            Fonlow.Web.Meta.WebApiDescription[] apiDescriptions;
            try
            {
                var descriptions = ApiExplorerHelper.GetApiDescriptions(apiExplorer);
                apiDescriptions = descriptions.Select(d => Fonlow.Web.Meta.MetaTransform.GetWebApiDescription(d)).ToArray();
            }
            catch (System.InvalidOperationException e)
            {
                System.Diagnostics.Trace.TraceWarning(e.Message);
                return(StatusCode((int)HttpStatusCode.ServiceUnavailable));
            }

            if (!settings.ClientApiOutputs.CamelCase.HasValue)
            {
                settings.ClientApiOutputs.CamelCase = true;
            }

            try
            {
                CodeGen.GenerateClientAPIs(webRootPath, settings, apiDescriptions);
            }
            catch (Fonlow.Web.Meta.CodeGenException e)
            {
                var msg = e.Message + " : " + e.Description;
                System.Diagnostics.Trace.TraceError(msg);
                return(BadRequest(msg));
            }

            return(Ok());
        }
Ejemplo n.º 26
0
        private List <string> GetProcedures(DatabaseTable table, CodeGenSettings settings)
        {
            List <string> prodecures = new List <string>();

            //Add the generated Insert statement to the collection
            string insertProcedure = GenerateInsertStatement(table, settings);

            prodecures.Add(insertProcedure);

            const string deleteProcedureName = "Delete";
            string       deleteSql           = string.Format("\tDelete From {0}", table.Name);
            string       deleteProcedure     = GenerateDeleteStatementByPrimaryKey(table, deleteProcedureName, deleteSql);

            prodecures.Add(deleteProcedure);

            //Generate the SelectByPrimaryKey procedure
            string       selectSql           = string.Format("\tSelect {0} \r\n\tFrom {1}", GetColumns(table.Columns, false), table.Name);
            const string selectProcedureName = "SelectByPrimaryKey";
            string       selectByPrimaryKey  = GenerateDeleteStatementByPrimaryKey(table, selectProcedureName, selectSql);

            prodecures.Add(selectByPrimaryKey);

            //generate the Update procedure
            string       updateSql           = string.Format("\tUpdate {0} \r\n\tSET {1}", table.Name, GetUpdateColumns(table));
            string       updateParameterList = GenerateParameterList(table, true, string.Empty);
            const string updateProcedureName = "Update";
            string       updateProcedure     = GenerateUpdateProcedure(table, updateProcedureName, updateSql, updateParameterList);

            prodecures.Add(updateProcedure);

            //generate the SelectAll procedure
            string       selectAllSql           = string.Format("\tSelect {0} \r\n\tFrom {1}", GetColumns(table.Columns, false), table.Name);
            const string selectAllProcedureName = "SelectAll";
            string       selectAllProcedure     = GenerateSelectAllProcedure(table, selectAllProcedureName, selectAllSql);

            prodecures.Add(selectAllProcedure);
            return(prodecures);
        }
        public IVisualStudioProject Render <T>(CodeGenSettings settings, object template, IEnumerable <T> collection, IVisualStudioProject projectFile)
        {
            ICompiledTemplate           _template = (ICompiledTemplate)template;
            IEnumerable <DatabaseTable> tables    = (IEnumerable <DatabaseTable>)collection;

            IClassMetadata classmeta = _template;

            //Creating project specific variables
            string projectNamespace = string.Format("{0}.{1}", settings.SolutionNamespace, classmeta.ProjectNamespace);
            string projectDirectory = string.Format(@"{0}\{1}", settings.CodeGenerationDirectory, projectNamespace);

            //Set the project properties. These should never change.
            ClassesLogic.SetProjectProperties(settings, classmeta, projectFile, projectDirectory);
            string fileDirectory = (string.IsNullOrEmpty(classmeta.ClassFilePath) ? projectDirectory : string.Format(@"{0}\{1}", projectDirectory, classmeta.ClassFilePath));

            //create the project and project sub directory
            CreateProjectAndClassDirectories(projectDirectory, fileDirectory);
            string fileNamespace = projectNamespace + ClassesLogic.AddFolderNamespaces(classmeta);

            //Render out the Templates by passing in the collection of Tables
            foreach (DatabaseTable table in tables)
            {
                string filename         = table.Name + classmeta.FilenameAppending;
                string projectClassPath = (string.IsNullOrEmpty(classmeta.ClassFilePath)
                                               ? filename
                                               : classmeta.ClassFilePath + filename);
                projectFile.Classes.Add(new ProjectArtifact(projectClassPath + ".cs", true));

                string fullQualifiedPathOfClass = string.Format(@"{0}\{1}.cs", fileDirectory, filename);
                string content = _template.RenderTemplate(table, settings);

                //Write out Generated code
                content = SetNamespaceAndClass(content, filename, fileNamespace);
                File.WriteAllText(fullQualifiedPathOfClass, content);
            }

            return(projectFile);
        }
        public string Render(DatabaseTable table, CodeGenSettings settings)
        {
            _content = Core.ResourceFileHelper.ConvertStreamResourceToUTF8String(typeof(Resources), "Chucksoft.Templates.Templates.Resources.template");

            //Check for expected content, if not found, badness has happen.
            if (string.IsNullOrEmpty(_content))
            {
                throw new ContentNotFound("Can't find embeddedResource \"Chucksoft.Templates.Templates.Resources.template\"");
            }

            GetItem(table);
            GenerateDeleteMethods(table);
            GenerateInsertMethods(table, settings);
            GenerateUpdateMethods(table);
            GenerateSelectAll(table);
            GenerateSelectByPrimaryKey(table);
            GeneratePopulateMethod(table);
            _content = _content.Replace("<%[TableName]%>", table.Name);
            _content = _content.Replace("<%[TableParameter]%>", table.Name.ToLower());


            return(_content);
        }
        private static void GenerateStaticSolutionAssets(CodeGenSettings settings)
        {
            List <IStaticSolutionAsset> dynamicTemplates = RetrieveTemplates <IStaticSolutionAsset>(settings, "IStaticSolutionAsset");

            foreach (IStaticSolutionAsset asset in dynamicTemplates)
            {
                List <GenerationArtifact> assets = asset.Render(settings);

                foreach (GenerationArtifact sa in assets)
                {
                    string content      = sa.Content.ToString();
                    string dirPath      = string.Format("{0}\\{1}", settings.CodeGenerationDirectory, asset.FolderName);
                    string fullFilePath = string.Format("{0}\\{1}", dirPath, sa.FileName);

                    if (!File.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath);
                    }

                    File.WriteAllText(fullFilePath, content);
                }
            }
        }
Ejemplo n.º 30
0
        public void Execute(CodeGenSettings settings)
        {
            var serviceProvider =
                new ServiceCollection()
                .AddLogging(p => p.AddConsole())
                .Configure <LoggerFilterOptions>(p => p.AddFilter((category, logLevel) => category.Contains(nameof(CodeGenProcess))))
                .AddPowerAppsWebApiConfiguration(settings.AuthenticationSettings)
                .AddTransient <EntityMetadataRepository>()
                .AddTransient <OptionSetMetadataRepository>()
                .BuildServiceProvider();

            var logger = serviceProvider.GetRequiredService <ILogger <CodeGenProcess> >();

            logger.LogInformation($"{nameof(CodeGenProcess)}. Starting process.");
            logger.LogInformation($"PowerAspps Url: {settings.AuthenticationSettings.ResourceUrl}");
            logger.LogInformation($"Entities: {string.Join(", ", settings.Entities)}");
            var now = DateTime.Now;

            using (var entityDefinitionRepository = serviceProvider.GetRequiredService <EntityMetadataRepository>())
                using (var picklistRepository = serviceProvider.GetRequiredService <OptionSetMetadataRepository>())
                {
                    var tasks =
                        settings
                        .Entities
                        .GroupBy(p => p)
                        .Select(p => p.First())
                        .Select(p =>
                    {
                        logger.LogInformation($"Fetching metadata of entity '{p}'");
                        return(entityDefinitionRepository.GetByLogicalName(p));
                    }).ToArray();
                    Task.WaitAll(tasks);
                    var entities = tasks.Select(p => p.Result).ToList();

                    logger.LogInformation($"Entities metadata done. Ready to fetch picklists metadata.");
                    var pickLists          = new Dictionary <string, Task <PicklistAttributeMetadata> >();
                    var referencedEntities = new Dictionary <string, Task <string> >();
                    entities.ForEach(
                        p =>
                    {
                        p.Attributes
                        .Where(q => q.AttributeType == AttributeTypeCode.Picklist || q.AttributeType == AttributeTypeCode.State || q.AttributeType == AttributeTypeCode.Status)
                        .GroupBy(q => q.LogicalName)
                        .Select(q => q.First())
                        .ToList()
                        .ForEach(
                            q =>
                        {
                            var key = $"{p.LogicalName}-{q.LogicalName}";
                            if (pickLists.ContainsKey(key))
                            {
                                return;
                            }

                            logger.LogInformation($"Fetching metadata of picklist '{key}'");
                            pickLists.Add(key, picklistRepository.GetOptionsetMetadata(q));
                        });

                        p.Attributes
                        .Where(q => q.AttributeType == AttributeTypeCode.Lookup)
                        .GroupBy(q => q.LogicalName)
                        .Select(q => q.First())
                        .ToList()
                        .ForEach(
                            q =>
                        {
                            foreach (var target in ((LookupAttributeMetadata)q).Targets)
                            {
                                if (referencedEntities.ContainsKey(target))
                                {
                                    return;
                                }
                                referencedEntities.Add(target, entityDefinitionRepository.GetLogicalCollectionName(target));
                            }
                        });
                    });

                    Task.WaitAll(pickLists.Select(p => p.Value).ToArray());
                    Task.WaitAll(referencedEntities.Select(p => p.Value).ToArray());


                    logger.LogInformation($"Fechting metadata done. Ready to generate code");
                    new CodeGen()
                    .Execute(
                        settings,
                        entities,
                        pickLists.ToDictionary(p => p.Key, p => p.Value.Result),
                        referencedEntities.ToDictionary(p => p.Key, p => p.Value.Result)
                        );
                    logger.LogInformation($"Code generated in file {settings.FileName}");
                    logger.LogInformation($"Processing time: {(DateTime.Now - now).ToString("c")}");
                    logger.LogInformation($"{nameof(CodeGenProcess)}. Ending process.");
                }
        }
 public abstract List<GenerationArtifact> Render(CodeGenSettings settings);
 public abstract GenerationArtifact RenderTemplate(DatabaseTable table, CodeGenSettings settings);
 public abstract string RenderTemplate(DatabaseTable table, CodeGenSettings settings);