private void WriteReader(ClassTemplate classTemplate, ModelTransferObject model) { IOptions modelOptions = this.Options.Get(model); TypeTemplate objectType = Code.Type(model.Name, model.Namespace); if (model.Namespace != classTemplate.Namespace.Name && model.Namespace != null) { classTemplate.AddUsing(model.Namespace); } classTemplate.WithUsing("Newtonsoft.Json") //.WithUsing("Newtonsoft.Json.Linq") .WithUsing("System.IO"); classTemplate.AddMethod("Load", objectType) .FormatName(modelOptions) .WithParameter(Code.Type("string"), "fileName") .Static() .Code.AddLine(Code.Return(Code.Method("Parse", Code.Local("File").Method("ReadAllText", Code.Local("fileName"))))); classTemplate.AddMethod("Parse", objectType) .FormatName(modelOptions) .WithParameter(Code.Type("string"), "json") .Static() .Code.AddLine(Code.Return(Code.Local("JsonConvert").GenericMethod("DeserializeObject", objectType, Code.Local("json")))); }
public void Write(WriteCommandParameters parameters, List <FileTemplate> files) { Logger.Trace($"Write a class for \"{parameters.Message}\"..."); ClassTemplate classTemplate = files.AddFile(parameters.RelativePath, !parameters.SkipHeader, null) .AddNamespace(parameters.Namespace) .AddClass(parameters.Class) /*.FormatName(parameters.FormatNames)*/; classTemplate.WithUsing("System", null, null) .AddMethod("Write", Code.Void()) .Code.AddLine(Code.Static(Code.Type("Console")).Method("WriteLine", Code.String(parameters.Message)).Close()); }
public void Write(DemoWriteConfiguration configuration, List <ITransferObject> transferObjects, List <FileTemplate> files) { foreach (ModelTransferObject model in transferObjects.OfType <ModelTransferObject>()) { Logger.Trace($"Write {model.Name}..."); ClassTemplate classTemplate = files.AddFile(configuration.RelativePath, configuration.AddHeader) .AddNamespace(model.Namespace) .AddClass(model.Name) .FormatName(configuration); foreach (PropertyTransferObject property in model.Properties) { classTemplate.AddProperty(property.Name, property.Type.ToTemplate()); } if (configuration.Test2) { classTemplate.WithUsing("System", null, null) .AddMethod("Test2", Code.Void()) .Code.AddLine(Code.Static(Code.Type("Console")).Method("WriteLine", Code.String("Hello World!")).Close()); } } }
public virtual void Write(EntityFrameworkWriteConfiguration configuration, List <ITransferObject> transferObjects, List <FileTemplate> files) { foreach (EntityFrameworkWriteRepositoryConfiguration repositoryConfiguration in configuration.Repositories) { EntityTransferObject entity = transferObjects.OfType <EntityTransferObject>().FirstOrDefault(x => x.Name == repositoryConfiguration.Entity) .AssertIsNotNull(nameof(repositoryConfiguration.Entity), $"Entity {repositoryConfiguration.Entity} not found. Ensure it is read before."); ClassTemplate repository = files.AddFile(configuration.RelativePath, configuration.AddHeader) .AddNamespace(repositoryConfiguration.Namespace ?? configuration.Namespace) .AddClass(repositoryConfiguration.Name ?? entity.Name + "Repository") .FormatName(configuration) .WithUsing("System.Collections.Generic") .WithUsing("System.Linq"); if (configuration.IsCore) { repository.WithUsing("Microsoft.EntityFrameworkCore"); } else { repository.WithUsing("System.Data.Entity"); } if (!string.IsNullOrEmpty(configuration.Namespace) && !string.IsNullOrEmpty(repositoryConfiguration.Namespace) && configuration.Namespace != repositoryConfiguration.Namespace) { repository.AddUsing(configuration.Namespace); } configuration.Usings.ForEach(x => repository.AddUsing(x)); repositoryConfiguration.Usings.ForEach(x => repository.AddUsing(x)); TypeTemplate modelType = entity.Model.ToTemplate(); FieldTemplate dataSetField = repository.AddField("dataSet", Code.Generic("DbSet", modelType)).Readonly(); FieldTemplate dataContextField = repository.AddField("dataContext", Code.Type("DataContext")).Readonly(); TypeTemplate dataContextType = Code.Type("DataContext"); ConstructorTemplate constructor = repository.AddConstructor(); ParameterTemplate dataContextParameter = constructor.AddParameter(dataContextType, "dataContext", Code.Null()); constructor.Code.AddLine(Code.This().Field(dataContextField).Assign(Code.NullCoalescing(Code.Local(dataContextParameter), Code.New(dataContextType))).Close()) .AddLine(Code.This().Field(dataSetField).Assign(Code.This().Field(dataContextField).GenericMethod("Set", modelType)).Close()); repository.AddMethod("Get", Code.Generic("IQueryable", modelType)) .Code.AddLine(Code.Return(Code.This().Field(dataSetField))); repository.AddMethod("Get", modelType) .WithParameter(Code.Type("params object[]"), "keys") .Code.AddLine(Code.Return(Code.This().Field(dataSetField).Method("Find", Code.Local("keys")))); if (configuration.IsCore) { repository.AddMethod("Add", modelType) .WithParameter(modelType, "entity") .Code.AddLine(Code.Declare(modelType, "result", Code.This().Field(dataSetField).Method("Add", Code.Local("entity")).Property("Entity"))) .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()) .AddLine(Code.Return(Code.Local("result"))); repository.AddMethod("Add", Code.Generic("IEnumerable", modelType)) .WithParameter(Code.Generic("IEnumerable", modelType), "entities") .Code.AddLine(Code.Declare(Code.Generic("IEnumerable", modelType), "result", Code.Local("entities").Method("Select", Code.Lambda("x", Code.This().Field(dataSetField).Method("Add", Code.Local("x")).Property("Entity"))).Method("ToList"))) .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()) .AddLine(Code.Return(Code.Local("result"))); repository.AddMethod("Update", modelType) .WithParameter(modelType, "entity") .Code.AddLine(Code.Declare(modelType, "result", Code.This().Field(dataSetField).Method("Update", Code.Local("entity")).Property("Entity"))) .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()) .AddLine(Code.Return(Code.Local("result"))); repository.AddMethod("Update", Code.Generic("IEnumerable", modelType)) .WithParameter(Code.Generic("IEnumerable", modelType), "entities") .Code.AddLine(Code.Declare(Code.Generic("IEnumerable", modelType), "result", Code.Local("entities").Method("Select", Code.Lambda("x", Code.This().Field(dataSetField).Method("Update", Code.Local("x")).Property("Entity"))).Method("ToList"))) .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()) .AddLine(Code.Return(Code.Local("result"))); } else { repository.AddMethod("Add", modelType) .WithParameter(modelType, "entity") .Code.AddLine(Code.Declare(modelType, "result", Code.This().Field(dataSetField).Method("Add", Code.Local("entity")))) .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()) .AddLine(Code.Return(Code.Local("result"))); repository.AddMethod("Add", Code.Generic("IEnumerable", modelType)) .WithParameter(Code.Generic("IEnumerable", modelType), "entities") .Code.AddLine(Code.Declare(Code.Generic("IEnumerable", modelType), "result", Code.Local("entities").Method("Select", Code.Lambda("x", Code.This().Field(dataSetField).Method("Add", Code.Local("x")))).Method("ToList"))) .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()) .AddLine(Code.Return(Code.Local("result"))); repository.WithUsing("System.Data.Entity.Migrations") .AddMethod("Update", modelType) .WithParameter(modelType, "entity") .Code.AddLine(Code.This().Field(dataSetField).Method("AddOrUpdate", Code.Local("entity")).Close()) .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()) .AddLine(Code.Return(Code.Local("entity"))); repository.WithUsing("System.Data.Entity.Migrations") .AddMethod("Update", Code.Generic("IEnumerable", modelType)) .WithParameter(Code.Generic("IEnumerable", modelType), "entities") .Code.AddLine(Code.Declare(Code.Generic("List", modelType), "result", Code.Local("entities").Method("ToList"))) .AddLine(Code.Local("result").Method("ForEach", Code.Lambda("x", Code.This().Field(dataSetField).Method("AddOrUpdate", Code.Local("x")))).Close()) .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()) .AddLine(Code.Return(Code.Local("result"))); } //repository.AddMethod("Update", Code.Void()) // .WithParameter(Code.Generic("Delta", modelType), "delta") // .WithParameter(Code.Type("object[]"), "keys") // .Code.AddLine(Code.Declare(modelType, "entity", Code.This().Field(dataSetField).Method("Find", Code.Local("keys")))) // .AddLine(Code.If(Code.Local("entity").Equals().Null(), x => x.Code.AddLine(Code.Throw(Code.Type("InvalidOperationException"), Code.String("Can not find any element with this keys, Use Add(...) method instead"))))) // .AddLine(Code.Local("delta").Method("Patch", Code.Local("entity")).Close()) // .AddLine(Code.This().Method("Update", Code.Local("entity")).Close()) // .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()); repository.AddMethod("Delete", Code.Void()) .WithParameter(modelType, "entity") .Code.AddLine(Code.This().Field(dataSetField).Method("Remove", Code.Local("entity")).Close()) .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()); repository.AddMethod("Delete", Code.Void()) .WithParameter(Code.Generic("IEnumerable", modelType), "entities") .Code.AddLine(Code.This().Field(dataSetField).Method("RemoveRange", Code.Local("entities")).Close()) .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()); if (configuration.IsCore) { repository.AddMethod("Delete", Code.Void()) .WithParameter(Code.Type("params object[]"), "keys") .Code.AddLine(Code.This().Field(dataSetField).Method("Remove", Code.This().Field(dataSetField).Method("Find", Code.Local("keys"))).Close()) .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()); } else { repository.AddMethod("Delete", Code.Void()) .WithParameter(Code.Type("params object[]"), "keys") .Code.AddLine(Code.This().Field(dataSetField).Method("Remove", Code.This().Field(dataSetField).Method("Find", Code.Local("keys"))).Close()) .AddLine(Code.This().Field(dataContextField).Method("SaveChanges").Close()); } //foreach (string key in entity.Keys) //{ // PropertyTransferObject property = entity.Model.Properties.First(x => x.Name.Equals(key, StringComparison.InvariantCultureIgnoreCase)); // delete.AddParameter(property.Type.ToTemplate(), property.Name) // .FormatName(configuration.Language, configuration.FormatNames); //} } }
public virtual void Write(AspDotNetWriteConfiguration configuration, List <FileTemplate> files) { Logger.Trace("Generate generator controller for ASP.net..."); if (!configuration.Language.IsCsharp()) { throw new InvalidOperationException($"Can not generate ASP.net Controller for language {configuration.Language?.Name ?? "Empty"}. Only Csharp is currently implemented"); } if (configuration.Standalone) { throw new InvalidOperationException("Can not generate Generator.Controller with KY.Generator.CLI.Standalone use KY.Generator.CLI instead"); } string nameSpace = (configuration.GeneratorController.Namespace ?? configuration.Namespace).AssertIsNotNull(nameof(configuration.Namespace), "asp writer requires a namespace"); ClassTemplate classTemplate = files.AddFile(configuration.GeneratorController.RelativePath ?? configuration.RelativePath, configuration.AddHeader) .AddNamespace(nameSpace) .AddClass("GeneratorController", Code.Type(configuration.Template.ControllerBase)) .WithUsing("System") .WithUsing("System.Linq") .WithUsing("KY.Generator") .WithUsing("KY.Generator.Output"); classTemplate.Usings.AddRange(configuration.Template.Usings); if (configuration.Template.UseOwnCache) { GenericTypeTemplate type = Code.Generic("Dictionary", Code.Type("string"), Code.Type("MemoryOutput")); classTemplate.AddField("cache", type) .FormatName(configuration) .Static() .Readonly() .DefaultValue = Code.New(type); } MethodTemplate createMethod = classTemplate.AddMethod("Create", Code.Type("string")) .FormatName(configuration) .WithParameter(Code.Type("string"), "configuration"); if (!configuration.Template.ValidateInput) { createMethod.WithAttribute("ValidateInput", Code.Local("false")); } MethodTemplate commandMethod = classTemplate.AddMethod("Command", Code.Type("string")) .FormatName(configuration) .WithParameter(Code.Type("string"), "command"); MultilineCodeFragment createCode = createMethod.Code; createCode.AddLine(Code.Declare(Code.Type("string"), "id", Code.Local("Guid").Method("NewGuid").Method("ToString"))) .AddLine(Code.Declare(Code.Type("MemoryOutput"), "output", Code.New(Code.Type("MemoryOutput")))) .AddLine(Code.Declare(Code.Type("Generator"), "generator", Code.New(Code.Type("Generator")))) .AddLine(Code.Local("generator").Method("SetOutput", Code.Local("output")).Close()); MultilineCodeFragment commandCode = commandMethod.Code; commandCode.AddLine(Code.Declare(Code.Type("string"), "id", Code.Local("Guid").Method("NewGuid").Method("ToString"))) .AddLine(Code.Declare(Code.Type("MemoryOutput"), "output", Code.New(Code.Type("MemoryOutput")))) .AddLine(Code.Declare(Code.Type("Generator"), "generator", Code.New(Code.Type("Generator")))) .AddLine(Code.Local("generator").Method("SetOutput", Code.Local("output")).Close()); foreach (string ns in configuration.GeneratorController.Usings) { classTemplate.AddUsing(ns); } foreach (string moduleType in configuration.GeneratorController.PreloadModules) { createCode.AddLine(Code.Local("generator").GenericMethod("PreloadModule", Code.Type(moduleType)).Close()); commandCode.AddLine(Code.Local("generator").GenericMethod("PreloadModule", Code.Type(moduleType)).Close()); } foreach (AspDotNetControllerConfigureModule configure in configuration.GeneratorController.Configures) { createCode.AddLine(Code.Local("generator").Method(configure.Module, Code.Lambda("x", Code.Csharp("x." + configure.Action)))); commandCode.AddLine(Code.Local("generator").Method(configure.Module, Code.Lambda("x", Code.Csharp("x." + configure.Action)))); } createCode.AddLine(Code.Local("generator").Method("ParseConfiguration", Code.Local("configuration")).Close()) .AddLine(Code.Local("generator").Method("Run").Close()) .AddBlankLine(); commandCode.AddLine(Code.Local("generator").Method("ParseCommand", Code.Local("command")).Close()) .AddLine(Code.Local("generator").Method("Run").Close()) .AddBlankLine(); if (configuration.Template.UseOwnCache) { createCode.AddLine(Code.Local("cache").Index(Code.Local("id")).Assign(Code.Local("output")).Close()); commandCode.AddLine(Code.Local("cache").Index(Code.Local("id")).Assign(Code.Local("output")).Close()); } else { createCode.AddLine(Code.Static(Code.Type("HttpContext")).Property("Current").Property("Cache").Index(Code.Local("id")).Assign(Code.Local("output")).Close()); commandCode.AddLine(Code.Static(Code.Type("HttpContext")).Property("Current").Property("Cache").Index(Code.Local("id")).Assign(Code.Local("output")).Close()); } createCode.AddLine(Code.Return(Code.Local("id"))); commandCode.AddLine(Code.Return(Code.Local("id"))); ChainedCodeFragment getFromCacheForFilesFragment = configuration.Template.UseOwnCache ? (ChainedCodeFragment)Code.Local("cache") : Code.Static(Code.Type("HttpContext")).Property("Current").Property("Cache"); MethodTemplate getFilesMethod = classTemplate.AddMethod("GetFiles", Code.Type("string")) .FormatName(configuration) .WithParameter(Code.Type("string"), "id"); getFilesMethod.Code.AddLine(Code.If(Code.Local("id").Equals().Null(), x => x.Code.AddLine(Code.Return(Code.Null())))) .AddLine(Code.Declare(Code.Type("MemoryOutput"), "output", getFromCacheForFilesFragment.Index(Code.Local("id")).As(Code.Type("MemoryOutput")))) .AddLine(Code.Return(Code.InlineIf(Code.Local("output").Equals().Null(), Code.Null(), Code.Local("string").Method("Join", Code.Local("Environment").Property("NewLine"), Code.Local("output").Property("Files").Method("Select", Code.Lambda("x", Code.Local("x").Property("Key"))))))); ChainedCodeFragment getFromCacheForFileFragment = configuration.Template.UseOwnCache ? (ChainedCodeFragment)Code.Local("cache") : Code.Static(Code.Type("HttpContext")).Property("Current").Property("Cache"); MethodTemplate getFileMethod = classTemplate.AddMethod("GetFile", Code.Type("string")) .FormatName(configuration) .WithParameter(Code.Type("string"), "id") .WithParameter(Code.Type("string"), "path"); getFileMethod.Code.AddLine(Code.If(Code.Local("id").Equals().Null(), x => x.Code.AddLine(Code.Return(Code.Null())))) .AddLine(Code.Declare(Code.Type("MemoryOutput"), "output", getFromCacheForFileFragment.Index(Code.Local("id")).As(Code.Type("MemoryOutput")))) .AddLine(Code.Return(Code.InlineIf(Code.Local("output").Equals().Null().Or().Not().Local("output").Property("Files").Method("ContainsKey", Code.Local("path")), Code.Null(), Code.Local("output").Property("Files").Index(Code.Local("path"))))); MethodTemplate availableMethod = classTemplate.AddMethod("Available", Code.Type("bool")) .FormatName(configuration); availableMethod.Code.AddLine(Code.Return(Code.Local("true"))); if (configuration.Template.UseAttributes) { classTemplate.WithUsing("Microsoft.AspNetCore.Mvc") .WithAttribute("Route", Code.String("[controller]")) .WithAttribute("Route", Code.String("api/v1/[controller]")); createMethod.WithAttribute("HttpPost", Code.String("[action]")); commandMethod.WithAttribute("HttpPost", Code.String("[action]")); getFilesMethod.WithAttribute("HttpPost", Code.String("[action]")); getFileMethod.WithAttribute("HttpPost", Code.String("[action]")); availableMethod.WithAttribute("HttpGet", Code.String("[action]")); } }
protected virtual ClassTemplate WriteClass(EntityFrameworkWriteConfiguration configuration, List <ITransferObject> transferObjects, List <FileTemplate> files) { ClassTemplate dataContext = files.AddFile(configuration.RelativePath, configuration.AddHeader) .AddNamespace(configuration.Namespace) .AddClass("DataContext", Code.Type("DbContext")); if (configuration.IsCore) { dataContext.WithUsing("Microsoft.EntityFrameworkCore"); } else { dataContext.WithUsing("System.Data.Entity"); } configuration.Usings.ForEach(x => dataContext.AddUsing(x)); PropertyTemplate defaultConnectionProperty = dataContext.AddProperty("DefaultConnection", Code.Type("string")).Static().WithDefaultValue(Code.String("name=DataContext")); foreach (EntityTransferObject entity in transferObjects.OfType <EntityTransferObject>()) { dataContext.AddProperty(entity.Name, Code.Generic("DbSet", entity.Model.ToTemplate())) .FormatName(configuration) .Virtual(); } dataContext.AddConstructor() .WithThisConstructor(Code.Null()); ConstructorTemplate constructor = dataContext.AddConstructor(); ParameterTemplate connectionString = constructor.AddParameter(Code.Type("string"), "connectionString"); if (configuration.IsCore) { constructor.WithBaseConstructor(Code.Static(Code.Type("SqlServerDbContextOptionsExtensions")).Method("UseSqlServer", Code.New(Code.Type("DbContextOptionsBuilder")), Code.NullCoalescing(Code.Local(connectionString), Code.Local(defaultConnectionProperty))).Property("Options")) .Code.AddLine(Code.This().Property("Database").Method("SetCommandTimeout", Code.Number(configuration.DataContext.CommandTimeout)).Close()); } else { constructor.WithBaseConstructor(Code.NullCoalescing(Code.Local("connectionString"), Code.Local(defaultConnectionProperty))) .Code.AddLine(Code.This().Property("Database").Property("CommandTimeout").Assign(Code.Number(configuration.DataContext.CommandTimeout)).Close()); } MethodTemplate createMethod = dataContext.AddMethod("OnModelCreating", Code.Void()).Protected().Override(); ParameterTemplate modelBuilder = createMethod.AddParameter(Code.Type(configuration.IsCore ? "ModelBuilder" : "DbModelBuilder"), "modelBuilder"); if (!configuration.IsCore) { createMethod.Code.AddLine(Code.Local(modelBuilder).Property("Configurations").Method("AddFromAssembly", Code.This().Method("GetType").Property("Assembly")).Close()); } foreach (EntityTransferObject entity in transferObjects.OfType <EntityTransferObject>()) { createMethod.Code.AddLine(Code.Local(modelBuilder).GenericMethod("Entity", entity.Model.ToTemplate()).BreakLine() .Method("ToTable", Code.String(entity.Table), Code.String(entity.Schema)).BreakLine() .Method("HasKey", Code.Lambda("x", Code.Csharp("new { " + string.Join(", ", entity.Keys.Select(key => $"x.{key.Name}")) + " }"))).Close()); } foreach (StoredProcedureTransferObject storedProcedure in transferObjects.OfType <StoredProcedureTransferObject>()) { dataContext.AddMethod(storedProcedure.Name, storedProcedure.ReturnType.ToTemplate()) .Code.AddLine(Code.This().Property("Database").Method("ExecuteSqlCommand", Code.String($"exec {storedProcedure.Schema}.{storedProcedure.Name}")).Close()); } return(dataContext); }