private static ClassConstructorDefinition GetConstructor(ProjectFeature <AspNetCoreProjectSettings> projectFeature) { var parameters = new List <ParameterDefinition> { new ParameterDefinition(projectFeature.GetInterfaceRepositoryName(), "repository") }; var lines = new List <ILine> { new CodeLine("Repository = repository;") }; var settings = projectFeature.GetAspNetCoreProject().GlobalSelection().Settings; if (settings.UseLogger) { parameters.Add(new ParameterDefinition(string.Format("ILogger<{0}>", projectFeature.GetControllerName()), "logger")); lines.Add(new CodeLine("Logger = logger;")); } return(new ClassConstructorDefinition(AccessModifier.Public, parameters.ToArray()) { Lines = lines }); }
public static IEnumerable <Column> GetUpdateColumns(this ProjectFeature <AspNetCoreProjectSettings> projectFeature, ITable table) { var aspNetCoreProject = projectFeature.GetAspNetCoreProject(); var efCoreProjectSettings = aspNetCoreProject.EntityFrameworkCoreProject.GetSelection(table).Settings; foreach (var column in table.Columns) { if (table.PrimaryKey != null && table.PrimaryKey.Key.Contains(column.Name)) { continue; } if (efCoreProjectSettings.AuditEntity != null && efCoreProjectSettings.AuditEntity.Names.Contains(column.Name)) { continue; } if (!string.IsNullOrEmpty(efCoreProjectSettings.ConcurrencyToken) && string.Compare(efCoreProjectSettings.ConcurrencyToken, column.Name) == 0) { continue; } yield return(column); } }
private static MethodDefinition GetDeleteMethod(ProjectFeature <AspNetCoreProjectSettings> projectFeature, ITable table) { var lines = new List <ILine>(); var aspNetCoreProject = projectFeature.GetAspNetCoreProject(); var selection = aspNetCoreProject.GetSelection(table); if (selection.Settings.UseLogger) { lines.Add(new CodeLine("Logger?.LogDebug(\"'{{0}}' has been invoked\", nameof({0}));", aspNetCoreProject.GetControllerDeleteAsyncMethodName(table))); lines.Add(new CodeLine()); } lines.Add(new CodeLine("var response = new Response();")); lines.Add(new CodeLine()); lines.Add(new CodeLine("try")); lines.Add(new CodeLine("{")); if (table.PrimaryKey.Key.Count == 1) { lines.Add(new CommentLine(1, " Retrieve entity by id")); lines.Add(new CodeLine(1, "var entity = await Repository.{0}(new {1}(id));", aspNetCoreProject.EntityFrameworkCoreProject.GetGetRepositoryMethodName(table), aspNetCoreProject.EntityFrameworkCoreProject.GetEntityName(table))); lines.Add(new CodeLine()); } else if (table.PrimaryKey.Key.Count > 1) { lines.Add(new CodeLine(1, "var key = id.Split('|');")); lines.Add(new CodeLine()); var key = table.GetColumnsFromConstraint(table.PrimaryKey).ToList(); for (var i = 0; i < key.Count; i++) { var column = key[i]; var parameterName = aspNetCoreProject.CodeNamingConvention.GetParameterName(column.Name); if (projectFeature.Project.Database.ColumnIsInt16(column)) { lines.Add(new CodeLine(1, "var {0} = Convert.ToInt16(key[{1}]);", parameterName, (i + 1).ToString())); } else if (projectFeature.Project.Database.ColumnIsInt32(column)) { lines.Add(new CodeLine(1, "var {0} = Convert.ToInt32(key[{1}]);", parameterName, (i + 1).ToString())); } else if (projectFeature.Project.Database.ColumnIsInt64(column)) { lines.Add(new CodeLine(1, "var {0} = Convert.ToInt64(key[{1}]);", parameterName, (i + 1).ToString())); } else { lines.Add(new CodeLine(1, "var {0} = key[{1}];", parameterName, (i + 1).ToString())); } } var exp = string.Join(", ", key.Select(item => string.Format("{0}", aspNetCoreProject.CodeNamingConvention.GetParameterName(item.Name)))); lines.Add(new CommentLine(1, " Retrieve entity")); lines.Add(new CodeLine(1, "var entity = await Repository.{0}(new {1}({2}));", aspNetCoreProject.EntityFrameworkCoreProject.GetGetRepositoryMethodName(table), aspNetCoreProject.EntityFrameworkCoreProject.GetEntityName(table), exp)); lines.Add(new CodeLine()); } lines.Add(new CodeLine(1, "if (entity != null)")); lines.Add(new CodeLine(1, "{")); lines.Add(new CommentLine(2, " Remove entity from database")); lines.Add(new CodeLine(2, "Repository.Remove(entity);")); lines.Add(new CodeLine()); lines.Add(new CodeLine(2, "await Repository.CommitChangesAsync();")); if (selection.Settings.UseLogger) { lines.Add(new CodeLine()); lines.Add(new CodeLine(2, "Logger?.LogInformation(\"The entity was deleted successfully\");")); } lines.Add(new CodeLine(1, "}")); lines.Add(new CodeLine("}")); lines.Add(new CodeLine("catch (Exception ex)")); lines.Add(new CodeLine("{")); if (selection.Settings.UseLogger) { lines.Add(new CodeLine(1, "response.SetError(Logger, nameof({0}), ex);", aspNetCoreProject.GetControllerDeleteAsyncMethodName(table))); } else { lines.Add(new CodeLine(1, "response.DidError = true;")); lines.Add(new CodeLine(1, "response.ErrorMessage = ex.Message;")); } lines.Add(new CodeLine("}")); lines.Add(new CodeLine()); lines.Add(new CodeLine("return response.ToHttpResponse();")); var parameters = new List <ParameterDefinition>(); if (table.PrimaryKey.Key.Count == 1) { var column = table.GetColumnsFromConstraint(table.PrimaryKey).First(); parameters.Add(new ParameterDefinition(projectFeature.Project.Database.ResolveDatabaseType(column), "id")); } else if (table.PrimaryKey.Key.Count > 1) { parameters.Add(new ParameterDefinition("string", "id")); } return(new MethodDefinition("Task<IActionResult>", aspNetCoreProject.GetControllerDeleteAsyncMethodName(table), parameters.ToArray()) { Attributes = { new MetadataAttribute("HttpDelete", string.Format("\"{0}/{{id}}\"", aspNetCoreProject.EntityFrameworkCoreProject.GetEntityName(table))), }, AccessModifier = AccessModifier.Public, IsAsync = true, Lines = lines }); }
private static MethodDefinition GetPostMethod(ProjectFeature <AspNetCoreProjectSettings> projectFeature, ITable table) { var lines = new List <ILine>(); var aspNetCoreProject = projectFeature.GetAspNetCoreProject(); var selection = aspNetCoreProject.GetSelection(table); if (selection.Settings.UseLogger) { lines.Add(new CodeLine("Logger?.LogDebug(\"'{{0}}' has been invoked\", nameof({0}));", aspNetCoreProject.GetControllerPostAsyncMethodName(table))); lines.Add(new CodeLine()); } lines.Add(new CommentLine(" Validate request model")); lines.Add(new CodeLine("if (!ModelState.IsValid)")); lines.Add(new CodeLine(1, "return BadRequest(request);")); lines.Add(new CodeLine()); lines.Add(new CodeLine("var response = new SingleResponse<{0}>();", aspNetCoreProject.GetRequestName(table))); lines.Add(new CodeLine()); lines.Add(new CodeLine("try")); lines.Add(new CodeLine("{")); lines.Add(new CodeLine(1, "var entity = request.ToEntity();", aspNetCoreProject.EntityFrameworkCoreProject.GetAddRepositoryMethodName(table))); lines.Add(new CodeLine()); foreach (var unique in table.Uniques) { lines.Add(new CommentLine(1, " Check if entity exists")); lines.Add(new CodeLine(1, "if ((await Repository.{0}(entity)) != null)", aspNetCoreProject.EntityFrameworkCoreProject.GetGetByUniqueRepositoryMethodName(table, unique))); lines.Add(new CodeLine(1, "{")); lines.Add(new CodeLine(2, "return BadRequest();")); lines.Add(new CodeLine(1, "}")); lines.Add(new CodeLine()); } lines.Add(new CommentLine(1, " Add entity to database")); lines.Add(new CodeLine(1, "Repository.Add(entity);")); lines.Add(new CodeLine()); lines.Add(new CodeLine(1, "await Repository.CommitChangesAsync();")); lines.Add(new CodeLine()); lines.Add(new CodeLine(1, "response.Model = entity.ToRequest();")); if (selection.Settings.UseLogger) { lines.Add(new CodeLine()); lines.Add(new CodeLine(1, "Logger?.LogInformation(\"The entity was created successfully\");")); } lines.Add(new CodeLine("}")); lines.Add(new CodeLine("catch (Exception ex)")); lines.Add(new CodeLine("{")); if (selection.Settings.UseLogger) { lines.Add(new CodeLine(1, "response.SetError(Logger, nameof({0}), ex);", aspNetCoreProject.GetControllerPostAsyncMethodName(table))); } else { lines.Add(new CodeLine(1, "response.DidError = true;")); lines.Add(new CodeLine(1, "response.ErrorMessage = ex.Message;")); } lines.Add(new CodeLine("}")); lines.Add(new CodeLine()); lines.Add(new CodeLine("return response.ToHttpResponse();")); return(new MethodDefinition("Task<IActionResult>", aspNetCoreProject.GetControllerPostAsyncMethodName(table), new ParameterDefinition(aspNetCoreProject.GetRequestName(table), "request", new MetadataAttribute("FromBody"))) { Attributes = { new MetadataAttribute("HttpPost", string.Format("\"{0}\"", aspNetCoreProject.EntityFrameworkCoreProject.GetEntityName(table))), }, AccessModifier = AccessModifier.Public, IsAsync = true, Lines = lines }); }
public static ControllerClassDefinition GetControllerClassDefinition(this ProjectFeature <AspNetCoreProjectSettings> projectFeature) { var aspNetCoreProject = projectFeature.GetAspNetCoreProject(); var definition = new ControllerClassDefinition { Namespaces = { "System", "System.Linq", "System.Threading.Tasks", "Microsoft.AspNetCore.Mvc", "Microsoft.EntityFrameworkCore", "Microsoft.Extensions.Logging", aspNetCoreProject.GetDataLayerContractsNamespace(), aspNetCoreProject.GetDataLayerRepositoriesNamespace(), aspNetCoreProject.GetResponsesNamespace(), aspNetCoreProject.GetRequestsNamespace() }, Namespace = string.Format("{0}.{1}", aspNetCoreProject.Name, "Controllers"), AccessModifier = AccessModifier.Public, Name = projectFeature.GetControllerName(), Attributes = new List <MetadataAttribute> { new MetadataAttribute("Route", string.IsNullOrEmpty(aspNetCoreProject.Version) ? "\"api/[controller]\"" : string.Format("\"api/{0}/[controller]\"", aspNetCoreProject.Version)), new MetadataAttribute("ApiController") }, BaseClass = "ControllerBase", Fields = { new FieldDefinition(AccessModifier.Protected, projectFeature.GetInterfaceRepositoryName(), "Repository") { IsReadOnly = true } } }; var settings = aspNetCoreProject.GlobalSelection().Settings; if (settings.UseLogger) { definition.Fields.Add(new FieldDefinition(AccessModifier.Protected, "ILogger", "Logger")); } definition.Constructors.Add(GetConstructor(projectFeature)); var dbos = projectFeature.DbObjects.Select(dbo => dbo.FullName).ToList(); var tables = projectFeature.Project.Database.Tables.Where(t => dbos.Contains(t.FullName)).ToList(); foreach (var table in tables) { if (table.Columns.Count == table.PrimaryKey?.Key.Count) { continue; } definition.Methods.Add(GetGetAllMethod(projectFeature, definition, table)); if (table.PrimaryKey != null) { definition.Methods.Add(GetGetMethod(projectFeature, table)); } definition.Methods.Add(GetPostMethod(projectFeature, table)); if (table.PrimaryKey != null) { definition.Methods.Add(GetPutMethod(projectFeature, table)); definition.Methods.Add(GetDeleteMethod(projectFeature, table)); } } // todo: Add views in controller definition.SimplifyDataTypes(); return(definition); }
private static MethodDefinition GetGetAllMethod(ProjectFeature <AspNetCoreProjectSettings> projectFeature, CSharpClassDefinition definition, ITable table) { if (projectFeature.Project.Database.HasDefaultSchema(table)) { definition.Namespaces.AddUnique(projectFeature.GetAspNetCoreProject().GetEntityLayerNamespace()); } else { definition.Namespaces.AddUnique(projectFeature.GetAspNetCoreProject().GetEntityLayerNamespace(table.Schema)); } var lines = new List <ILine>(); var aspNetCoreProject = projectFeature.GetAspNetCoreProject(); var aspNetCoreSelection = aspNetCoreProject.GetSelection(table); var efCoreProject = aspNetCoreProject.EntityFrameworkCoreProject; var efCoreSelection = efCoreProject.GetSelection(table); if (aspNetCoreSelection.Settings.UseLogger) { lines.Add(new CodeLine("Logger?.LogDebug(\"'{{0}}' has been invoked\", nameof({0}));", aspNetCoreProject.GetControllerGetAllAsyncMethodName(table))); lines.Add(new CodeLine()); } if (efCoreSelection.Settings.EntitiesWithDataContracts) { definition.Namespaces.AddUnique(projectFeature.GetAspNetCoreProject().GetDataLayerDataContractsNamespace()); lines.Add(new CodeLine("var response = new PagedResponse<{0}>();", aspNetCoreProject.EntityFrameworkCoreProject.GetDataContractName(table))); } else { lines.Add(new CodeLine("var response = new PagedResponse<{0}>();", aspNetCoreProject.EntityFrameworkCoreProject.GetEntityName(table))); } lines.Add(new CodeLine()); lines.Add(new CodeLine("try")); lines.Add(new CodeLine("{")); var parameters = new List <ParameterDefinition> { new ParameterDefinition("int?", "pageSize", "10"), new ParameterDefinition("int?", "pageNumber", "1") }; var foreignKeys = new List <string>(); foreach (var foreignKey in table.ForeignKeys) { var parentTable = projectFeature.Project.Database.FindTable(foreignKey.References); if (parentTable == null) { continue; } if (parentTable.PrimaryKey?.Key.Count == 1) { var column = parentTable.GetColumnsFromConstraint(parentTable.PrimaryKey).First(); parameters.Add(new ParameterDefinition(projectFeature.Project.Database.ResolveDatabaseType(column), aspNetCoreProject.CodeNamingConvention.GetParameterName(column.Name), "null")); foreignKeys.Add(aspNetCoreProject.CodeNamingConvention.GetParameterName(column.Name)); } else { // todo: add logic for multiple columns in key } } lines.Add(new CommentLine(1, " Get query from repository")); if (foreignKeys.Count == 0) { lines.Add(new CodeLine(1, "var query = Repository.{0}();", aspNetCoreProject.EntityFrameworkCoreProject.GetGetAllRepositoryMethodName(table))); } else { lines.Add(new CodeLine(1, "var query = Repository.{0}({1});", aspNetCoreProject.EntityFrameworkCoreProject.GetGetAllRepositoryMethodName(table), string.Join(", ", foreignKeys))); } lines.Add(new CodeLine()); if (aspNetCoreSelection.Settings.UseLogger) { lines.Add(new CommentLine(1, " Set paging's information")); lines.Add(new CodeLine(1, "response.PageSize = (int)pageSize;")); lines.Add(new CodeLine(1, "response.PageNumber = (int)pageNumber;")); lines.Add(new CodeLine(1, "response.ItemsCount = await query.CountAsync();")); lines.Add(new CodeLine()); lines.Add(new CommentLine(1, " Retrieve items by page size and page number, set model for response")); lines.Add(new CodeLine(1, "response.Model = await query.Paging(response.PageSize, response.PageNumber).ToListAsync();")); lines.Add(new CodeLine()); lines.Add(new CodeLine(1, "Logger?.LogInformation(\"Page {0} of {1}, Total of rows: {2}.\", response.PageNumber, response.PageCount, response.ItemsCount);")); } lines.Add(new CodeLine("}")); lines.Add(new CodeLine("catch (Exception ex)")); lines.Add(new CodeLine("{")); if (aspNetCoreSelection.Settings.UseLogger) { lines.Add(new CodeLine(1, "response.SetError(Logger, nameof({0}), ex);", aspNetCoreProject.GetControllerGetAllAsyncMethodName(table))); } else { lines.Add(new CodeLine(1, "response.DidError = true;")); lines.Add(new CodeLine(1, "response.ErrorMessage = ex.Message;")); } lines.Add(new CodeLine("}")); lines.Add(new CodeLine()); lines.Add(new CodeLine("return response.ToHttpResponse();")); return(new MethodDefinition("Task<IActionResult>", aspNetCoreProject.GetControllerGetAllAsyncMethodName(table), parameters.ToArray()) { AccessModifier = AccessModifier.Public, Attributes = { new MetadataAttribute("HttpGet", string.Format("\"{0}\"", aspNetCoreProject.EntityFrameworkCoreProject.GetEntityName(table))), }, IsAsync = true, Lines = lines }); }
private static MethodDefinition GetDeleteMethod(ProjectFeature <AspNetCoreProjectSettings> projectFeature, ITable table) { var lines = new List <ILine>(); var selection = projectFeature.GetAspNetCoreProject().GetSelection(table); if (selection.Settings.UseLogger) { lines.Add(new CodeLine("Logger?.LogDebug(\"'{{0}}' has been invoked\", nameof({0}));", table.GetControllerDeleteAsyncMethodName())); lines.Add(new CodeLine()); } lines.Add(new CodeLine("var response = new SingleResponse<{0}>();", table.GetRequestModelName())); lines.Add(new CodeLine()); lines.Add(new CodeLine("try")); lines.Add(new CodeLine("{")); lines.Add(new CommentLine(1, " Retrieve entity by id")); lines.Add(new CodeLine(1, "var entity = await Repository.{0}(new {1}(id));", table.GetGetRepositoryMethodName(), table.GetEntityName())); lines.Add(new CodeLine()); lines.Add(new CodeLine(1, "if (entity != null)")); lines.Add(new CodeLine(1, "{")); lines.Add(new CommentLine(2, " Remove entity from database")); lines.Add(new CodeLine(2, "await Repository.{0}(entity);", table.GetRemoveRepositoryMethodName())); if (selection.Settings.UseLogger) { lines.Add(new CodeLine()); lines.Add(new CodeLine(2, "Logger?.LogInformation(\"The entity was deleted successfully\");")); } lines.Add(new CodeLine()); lines.Add(new CodeLine(2, "response.Model = entity.ToRequestModel();")); lines.Add(new CodeLine(1, "}")); lines.Add(new CodeLine("}")); lines.Add(new CodeLine("catch (Exception ex)")); lines.Add(new CodeLine("{")); if (selection.Settings.UseLogger) { lines.Add(new CodeLine(1, "response.SetError(ex, Logger);")); } else { lines.Add(new CodeLine(1, "response.DidError = true;")); lines.Add(new CodeLine(1, "response.ErrorMessage = ex.Message;")); } lines.Add(new CodeLine("}")); lines.Add(new CodeLine()); lines.Add(new CodeLine("return response.ToHttpResponse();")); var parameters = new List <ParameterDefinition>(); if (table.PrimaryKey?.Key.Count == 1) { var column = table.Columns.FirstOrDefault(item => item.Name == table.PrimaryKey.Key.First()); parameters.Add(new ParameterDefinition(EfCore.DatabaseExtensions.ResolveType(projectFeature.Project.Database, column), "id")); } return(new MethodDefinition("Task<IActionResult>", table.GetControllerDeleteAsyncMethodName(), parameters.ToArray()) { Attributes = new List <MetadataAttribute> { new MetadataAttribute("HttpDelete", string.Format("\"{0}\"", table.GetEntityName())), }, IsAsync = true, Lines = lines }); }
public static CSharpClassDefinition GetControllerClassDefinition(this ProjectFeature <AspNetCoreProjectSettings> projectFeature) { var definition = new CSharpClassDefinition(); definition.Namespaces.Add("System"); definition.Namespaces.Add("System.Linq"); definition.Namespaces.Add("System.Threading.Tasks"); definition.Namespaces.Add("Microsoft.AspNetCore.Mvc"); definition.Namespaces.Add("Microsoft.EntityFrameworkCore"); definition.Namespaces.Add("Microsoft.Extensions.Logging"); var project = projectFeature.GetAspNetCoreProject(); definition.Namespaces.Add(project.GetDataLayerContractsNamespace()); definition.Namespaces.Add(project.GetDataLayerRepositoriesNamespace()); var settings = project.GlobalSelection().Settings; definition.Namespaces.Add(project.GetResponsesNamespace()); definition.Namespaces.Add(project.GetRequestModelsNamespace()); definition.Namespace = string.Format("{0}.{1}", project.Name, "Controllers"); definition.Attributes = new List <MetadataAttribute> { new MetadataAttribute("Route", "\"api/[controller]\"") }; definition.Name = projectFeature.GetControllerName(); definition.BaseClass = "Controller"; definition.Fields.Add(new FieldDefinition(AccessModifier.Protected, projectFeature.GetInterfaceRepositoryName(), "Repository") { IsReadOnly = true }); if (settings.UseLogger) { definition.Fields.Add(new FieldDefinition(AccessModifier.Protected, "ILogger", "Logger")); } definition.Constructors.Add(GetConstructor(projectFeature)); definition.Methods.Add(new MethodDefinition(AccessModifier.Protected, "void", "Dispose", new ParameterDefinition("Boolean", "disposing")) { IsOverride = true, Lines = new List <ILine> { new CodeLine("Repository?.Dispose();"), new CodeLine(), new CodeLine("base.Dispose(disposing);") } }); var dbos = projectFeature.DbObjects.Select(dbo => dbo.FullName).ToList(); var tables = projectFeature.Project.Database.Tables.Where(t => dbos.Contains(t.FullName)).ToList(); foreach (var table in tables) { definition.Methods.Add(GetGetAllMethod(projectFeature, definition, table)); if (table.PrimaryKey != null) { definition.Methods.Add(GetGetMethod(projectFeature, table)); } definition.Methods.Add(GetPostMethod(projectFeature, table)); if (table.PrimaryKey != null) { definition.Methods.Add(GetPutMethod(projectFeature, table)); definition.Methods.Add(GetDeleteMethod(projectFeature, table)); } } return(definition); }