private void GenerateDbModel() { var dt = GetTableFlat(); var nameText = Namespace ?? "Aescr.Model"; for (int index = 0; index < dt.Rows.Count;) { DataRow dataRow = dt.Rows[index]; var ft = CreateFile(); ft.DownloadPath = DownloadPath + "/DbModel"; var namespaceTemplate = ft.CreateNamespace(); namespaceTemplate.NamespaceName = nameText; ClassTemplate classTemplate = new ClassTemplate(); namespaceTemplate.AddClass(classTemplate); if (RemoveLine) { classTemplate.ClassName = dataRow["表名"].ToString(); classTemplate.ClassName = classTemplate.ClassName.Replace("_", ""); } else { classTemplate.ClassName = dataRow["表名"].ToString(); } classTemplate.RealName = dataRow["表名"].ToString(); classTemplate.Comment = new Code.Template.CommentTemplate(); classTemplate.Comment.CommentName = dataRow["表说明"].ToString(); do { DataRow tempRow = dt.Rows[index]; var field = new Code.Template.FieldTemplate(); var comment = new Code.Template.CommentTemplate(); field.FieldName = tempRow["字段名"].ToString(); comment.CommentName = tempRow["字段说明"].ToString(); field.DbType = tempRow["类型"].ToString(); field.MaxLength = tempRow["长度"].ToString().ToInt64(); field.MinLength = 0; field.Comment = comment; field.IsProperty = true; field.IsKey = tempRow["主键"].ToString() == "√"; field.CanNull = tempRow["允许空"].ToString() == "√"; if (_connect.DbType == DataBaseType.MsSQL) { field.FieldTypeName = DbToCsharpType.MsSqlToCsharpType(tempRow["类型"].ToString()); } else if (_connect.DbType == DataBaseType.MySQL) { field.FieldTypeName = DbToCsharpType.MySqlToCsharpType(tempRow["类型"].ToString()); } classTemplate.AddField(field); index++; if (index == dt.Rows.Count) { break; } } while (string.IsNullOrWhiteSpace(dt.Rows[index]["表名"].ToString())); } }
public void ClassOneFieldAndOneConstructor() { ClassTemplate template = new ClassTemplate((NamespaceTemplate)null, "test"); template.AddField("field1", Code.Type("string")); template.AddConstructor(); ClassWriter writer = new ClassWriter(this.options); writer.Write(template, this.output); Assert.AreEqual("export class test {\r\n private field1: string;\r\n\r\n public constructor() {\r\n }\r\n}", this.output.ToString()); }
protected virtual FieldTemplate AddField(ModelTransferObject model, MemberTransferObject member, ClassTemplate classTemplate) { IOptions fieldOptions = this.Options.Get(member); if (model.Language != null && fieldOptions.Language != null) { this.MapType(model.Language, fieldOptions.Language, member.Type); } this.AddUsing(member.Type, classTemplate, fieldOptions); FieldTemplate fieldTemplate = classTemplate.AddField(member.Name, member.Type.ToTemplate()).Public().FormatName(fieldOptions) .WithComment(member.Comment); if (fieldOptions.WithOptionalProperties) { fieldTemplate.Optional(); } return(fieldTemplate); }
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); //} } }
protected virtual FieldTemplate AddField(ModelTransferObject model, string name, TypeTransferObject type, ClassTemplate classTemplate, IConfiguration configuration) { this.MapType(model.Language, configuration.Language, type); this.AddUsing(type, classTemplate, configuration); return(classTemplate.AddField(name, type.ToTemplate()).Public().FormatName(configuration)); }
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]")); } }
public virtual void Write(AspDotNetWriteConfiguration configuration, List <ITransferObject> transferObjects, List <FileTemplate> files) { if (!configuration.Language.IsCsharp()) { throw new InvalidOperationException($"Can not generate ASP.net Controller for language {configuration.Language?.Name ?? "Empty"}. Only Csharp is currently implemented"); } foreach (AspDotNetWriteEntityControllerConfiguration controllerConfiguration in configuration.Controllers) { EntityTransferObject entity = transferObjects.OfType <EntityTransferObject>().FirstOrDefault(x => x.Name == controllerConfiguration.Entity) .AssertIsNotNull(nameof(controllerConfiguration.Entity), $"Entity {controllerConfiguration.Entity} not found. Ensure it is read before."); string nameSpace = (controllerConfiguration.Namespace ?? configuration.Namespace).AssertIsNotNull(nameof(configuration.Namespace), "asp writer requires a namespace"); ClassTemplate controller = files.AddFile(configuration.RelativePath, configuration.AddHeader) .AddNamespace(nameSpace) .AddClass(controllerConfiguration.Name ?? entity.Name + "Controller", Code.Type(configuration.Template.ControllerBase)) .FormatName(configuration) .WithAttribute("Route", Code.String(controllerConfiguration.Route ?? "[controller]")); controller.Usings.AddRange(configuration.Template.Usings); TypeTemplate modelType = entity.Model.ToTemplate(); configuration.Usings.ForEach(x => controller.AddUsing(x)); controllerConfiguration.Usings.ForEach(x => controller.AddUsing(x)); FieldTemplate repositoryField = controller.AddField("repository", Code.Type(entity.Name + "Repository")).Readonly(); controller.AddConstructor().Code.AddLine(Code.This().Field(repositoryField).Assign(Code.New(repositoryField.Type)).Close()); if (controllerConfiguration.Get != null) { controller.AddUsing("System.Linq"); MethodTemplate method = controller.AddMethod("Get", Code.Generic("IEnumerable", modelType)); if (configuration.Template.UseAttributes) { method.WithAttribute("HttpGet", Code.String(controllerConfiguration.Get.Name ?? "[action]")); } DeclareTemplate queryable = Code.Declare(Code.Generic("IQueryable", modelType), "queryable", Code.This().Field(repositoryField).Method("Get")); method.Code.AddLine(queryable); foreach (PropertyTransferObject property in entity.Model.Properties) { ParameterTemplate parameter = method.AddParameter(property.Type.ToTemplate(), property.Name, Code.Local("default")).FormatName(configuration); method.Code.AddLine(Code.If(Code.Local(parameter).NotEquals().Local("default"), x => x.Code.AddLine(Code.Local(queryable).Assign(Code.Local(queryable).Method("Where", Code.Lambda("x", Code.Local("x").Property(property.Name).Equals().Local(parameter)))).Close()))); } method.Code.AddLine(Code.Return(Code.Local(queryable))); } if (controllerConfiguration.Post != null) { MethodTemplate method = controller.AddMethod("Post", Code.Void()); if (configuration.Template.UseAttributes) { method.WithAttribute("HttpPost", Code.String(controllerConfiguration.Post.Name ?? "[action]")); } ParameterTemplate parameter = method.AddParameter(modelType, "entity") .WithAttribute("FromBody"); method.Code.AddLine(Code.This().Field(repositoryField).Method("Add", Code.Local(parameter)).Close()); } if (controllerConfiguration.Patch != null) { MethodTemplate method = controller.AddMethod("Patch", Code.Void()); if (configuration.Template.UseAttributes) { method.WithAttribute("HttpPatch", Code.String(controllerConfiguration.Patch.Name ?? "[action]")); } ParameterTemplate parameter = method.AddParameter(modelType, "entity") .WithAttribute("FromBody"); method.Code.AddLine(Code.This().Field(repositoryField).Method("Update", Code.Local(parameter)).Close()); } if (controllerConfiguration.Put != null) { MethodTemplate method = controller.AddMethod("Put", Code.Void()); if (configuration.Template.UseAttributes) { method.WithAttribute("HttpPut", Code.String(controllerConfiguration.Put.Name ?? "[action]")); } ParameterTemplate parameter = method.AddParameter(modelType, "entity") .WithAttribute("FromBody"); method.Code.AddLine(Code.This().Field(repositoryField).Method("Update", Code.Local(parameter)).Close()); } if (controllerConfiguration.Delete != null) { MethodTemplate method = controller.AddMethod("Delete", Code.Void()); if (configuration.Template.UseAttributes) { method.WithAttribute("HttpDelete", Code.String(controllerConfiguration.Delete.Name ?? "[action]")); } List <ParameterTemplate> parameters = new List <ParameterTemplate>(); foreach (EntityKeyTransferObject key in entity.Keys) { PropertyTransferObject property = entity.Model.Properties.First(x => x.Name.Equals(key.Name, StringComparison.InvariantCultureIgnoreCase)); parameters.Add(method.AddParameter(property.Type.ToTemplate(), property.Name) .FormatName(configuration)); } method.Code.AddLine(Code.This().Field(repositoryField).Method("Delete", parameters.Select(x => Code.Local(x))).Close()); } } }
private void GenerateDbInputModel() { var dt = _dbTable; var nameText = RepositoryNamespace ?? "Aescr.Model"; for (int index = 0; index < dt.Rows.Count;) { DataRow dataRow = dt.Rows[index]; var inputFile = CreateFile(); inputFile.DownloadPath = DownloadPath + "/InputModel"; var viewFile = CreateFile(); viewFile.DownloadPath = DownloadPath + "/ViewModel"; var updateFile = CreateFile(); updateFile.DownloadPath = DownloadPath + "/InputModel"; var namespaceTemplate = inputFile.CreateNamespace(); namespaceTemplate.NamespaceName = nameText; var viewTemplate = namespaceTemplate.DeepClone(); viewFile.AddNamespace(viewTemplate); var updateTemplate = namespaceTemplate.DeepClone(); updateFile.AddNamespace(updateTemplate); ClassTemplate classTemplate = new ClassTemplate(); classTemplate.ClassName = dataRow["表名"].ToString(); classTemplate.ClassName = classTemplate.ClassName.Replace("_", ""); classTemplate.RealName = dataRow["表名"].ToString(); classTemplate.Comment = new Code.Template.CommentTemplate(); classTemplate.Comment.CommentName = dataRow["表说明"].ToString(); do { DataRow tempRow = dt.Rows[index]; var field = new Code.Template.FieldTemplate(); var comment = new Code.Template.CommentTemplate(); field.FieldName = tempRow["字段名"].ToString(); comment.CommentName = tempRow["字段说明"].ToString(); field.DbType = tempRow["类型"].ToString(); field.MaxLength = tempRow["长度"].ToString().ToInt64(); field.MinLength = 0; field.Comment = comment; field.IsProperty = true; field.IsKey = tempRow["主键"].ToString() == "√"; field.CanNull = tempRow["允许空"].ToString() == "√"; if (_dbGenerate.DbType == DataBaseType.MsSQL) { field.FieldTypeName = DbToCsharpType.MsSqlToCsharpType(tempRow["类型"].ToString()); } else if (_dbGenerate.DbType == DataBaseType.MySQL) { field.FieldTypeName = DbToCsharpType.MySqlToCsharpType(tempRow["类型"].ToString()); } if (field.CanNull == false) { classTemplate.AddField(field); var inputClass = classTemplate.DeepClone(); var viewClass = classTemplate.DeepClone(); var updateClass = classTemplate.DeepClone(); inputClass.ClassName = "Input" + inputClass.ClassName; namespaceTemplate.AddClass(inputClass); viewClass.ClassName = "View" + viewClass.ClassName; viewTemplate.AddClass(viewClass); updateClass.ClassName = "Update" + updateClass.ClassName; updateTemplate.AddClass(updateClass); } index++; if (index == dt.Rows.Count) { break; } } while (string.IsNullOrWhiteSpace(dt.Rows[index]["表名"].ToString())); } }
public virtual void Write(AngularWriteConfiguration configuration, List <ITransferObject> transferObjects, List <FileTemplate> files) { Logger.Trace("Generate angular service for ASP.net controller..."); if (!configuration.Language.IsTypeScript()) { throw new InvalidOperationException($"Can not generate service for ASP.net Controller for language {configuration.Language?.Name ?? "Empty"}"); } string httpClient = configuration.Service.HttpClient?.Name ?? "HttpClient"; string httpClientImport = configuration.Service.HttpClient?.Import ?? "@angular/common/http"; foreach (HttpServiceTransferObject controller in transferObjects.OfType <HttpServiceTransferObject>()) { Dictionary <HttpServiceActionParameterTransferObject, ParameterTemplate> mapping = new Dictionary <HttpServiceActionParameterTransferObject, ParameterTemplate>(); string controllerName = controller.Name.TrimEnd("Controller"); ClassTemplate classTemplate = files.AddFile(configuration.Service.RelativePath, configuration.AddHeader) .AddNamespace(string.Empty) .AddClass(configuration.Service.Name ?? controllerName + "Service") .FormatName(configuration) .WithUsing(httpClient, httpClientImport) .WithUsing("Injectable", "@angular/core") .WithUsing("Observable", "rxjs") .WithUsing("Subject", "rxjs") .WithAttribute("Injectable", Code.AnonymousObject().WithProperty("providedIn", Code.String("root"))); FieldTemplate httpField = classTemplate.AddField("http", Code.Type(httpClient)).Readonly().FormatName(configuration); FieldTemplate serviceUrlField = classTemplate.AddField("serviceUrl", Code.Type("string")).Public().FormatName(configuration).Default(Code.String(string.Empty)); classTemplate.AddConstructor().WithParameter(Code.Type(httpClient), "http") .WithCode(Code.This().Field(httpField).Assign(Code.Local("http")).Close()); string relativeModelPath = FileSystem.RelativeTo(configuration.Model?.RelativePath ?? ".", configuration.Service.RelativePath); foreach (HttpServiceActionTransferObject action in controller.Actions) { ICodeFragment errorCode = Code.Lambda("error", Code.Local("subject").Method("error", Code.Local("error"))); this.MapType(controller.Language, configuration.Language, action.ReturnType); TypeTemplate returnType = action.ReturnType.ToTemplate(); this.AddUsing(action.ReturnType, classTemplate, configuration, relativeModelPath); MethodTemplate methodTemplate = classTemplate.AddMethod(action.Name, Code.Generic("Observable", returnType)) .FormatName(configuration); foreach (HttpServiceActionParameterTransferObject parameter in action.Parameters) { this.MapType(controller.Language, configuration.Language, parameter.Type); this.AddUsing(parameter.Type, classTemplate, configuration, relativeModelPath); ParameterTemplate parameterTemplate = methodTemplate.AddParameter(parameter.Type.ToTemplate(), parameter.Name).FormatName(configuration); mapping.Add(parameter, parameterTemplate); } methodTemplate.AddParameter(Code.Type("{}"), "httpOptions?"); TypeTemplate subjectType = Code.Generic("Subject", returnType); methodTemplate.WithCode(Code.Declare(subjectType, "subject", Code.New(subjectType))); string uri = ("/" + (controller.Route?.Replace("[controller]", controllerName.ToLower()).TrimEnd('/') ?? controllerName) + "/" + action.Route?.Replace("[action]", action.Name.ToLower())).TrimEnd('/'); List <HttpServiceActionParameterTransferObject> inlineParameters = action.Parameters.Where(x => !x.FromBody && x.Inline).OrderBy(x => x.InlineIndex).ToList(); List <HttpServiceActionParameterTransferObject> urlParameters = action.Parameters.Where(x => !x.FromBody && !x.Inline && x.AppendName).ToList(); List <HttpServiceActionParameterTransferObject> urlDirectParameters = action.Parameters.Where(x => !x.FromBody && !x.Inline && !x.AppendName).ToList(); uri = urlParameters.Count > 0 ? $"{uri}?{urlParameters.First().Name}=" : urlDirectParameters.Count > 0 ? $"{uri}?" : uri; MultilineCodeFragment code = Code.Multiline(); DeclareTemplate declareTemplate = null; bool hasReturnType = returnType.Name != "void"; bool isPrimitive = this.IsPrimitive(returnType); if (returnType.Name == "Array") { TypeTemplate type = ((GenericTypeTemplate)returnType).Types[0]; declareTemplate = Code.Declare(returnType, "list", Code.TypeScript("[]")).Constant(); code.AddLine(declareTemplate) .AddLine(Code.TypeScript("for (const entry of <[]>result)").StartBlock()) .AddLine(Code.Local(declareTemplate).Method("push", isPrimitive ? (ICodeFragment)Code.Cast(type, Code.Local("entry")) : Code.New(type, Code.Local("entry"))).Close()) .AddLine(Code.TypeScript("").EndBlock()); } else if (hasReturnType) { declareTemplate = Code.Declare(returnType, "model", isPrimitive ? (ICodeFragment)Code.Cast(returnType, Code.Local("result")) : Code.New(returnType, Code.Local("result"))).Constant(); code.AddLine(declareTemplate); } code.AddLine(Code.Local("subject").Method("next").WithParameter(declareTemplate.ToLocal()).Close()) .AddLine(Code.Local("subject").Method("complete").Close()); ChainedCodeFragment parameterUrl = Code.This().Field(serviceUrlField); if (inlineParameters.Count == 0) { parameterUrl = parameterUrl.Append(Code.String(uri)); } foreach (HttpServiceActionParameterTransferObject parameter in inlineParameters) { string[] chunks = uri.Split(new [] { $"{{{parameter.Name}}}" }, StringSplitOptions.RemoveEmptyEntries); parameterUrl = parameterUrl.Append(Code.String(chunks[0])).Append(Code.Local(parameter.Name)); uri = chunks.Length == 1 ? string.Empty : chunks[1]; } bool isFirst = true; foreach (HttpServiceActionParameterTransferObject parameter in urlDirectParameters) { if (isFirst) { isFirst = false; parameterUrl = parameterUrl.Append(Code.Local(parameter.Name)); } else { parameterUrl = parameterUrl.Append(Code.String("&")).Append(Code.Local(parameter.Name)); } } foreach (HttpServiceActionParameterTransferObject parameter in urlParameters) { if (isFirst) { isFirst = false; parameterUrl = parameterUrl.Append(Code.Local(mapping[parameter])); } else { parameterUrl = parameterUrl.Append(Code.String($"&{parameter.Name}=")).Append(Code.Local(mapping[parameter])); } } methodTemplate.WithCode( Code.This() .Field(httpField) .Method(action.Type.ToString().ToLowerInvariant(), parameterUrl, action.RequireBodyParameter ? Code.Local(action.Parameters.Single(x => x.FromBody).Name) : null, Code.Local("httpOptions") ) .Method("subscribe", Code.Lambda(hasReturnType ? "result" : null, code), errorCode).Close() ); methodTemplate.WithCode(Code.Return(Code.Local("subject"))); } } }
private void GenerateDbContext() { var ft = CreateFile(); ft.DownloadPath = DownloadPath + "/DbContext"; var namespaceTemplate = ft.CreateNamespace(); namespaceTemplate.NamespaceName = "Microsoft.EntityFrameworkCore"; var classTemplate = new ClassTemplate(); namespaceTemplate.AddClass(classTemplate); classTemplate.ClassName = _connect.Database.Trim() + "DbContext"; classTemplate.BaseClass = new ClassTemplate() { ClassName = "DbContext" }; var method = new MethodTemplate(); classTemplate.AddMethod(method); method.Overwrite = true; method.MethodName = "OnModelCreating"; method.Parameters.Add(new ParameterTemplate() { ParameterTypeName = "ModelBuilder", ParameterName = "modelBuilder" }); var dt = GetTableFlat(); for (int index = 0; index < dt.Rows.Count;) { DataRow dataRow = dt.Rows[index]; ClassTemplate tableTemplate = new ClassTemplate(); if (RemoveLine) { tableTemplate.ClassName = dataRow["表名"].ToString(); tableTemplate.ClassName = classTemplate.ClassName.Replace("_", ""); } else { tableTemplate.ClassName = dataRow["表名"].ToString(); } tableTemplate.RealName = dataRow["表名"].ToString(); tableTemplate.Comment = new Code.Template.CommentTemplate(); tableTemplate.Comment.CommentName = dataRow["表说明"].ToString(); method.CodeLine.Add($"modelBuilder.Entity<{ tableTemplate.ClassName}>().HasComment(\"{tableTemplate.Comment.CommentName }\");"); var field = new Code.Template.FieldTemplate(); field.IsGenerateAttribute = false; field.FieldName = tableTemplate.ClassName; field.FieldTypeName = $"DbSet<{tableTemplate.ClassName}>"; field.IsProperty = true; classTemplate.AddField(field); do { DataRow tempRow = dt.Rows[index]; method.CodeLine.Add($"modelBuilder.Entity<{ tableTemplate.ClassName }>().Property(b => b.{ tempRow["字段名"].ToString()}).HasComment(\"{ tempRow["字段说明"].ToString()}\");"); index++; if (index == dt.Rows.Count) { break; } } while (string.IsNullOrWhiteSpace(dt.Rows[index]["表名"].ToString())); } }