public void Humanize() { foreach (var pair in TestData) { Assert.AreEqual(Inflector.Humanize(pair.Key), pair.Value); } }
internal string GenerateActions(string baseNamespace, string namespacePostfix, string classNamespace, IList <IEntityNavigation> excludeCircularReferenceNavigationProperties, IEntityType entity, bool InludeRelatedObjects, bool prependSchemaNameIndicator) { var sb = new StringBuilder(); string entityName = Inflector.Humanize(entity.ClrType.Name); sb.AppendLine($"using System;"); sb.AppendLine($"using System.Collections.Generic;"); sb.AppendLine($"using System.Text;"); sb.AppendLine($"using Csla; //https://github.com/MarimerLLC/csla"); sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"using {baseNamespace}.DataAccess;" : $"using {baseNamespace}.DataAccess.{namespacePostfix};"); sb.AppendLine($""); sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"namespace {baseNamespace}.Shared" : $"namespace {baseNamespace}.Shared.{namespacePostfix}"); sb.AppendLine($"{{"); sb.AppendLine("\t[Serializable]"); sb.AppendLine($"\tpublic class {entityName}Info : ReadOnlyBase<{entityName}Info>"); sb.AppendLine($"\t{{"); var primaryKeyList = GetPrimaryKeys(entity); var entityProperties = entity.GetProperties(); foreach (var property in entityProperties) { string ctype = GetCType(property); var simpleType = ConvertToSimpleType(ctype); string propertyName = property.Name; sb.AppendLine($"\t public static readonly PropertyInfo<{simpleType}> {propertyName}Property = RegisterProperty<{simpleType}>(nameof({propertyName}));"); sb.AppendLine($"\t public {simpleType} {propertyName}"); sb.AppendLine("\t {"); sb.AppendLine($"\t\t get {{return GetProperty({propertyName}Property);}}"); sb.AppendLine($"\t\t private set {{ LoadProperty({propertyName}Property, value);}}"); sb.AppendLine("\t }"); sb.AppendLine(string.Empty); } //////////////////FETCH CHILD sb.AppendLine("\t [FetchChild]"); sb.AppendLine($"\t private void Fetch({entityName}Entity data)"); sb.AppendLine("\t {"); foreach (var property in entityProperties) { string ctype = GetCType(property); var simpleType = ConvertToSimpleType(ctype); string propertyName = property.Name; sb.AppendLine($"\t\t {propertyName} = data.{propertyName};"); } sb.AppendLine("\t }"); sb.AppendLine(string.Empty); sb.AppendLine($"\t}}"); sb.AppendLine($"}}"); return(sb.ToString()); }
internal string GenerateInterface(string baseNamespace, string namespacePostfix, string classNamespace, bool InludeRelatedObjects, bool prependSchemaNameIndicator, IList <IEntityNavigation> excludeCircularReferenceNavigationProperties, IEntityType entity) { var sb = new StringBuilder(); string entityName = Inflector.Pascalize(Inflector.Humanize(entity.ClrType.Name)); sb.AppendLine($"using System;"); sb.AppendLine($"using System.Collections.Generic;"); sb.AppendLine($"using System.Text;"); sb.AppendLine($"using System.Threading.Tasks;"); sb.AppendLine(string.Empty); sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"namespace {baseNamespace}.DataAccess" : $"namespace {baseNamespace}.DataAccess.{namespacePostfix}"); sb.AppendLine($"{{"); sb.AppendLine($"\tpublic partial interface I{entityName}Dal"); sb.AppendLine($"\t{{"); //////////// // DELETE //////////// sb.AppendLine($"\t bool Delete({GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())});"); sb.AppendLine(string.Empty); //////////// // EXISTS //////////// sb.AppendLine($"\t bool Exists({GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())});"); sb.AppendLine(string.Empty); //////////// // SINGLE GET //////////// sb.AppendLine($"\t {entityName}Entity Get({GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())});"); sb.AppendLine(string.Empty); //////////// // List GET //////////// sb.AppendLine($"\t List<{entityName}Entity> Get();"); sb.AppendLine(string.Empty); //////////// // INSERT //////////// sb.AppendLine($"\t {entityName}Entity Insert({entityName}Entity {Inflector.ToLowerFirstCharacter(entityName)});"); sb.AppendLine(string.Empty); //////////// // UPDATE //////////// sb.AppendLine($"\t {entityName}Entity Update({entityName}Entity {Inflector.ToLowerFirstCharacter(entityName)});"); sb.AppendLine(string.Empty); sb.AppendLine(string.Empty); sb.AppendLine($"\t}}"); sb.AppendLine($"}}"); return(sb.ToString()); }
/// <summary> /// Initializes a new instance of the <see cref="SilverNeedle.Characters.WeaponProficiency"/> class. /// </summary> /// <param name="proficiency">Proficiency weapon to add</param> public WeaponProficiency(string proficiency) { this.Name = Inflector.Humanize(proficiency); this.isLevel = EnumHelpers.TryParse <WeaponTrainingLevel>(proficiency, true, out this.trainingLevel); // Append a descriptive string so we know this is a group of weapons if (this.isLevel) { this.Name += " weapons"; } }
public override TemplateOutput Generate() { TemplateOutput retVal = new TemplateOutput(); try { foreach (var entity in ProcessModel.MetadataSourceModel.EntityTypes) { string outputfile = TemplateVariablesManager.GetOutputFile(templateIdentity: ProcessModel.TemplateIdentity, fileName: Consts.OUT_webApiControllerPartialMethods); outputfile = outputfile.Replace("[tablename]", Inflector.Humanize(entity.ClrType.Name)).Replace("[tablepluralname]", Inflector.Pluralize(entity.ClrType.Name)); string filepath = outputfile; string baseControllerName = $"{NamespacePostfix}BaseApiController"; if (UseAuthorizedBaseController) //!string.IsNullOrEmpty(UseAuthorizedBaseController) && UseAuthorizedBaseController.ToLowerInvariant() == "true") { baseControllerName = $"{NamespacePostfix}BaseApiControllerAuthorized"; } var generator = new WebApiControllerPartialMethodsGenerator(inflector: Inflector); string generatedCode = generator.GenerateWebApiControllerPartialMethods( namespacePostfix: NamespacePostfix, classNamespace: WebApiControllerNamespace, baseControllerName: baseControllerName, efEntityNamespacePrefix: $"ent{NamespacePostfix}", efEntityNamespace: RepositoryEntitiesNamespace, dbContextName: DbContextName, entity: entity, excludedNavigationProperties: ProcessModel.ExcludedNavigationProperties, allowUpsertDuringPut: AllowUpsertDuringPut ); retVal.Files.Add(new OutputFile() { Content = generatedCode, Name = filepath }); } } catch (Exception ex) { base.AddError(ref retVal, ex, Enums.LogLevel.Error); } AddTemplateVariablesManagerErrorsToRetVal(ref retVal, Enums.LogLevel.Error); return(retVal); }
public override TemplateOutput Generate() { TemplateOutput retVal = new TemplateOutput(); try { foreach (var entity in ProcessModel.MetadataSourceModel.EntityTypes) { string entityName = Inflector.Humanize(entity.ClrType.Name); string generatedCode; string outputfile = TemplateVariablesManager.GetOutputFile(templateIdentity: ProcessModel.TemplateIdentity, fileName: Consts.OUT_Blazor_CSLA_Razor_Edit); outputfile = outputfile.Replace("[entityname]", $"{entityName}"); string filepath = outputfile; if (UseBootstrap) { var generator = new CSLAEditRazorGeneratorBootstrap(inflector: Inflector); generatedCode = generator.GenerateRazor(baseNamespace: BaseNamespace, namespacePostfix: NamespacePostfix, entity: entity, AuthorizeRoles: AuthorizeRoles); } else { var generator = new CSLAEditRazorGenerator(inflector: Inflector); generatedCode = generator.GenerateRazor(baseNamespace: BaseNamespace, namespacePostfix: NamespacePostfix, entity: entity, AuthorizeRoles: AuthorizeRoles); } retVal.Files.Add(new OutputFile() { Content = generatedCode, Name = filepath }); } } catch (Exception ex) { base.AddError(ref retVal, ex, Enums.LogLevel.Error); } AddTemplateVariablesManagerErrorsToRetVal(ref retVal, Enums.LogLevel.Error); return(retVal); }
public override TemplateOutput Generate() { TemplateOutput retVal = new TemplateOutput(); try { if (retVal.Errors.Count > 0) { return(retVal); } var entityTypes = ProcessModel.MetadataSourceModel.GetEntityTypesByRegEx(excludeRegExPattern: RegexExclude, includeRegExPattern: RegexInclude); foreach (var entity in entityTypes) { // Determine the navigation properties that should be excluded due to the RegEx patterns. var excludedNavigationProperties = GetExcludedNavigationProperties(entity, entityTypes, ProcessModel.ExcludedNavigationProperties); string outputfile = TemplateVariablesManager.GetOutputFile(templateIdentity: ProcessModel.TemplateIdentity, fileName: Consts.OUT_mvvmLightModelObject); string entityName = Inflector.Humanize(entity.ClrType.Name); outputfile = outputfile.Replace("[tablename]", entityName); string filepath = outputfile; var generator = new MvvmLightModelObjectGenerator(inflector: Inflector); string generatedCode = generator.GenerateMvvmLightModelObject( classNamespace: SqliteModelObjectNamespace, baseAuditEditNamespace: SqliteModelObjectBaseAuditEditNamespace, prependSchemaNameIndicator: PrependSchemaNameIndicator, entity: entity, excludedNavigationProperties: excludedNavigationProperties); retVal.Files.Add(new OutputFile() { Content = generatedCode, Name = filepath }); } } catch (Exception ex) { base.AddError(ref retVal, ex, Enums.LogLevel.Error); } AddTemplateVariablesManagerErrorsToRetVal(ref retVal, Enums.LogLevel.Error); return(retVal); }
// [TemplateVariable(Consts.STG_sqliteModelObjectBaseAuditEditNamespace_DEFAULTVALUE)] // public string SqliteModelObjectBaseAuditEditNamespace { get; set; } #endregion TemplateVariables public override TemplateOutput Generate() { TemplateOutput retVal = new TemplateOutput(); try { foreach (var entity in ProcessModel.MetadataSourceModel.EntityTypes) { string entityName = Inflector.Humanize(entity.ClrType.Name); string outputfile = TemplateVariablesManager.GetOutputFile(templateIdentity: ProcessModel.TemplateIdentity, fileName: Consts.OUT_ModelsBackedByDto); //outputfile = outputfile.Replace("[tablename]", table.NameHumanCaseSingular).Replace("[tablepluralname]", table.NamePlural); outputfile = outputfile.Replace("[tablename]", entityName).Replace("[tablepluralname]", entityName); string filepath = outputfile; var generator = new ModelsBackedByDtoGenerator(inflector: Inflector); string generatedCode = generator.GenerateModelsBackedByDto( baseNamespace: BaseNamespace, namespacePostfix: NamespacePostfix, classNamespace: ClassNameSpace, prependSchemaNameIndicator: PrependSchemaNameIndicator, modelsBackedByDtoInterfaceNamespace: ModelsBackedByDtoInterfaceNamespace, webApiDataServiceInterfaceNamespace: WebApiDataServiceInterfaceNamespace, webApiDataServiceInterfaceClassName: WebApiDataServiceInterfaceClassName, excludedNavigationProperties: ProcessModel.ExcludedNavigationProperties, entity: entity ); retVal.Files.Add(new OutputFile() { Content = generatedCode, Name = filepath }); } } catch (Exception ex) { base.AddError(ref retVal, ex, Enums.LogLevel.Error); } //AddTemplateVariablesManagerErrorsToRetVal(ref retVal); AddTemplateVariablesManagerErrorsToRetVal(ref retVal, Enums.LogLevel.Error); return(retVal); }
internal string GenerateEntity(string baseNamespace, string namespacePostfix, string classNamespace, IList <IEntityNavigation> excludeCircularReferenceNavigationProperties, IEntityType entity, bool InludeRelatedObjects, bool prependSchemaNameIndicator) { var sb = new StringBuilder(); string entityName = Inflector.Humanize(entity.ClrType.Name); sb.AppendLine($"using System;"); sb.AppendLine($"using System.Collections.Generic;"); sb.AppendLine($"using System.Text;"); sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"namespace {baseNamespace}.DataAccess" : $"namespace {baseNamespace}.DataAccess.{namespacePostfix}"); sb.AppendLine($"{{"); sb.AppendLine($"\tpublic partial class {entityName}Entity"); sb.AppendLine($"\t{{"); var primaryKeyList = GetPrimaryKeys(entity); var entityProperties = entity.GetProperties(); foreach (var property in entityProperties) { string ctype = GetCType(property); string propertyName = property.Name; bool isPrimaryKey = primaryKeyList.Any(x => x.Equals(property.Name)); sb.Append($"\t\tpublic {ctype} {Inflector.Pascalize(propertyName)} {{ get; set; }}"); if (isPrimaryKey) { sb.AppendLine($" // Primary key"); } else { sb.AppendLine(string.Empty); } } sb.AppendLine(string.Empty); sb.AppendLine($"\t}}"); sb.AppendLine($"}}"); return(sb.ToString()); }
public override TemplateOutput Generate() { TemplateOutput retVal = new TemplateOutput(); try { var entityTypes = ProcessModel.MetadataSourceModel.GetEntityTypesByRegEx(excludeRegExPattern: RegexExclude, includeRegExPattern: RegexInclude); foreach (var entity in entityTypes) { string entityName = Inflector.Humanize(entity.ClrType.Name); string outputfile = TemplateVariablesManager.GetOutputFile(templateIdentity: ProcessModel.TemplateIdentity, fileName: Consts.OUT_dto); outputfile = outputfile.Replace("[tablename]", entityName).Replace("[tablepluralname]", Inflector.Pluralize(entityName)); string filepath = outputfile; var generator = new DTOSimpleGenerator(inflector: Inflector); string generatedCode = generator.GenerateDTO( excludedNavigationProperties: ProcessModel.ExcludedNavigationProperties, entity: entity, namespacePostfix: NamespacePostfix, baseNamespace: BaseNamespace, dtoIncludeRelatedObjects: DTOIncludeRelatedObjects, prependSchemaNameIndicator: PrependSchemaNameIndicator, dtoNamespace: DTONamespace ); retVal.Files.Add(new OutputFile() { Content = generatedCode, Name = filepath }); } AddTemplateVariablesManagerErrorsToRetVal(ref retVal, Enums.LogLevel.Error); } catch (Exception ex) { base.AddError(ref retVal, ex, Enums.LogLevel.Error); } return(retVal); }
public override TemplateOutput Generate() { TemplateOutput retVal = new TemplateOutput(); try { foreach (var entity in ProcessModel.MetadataSourceModel.EntityTypes) { string entityName = Inflector.Humanize(entity.ClrType.Name); string outputfile = TemplateVariablesManager.GetOutputFile(templateIdentity: ProcessModel.TemplateIdentity, fileName: Consts.OUT_Blazor_CSLA_EditBusiness); outputfile = outputfile.Replace("[entityname]", $"{entityName}"); string filepath = outputfile; var generator = new CSLAEditBusinessGenerator(inflector: Inflector); string generatedCode = generator.GenerateActions( baseNamespace: BaseNamespace, namespacePostfix: NamespacePostfix, classNamespace: ClassNameSpace, InludeRelatedObjects: DataAccessIncludeRelatedObjects, prependSchemaNameIndicator: PrependSchemaNameIndicator, excludeCircularReferenceNavigationProperties: ProcessModel.ExcludedNavigationProperties, entity: entity ); retVal.Files.Add(new OutputFile() { Content = generatedCode, Name = filepath }); } } catch (Exception ex) { base.AddError(ref retVal, ex, Enums.LogLevel.Error); } AddTemplateVariablesManagerErrorsToRetVal(ref retVal, Enums.LogLevel.Error); return(retVal); }
public override TemplateOutput Generate() { TemplateOutput retVal = new TemplateOutput(); try { foreach (var entity in ProcessModel.MetadataSourceModel.EntityTypes) { string entityName = Inflector.Humanize(entity.ClrType.Name); string outputfile = TemplateVariablesManager.GetOutputFile(templateIdentity: ProcessModel.TemplateIdentity, fileName: Consts.OUT_DataAccessEF); outputfile = outputfile.Replace("[entityname]", entityName).Replace("[tablename]", entityName).Replace("[entitynamepluralname]", entityName).Replace("[tablenamepluralname]", entityName); string filepath = outputfile; string useNamespace = TemplateVariablesManager.GetValue(Consts.STG_dataAccessEFNamespace); var generator = new DataAccessEFGenerator(inflector: Inflector); string generatedCode = generator.GenerateDataAccessEF( entity: entity, useNamespace: useNamespace, dbContextName: DBContextName ); retVal.Files.Add(new OutputFile() { Content = generatedCode, Name = filepath }); } AddTemplateVariablesManagerErrorsToRetVal(ref retVal, Enums.LogLevel.Error); } catch (Exception ex) { base.AddError(ref retVal, ex, Enums.LogLevel.Error); } return(retVal); }
internal string GenerateActions(string baseNamespace, string namespacePostfix, string classNamespace, IList<IEntityNavigation> excludeCircularReferenceNavigationProperties, IEntityType entity, bool InludeRelatedObjects, bool prependSchemaNameIndicator) { var sb = new StringBuilder(); string entityName = Inflector.Humanize(entity.ClrType.Name); sb.AppendLine($"using System;"); sb.AppendLine($"using System.Collections.Generic;"); sb.AppendLine($"using System.Text;"); sb.AppendLine($"using System.Linq;"); sb.AppendLine($"using Csla; //https://github.com/MarimerLLC/csla"); sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"using {baseNamespace}.DataAccess;" : $"using {baseNamespace}.DataAccess.{namespacePostfix};"); sb.AppendLine($""); sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"namespace {baseNamespace}.Shared" : $"namespace {baseNamespace}.Shared.{namespacePostfix}"); sb.AppendLine($"{{"); sb.AppendLine("\t[Serializable]"); sb.AppendLine($"\tpublic class {entityName}List : ReadOnlyListBase<{entityName}List, {entityName}Info>"); sb.AppendLine($"\t{{"); sb.AppendLine("\t\t[Fetch]"); sb.AppendLine($"\t\tprivate void Fetch([Inject]I{entityName}Dal dal)"); sb.AppendLine("\t\t{"); sb.AppendLine("\t\t\tIsReadOnly = false;"); sb.AppendLine("\t\t\tvar data = dal.Get().Select(d => DataPortal.FetchChild<PersonInfo>(d));"); sb.AppendLine("\t\t\tAddRange(data);"); sb.AppendLine("\t\t\tIsReadOnly = true;"); sb.AppendLine("\t\t}"); sb.AppendLine(string.Empty); sb.AppendLine($"\t}}"); sb.AppendLine($"}}"); return sb.ToString(); }
internal string GenerateRazor(string baseNamespace, string namespacePostfix, IEntityType entity) { var sb = new StringBuilder(); string entityName = Inflector.Humanize(entity.ClrType.Name); var k = entity.FindPrimaryKey(); var kctype = k.Properties[0].ClrType; var primaryKey = entity.FindPrimaryKey(); var ksimpleType = ConvertToSimpleType(kctype.Name); // Header area directives #region HeaderDirectives sb.AppendLine($"@page \"/List{Inflector.Pluralize(entityName)}\""); sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"@using {baseNamespace}.Shared" : $"@using {baseNamespace}.Shared.{namespacePostfix}"); sb.AppendLine($"@inject Csla.Blazor.ViewModel<{entityName}List> vm"); #endregion HeaderDirectives // Begin page body #region PageBody sb.AppendLine($"<h1>List of {entityName}</h1>"); sb.AppendLine($""); sb.AppendLine($"\t<p style=\"background-color:red; color: white\">@vm.ViewModelErrorText</p>"); sb.AppendLine($""); // Loading, with link to add entity sb.AppendLine($"@if (vm.Model == null)"); sb.AppendLine($"{{"); sb.AppendLine($"\t\t<p>Loading List ...</p>"); sb.AppendLine($"\t\t<p><a href=\"edit{entityName}\">Add {entityName}</a></p>"); sb.AppendLine($"}}"); sb.AppendLine($"else"); // Beginning of loading else sb.AppendLine($"{{"); // Link to add entity sb.AppendLine($"\t<p><a href=\"edit{entityName}\">Add {entityName}</a></p>"); sb.AppendLine($""); // Main Table sb.AppendLine($"\t<table class=\"table\">"); sb.AppendLine($"\t<thead>"); sb.AppendLine($"\t\t<tr>"); sb.AppendLine($"\t\t\t<th>Name</th>"); sb.AppendLine($"\t\t\t<th></th>"); sb.AppendLine($"\t\t</tr>"); sb.AppendLine($"\t</thead>"); sb.AppendLine($"\t<tbody>"); // begin generated razor foreach sb.AppendLine($"\t\t@foreach (var item in vm.Model)"); sb.AppendLine($"\t\t{{"); // begin generated rows and columns var entityProperties = entity.GetProperties(); foreach (var property in entityProperties) { string ctype = GetCType(property); var simpleType = ConvertToSimpleType(ctype); string propertyName = property.Name; if (propertyName == k.Properties[0].Name) { //key, save for the end column } else { sb.AppendLine($"\t\t\t<tr>"); sb.AppendLine($"\t\t\t<td>@item.{propertyName}</td>"); } } sb.AppendLine($"\t\t\t<td><a href=\"edit{entityName}/@item.{k.Properties[0].Name}\">Edit</a></td>"); sb.AppendLine($"\t\t\t</tr>"); // end generated razor foreach sb.AppendLine($"\t\t}}"); sb.AppendLine($""); sb.AppendLine($"\t</tbody>"); sb.AppendLine($"\t</table>"); // End of loading else sb.AppendLine($"}}"); #endregion PageBody GenerateRazorCodeSection(sb, entity); return sb.ToString(); }
private void GenerateRazorCodeSection(StringBuilder sb, IEntityType entity) { var primaryKey = entity.FindPrimaryKey(); var primaryKeyCType = primaryKey.Properties[0].ClrType; var primatyKeySimpleType = ConvertToSimpleType(primaryKeyCType.Name); // Beginning code section declaration sb.AppendLine($"@code {{"); // Parameter sb.AppendLine("\t[Parameter]"); // In the original razor page, the parameter was declared as a string even though the key type was int // May want to revisit this sb.AppendLine($"\tpublic string {primaryKey.Properties[0].Name} {{ get; set; }}"); // OnInitialized sb.AppendLine($"\tprotected override void OnInitialized()"); sb.AppendLine("\t{"); sb.AppendLine($"\t\tvm.Saved += () => NavigationManager.NavigateTo(\"list{ Inflector.Pluralize(Inflector.Humanize(entity.ClrType.Name))}\");"); sb.AppendLine("\t\tvm.ModelChanging += (o, n) =>"); sb.AppendLine($"\t\t{{"); sb.AppendLine("\t\t\tif (o != null)"); sb.AppendLine("\t\t\t\to.PropertyChanged -= async (s, e) => await InvokeAsync(() => StateHasChanged());"); sb.AppendLine("\t\t\tif (n != null)"); sb.AppendLine("\t\t\t\tn.PropertyChanged += async (s, e) => await InvokeAsync(() => StateHasChanged());"); sb.AppendLine(""); sb.AppendLine($"\t\t}};"); sb.AppendLine($"\t}}"); // OnParametersSetAsync sb.AppendLine($"\tprotected override async Task OnParametersSetAsync()"); sb.AppendLine("\t{"); sb.AppendLine($"\t\tif (string.IsNullOrWhiteSpace({primaryKey.Properties[0].Name}))"); sb.AppendLine("\t\t\tawait vm.RefreshAsync();"); sb.AppendLine("\t\telse"); sb.AppendLine($"\t\t\tawait vm.RefreshAsync(int.Parse({primaryKey.Properties[0].Name}));"); sb.AppendLine(""); sb.AppendLine($"\t}}"); // End code section declaration sb.AppendLine($"}}"); }
internal string GenerateRazor(string baseNamespace, string namespacePostfix, IEntityType entity, string AuthorizeRoles) { var sb = new StringBuilder(); string entityName = Inflector.Humanize(entity.ClrType.Name); var k = entity.FindPrimaryKey(); var kctype = k.Properties[0].ClrType; var primaryKey = entity.FindPrimaryKey(); var ksimpleType = ConvertToSimpleType(kctype.Name); // Header area directives #region HeaderDirectives sb.AppendLine($"@page \"/Edit{entityName}\""); sb.AppendLine($"@page \"/EditPerson/{{{primaryKey.Properties[0].Name}}}\""); sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"@using {baseNamespace}.Shared" : $"@using {baseNamespace}.Shared.{namespacePostfix}"); sb.AppendLine($"@inject Csla.Blazor.ViewModel<{entityName}Edit> vm"); sb.AppendLine($"@inject NavigationManager NavigationManager"); if (AuthorizeRoles != null && AuthorizeRoles.Any()) { sb.AppendLine($"@attribute [Authorize(Roles = \"{AuthorizeRoles}\")]"); } #endregion HeaderDirectives // Begin page body #region PageBody sb.AppendLine($"<h1>Edit {entityName}</h1>"); sb.AppendLine($""); sb.AppendLine($"<p class=\"lead\">This component demonstrates editing a BusinessBase-derived object.</p>"); sb.AppendLine($""); sb.AppendLine($"<p style=\"background-color:red; color: white\">@vm.ViewModelErrorText</p>"); sb.AppendLine($""); // Loading sb.AppendLine($"@if (vm.Model == null)"); sb.AppendLine($"{{"); sb.AppendLine($"\t\t<p>Loading {entityName}...</p>"); sb.AppendLine($"}}"); sb.AppendLine($"else"); // Beginning of loading else sb.AppendLine($"{{"); // Link back to index sb.AppendLine($"\t<p>"); sb.AppendLine($"\t<a href=\"list{Inflector.Pluralize(entityName)}\">List of {Inflector.Pluralize(entityName)}</a>"); sb.AppendLine($"\t</p>"); sb.AppendLine($""); // Edit Table sb.AppendLine($"\t<table class=\"table table-bordered table-striped\">"); sb.AppendLine($"\t<thead>"); sb.AppendLine($"\t\t<tr>"); sb.AppendLine($"\t\t\t<th scope=\"col\">Property</th>"); sb.AppendLine($"\t\t\t<th scope=\"col\">Value</th>"); sb.AppendLine($"\t\t</tr>"); sb.AppendLine($"\t</thead>"); sb.AppendLine($"\t<tbody>"); // begin iterate through properties for table var entityProperties = entity.GetProperties(); foreach (var property in entityProperties) { string ctype = GetCType(property); var simpleType = ConvertToSimpleType(ctype); string propertyName = property.Name; if (propertyName == k.Properties[0].Name) { //key sb.AppendLine($"\t\t<tr>"); sb.AppendLine($"\t\t<td>{k.Properties[0].Name}</td>"); sb.AppendLine($"\t\t<td>@vm.Model.{k.Properties[0].Name}</td>"); sb.AppendLine($"\t\t</tr>"); sb.AppendLine($"\t\t"); } else { //non key sb.AppendLine($"\t@if(vm.GetPropertyInfo(nameof(vm.Model.{propertyName})).CanRead)"); sb.AppendLine($"\t{{"); sb.AppendLine($"\t\t<tr>"); sb.AppendLine("\t\t<td>@(vm.GetPropertyInfo(nameof(vm.Model.Name)).FriendlyName)</td>"); sb.AppendLine($"\t\t<td>"); sb.AppendLine($"\t\t<TextInput Property = \"@(vm.GetPropertyInfo(nameof(vm.Model.{propertyName})))\"/>"); sb.AppendLine($"\t\t</td>"); sb.AppendLine($"\t\t</tr>"); sb.AppendLine($""); sb.AppendLine($"\t}}"); } } sb.AppendLine($""); // Is new sb.AppendLine($"\t<tr>"); sb.AppendLine($"\t\t<td>Is New</td>"); sb.AppendLine($"\t\t<td>@vm.Model.IsNew</td>"); sb.AppendLine($"\t</tr>"); sb.AppendLine($""); // Is savable sb.AppendLine($"\t<tr>"); sb.AppendLine($"\t\t<td>Is Savable</td>"); sb.AppendLine($"\t\t<td>@vm.Model.IsSavable</td>"); sb.AppendLine($"\t</tr>"); sb.AppendLine($""); sb.AppendLine($"\t</tbody>"); sb.AppendLine($"\t</table>"); // Save buuton sb.AppendLine($""); sb.AppendLine($"\t<button @onclick=\"vm.SaveAsync\" disabled=\"@(!vm.Model.IsSavable)\" class=\"btn btn-primary\">Save {entityName}</button>"); // End of loading else sb.AppendLine($"}}"); #endregion PageBody GenerateRazorCodeSection(sb, entity); return(sb.ToString()); }
public string GenerateWebApiDataService( string iLoggingServiceNamespace, string serializationHelperNamespace, string webApiDataServiceInterfaceNamespace, string webApiDataServiceNamespace, string dtoNamespacePrefix, string dtoNamespace, string classNamespace, string namespacePostfix, string defaultCriteria, bool prependSchemaNameIndicator, IList <IEntityType> entityTypes, string baseNamespace) { var entitiesSortedByName = entityTypes.OrderBy(f => f.ClrType.Name); var sb = new StringBuilder(); var sbGetAllPages = new StringBuilder(); var sbGetOnePage = new StringBuilder(); var sbGetByPK = new StringBuilder(); var sbCreate = new StringBuilder(); var sbUpdate = new StringBuilder(); var sbDelete = new StringBuilder(); sb.Append(GenerateHeader( iLoggingServiceNamespace: iLoggingServiceNamespace, serializationHelperNamespace: serializationHelperNamespace, webApiDataServiceInterfaceNamespace: webApiDataServiceInterfaceNamespace, webApiDataServiceNamespace: webApiDataServiceNamespace, dtoNamespacePrefix: dtoNamespacePrefix, dtoNamespace: dtoNamespace, namespacePostfix: namespacePostfix, baseNamespace: baseNamespace)); sbGetAllPages.AppendLine($"{Environment.NewLine}\t\t#region GetAllPages{Environment.NewLine}"); sbGetOnePage.AppendLine($"{Environment.NewLine}\t\t#region GetOnePage{Environment.NewLine}"); sbGetByPK.AppendLine($"{Environment.NewLine}\t\t#region Get By PK{Environment.NewLine}"); sbCreate.AppendLine($"{Environment.NewLine}\t\t#region Create{Environment.NewLine}"); sbUpdate.AppendLine($"{Environment.NewLine}\t\t#region Update{Environment.NewLine}"); sbDelete.AppendLine($"{Environment.NewLine}\t\t#region Delete{Environment.NewLine}"); foreach (var entity in entitiesSortedByName) { string defaultCriteriaTableNameSubstituted = defaultCriteria?.Replace("[tablename]", Inflector.Humanize(entity.ClrType.Name)); var defaultCriteriaAsTypeAndFieldNameList = GetDefaultCriteriaListForWebApi(defaultCriteriaTableNameSubstituted); string entityName = Inflector.Pascalize(entity.ClrType.Name); var criteriaFieldsThatExistInTable = FilterFieldTypeAndNamesByExistingColumns(entity, defaultCriteriaAsTypeAndFieldNameList); var criteriaTypeAndFieldNamesConcatenated = GetFieldTypeAndNamesConcatenated(criteriaFieldsThatExistInTable); var criteriaFieldNamesConcatenated = GetFieldNamesConcatenated(criteriaFieldsThatExistInTable); string keylist = string.Join("}/{", entity.GetKeys().Select(n => Inflector.ToLowerFirstCharacter(n.Properties[0].Name))); // Get All Pages // Begin method signature sbGetAllPages.AppendLine($"\t\tpublic async Task<IList<{dtoNamespacePrefix}.{entityName}>> GetAllPages{Inflector.Pluralize(entityName)}Async("); sbGetAllPages.Append($"\t\t\t"); if (!string.IsNullOrEmpty(criteriaTypeAndFieldNamesConcatenated)) { sbGetAllPages.Append($"{criteriaTypeAndFieldNamesConcatenated}, "); } sbGetAllPages.AppendLine($"string sort = null)"); // End method signature sbGetAllPages.AppendLine($"\t\t{{"); BuildFilterCriteria(ref sbGetAllPages, criteriaFieldsThatExistInTable); sbGetAllPages.AppendLine($"\t\t\tIPageDataRequest pageDataRequest = new PageDataRequest(filterCriteria: filterCriteria, sort: sort, page: 1, pageSize: 100);"); //sbGetAllPages.AppendLine($"\t\t\treturn await GetAllPageDataResultsAsync<{dtoNamespacePrefix}.{tableName}>(pageDataRequest, Get{table.NamePlural}Async);"); sbGetAllPages.AppendLine($"\t\t\treturn await GetAllPageDataResultsAsync(pageDataRequest, Get{Inflector.Pluralize(entityName)}Async);"); sbGetAllPages.AppendLine($"\t\t}}"); sbGetAllPages.AppendLine(string.Empty); // Get One Page - Part 1 sbGetOnePage.AppendLine($"\t\tpublic async Task<IHttpCallResultCGHT<IPageDataT<IList<{dtoNamespacePrefix}.{entityName}>>>> Get{Inflector.Pluralize(entityName)}Async(IPageDataRequest pageDataRequest)"); sbGetOnePage.AppendLine($"\t\t{{"); sbGetOnePage.AppendLine($"\t\t\tList<string> filter = BuildFilter(pageDataRequest.FilterCriteria);"); sbGetOnePage.AppendLine($"\t\t\treturn await SerializationHelper.Instance.SerializeCallResultsGet<IList<{dtoNamespacePrefix}.{entityName}>>(Log, HttpClient, "); sbGetOnePage.AppendLine($"\t\t\t\t$\"{namespacePostfix}/{Inflector.Pluralize(entityName)}\", filter, page: pageDataRequest.Page, pageSize: pageDataRequest.PageSize);"); sbGetOnePage.AppendLine($"\t\t}}"); sbGetOnePage.AppendLine(string.Empty); // Get One Page - Part 2 sbGetOnePage.AppendLine($"\t\tpublic async Task<IHttpCallResultCGHT<IPageDataT<IList<{dtoNamespacePrefix}.{entityName}>>>> Get{Inflector.Pluralize(entityName)}Async("); sbGetOnePage.Append($"\t\t\t"); if (!string.IsNullOrEmpty(criteriaTypeAndFieldNamesConcatenated)) { sbGetOnePage.Append($"{criteriaTypeAndFieldNamesConcatenated}, "); } sbGetOnePage.AppendLine($"string sort = null, int page = 1, int pageSize = 100)"); sbGetOnePage.AppendLine($"\t\t{{"); BuildFilterCriteria(ref sbGetOnePage, criteriaFieldsThatExistInTable); sbGetOnePage.AppendLine(string.Empty); sbGetOnePage.AppendLine($"\t\t\tIPageDataRequest pageDataRequest = new PageDataRequest(filterCriteria: filterCriteria, sort: sort, page: page, pageSize: pageSize);"); sbGetOnePage.AppendLine($"\t\t\treturn await Get{Inflector.Pluralize(entityName)}Async(pageDataRequest);"); sbGetOnePage.AppendLine($"\t\t}}"); sbGetOnePage.AppendLine(string.Empty); // Get By PK sbGetByPK.AppendLine($"\t\tpublic async Task<IHttpCallResultCGHT<{dtoNamespacePrefix}.{entityName}>> Get{entityName}Async({GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())}, int numChildLevels)"); sbGetByPK.AppendLine($"\t\t{{"); sbGetByPK.AppendLine($"\t\t\tvar retVal = await SerializationHelper.Instance.SerializeCallResultsGet<{dtoNamespacePrefix}.{entityName}>(Log, HttpClient, $\"{namespacePostfix}/{Inflector.Pluralize(entityName)}/{{{keylist}}}?numChildLevels={{numChildLevels}}\");"); sbGetByPK.AppendLine($"\t\t\treturn retVal;"); sbGetByPK.AppendLine($"\t\t}}"); sbGetByPK.AppendLine(string.Empty); // Create sbCreate.Append(GenerateSerializeCallFor(namespacePostfix: namespacePostfix, dtoNamespacePrefix: dtoNamespacePrefix, httpVerb: "Post", prependSchemaNameIndicator: prependSchemaNameIndicator, entity: entity)); // Update sbUpdate.Append(GenerateSerializeCallFor(namespacePostfix: namespacePostfix, dtoNamespacePrefix: dtoNamespacePrefix, httpVerb: "Put", prependSchemaNameIndicator: prependSchemaNameIndicator, entity: entity)); // Delete sbDelete.AppendLine($"\t\tpublic async Task<IHttpCallResultCGHT<{dtoNamespacePrefix}.{entityName}>> Delete{Inflector.Humanize(entity.ClrType.Name)}Async({GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())})"); sbDelete.AppendLine($"\t\t{{"); sbDelete.AppendLine($"\t\t\tvar retVal = await SerializationHelper.Instance.SerializeCallResultsDelete<{dtoNamespacePrefix}.{entityName}>(Log, HttpClient, $\"{namespacePostfix}/{Inflector.Pluralize(entityName)}/{{{keylist}}}\");"); sbDelete.AppendLine($"\t\t\treturn retVal;"); sbDelete.AppendLine($"\t\t}}"); sbDelete.AppendLine(string.Empty); } sbGetAllPages.AppendLine($"\t\t#endregion GetAllPages{Environment.NewLine}"); sb.AppendLine(sbGetAllPages.ToString()); sbGetOnePage.AppendLine($"\t\t#endregion GetOnePage{Environment.NewLine}"); sb.AppendLine(sbGetOnePage.ToString()); sbGetByPK.AppendLine($"\t\t#endregion Get By PK{Environment.NewLine}"); sb.AppendLine(sbGetByPK.ToString()); sbCreate.AppendLine($"\t\t#endregion Create{Environment.NewLine}"); sb.AppendLine(sbCreate.ToString()); sbUpdate.AppendLine($"\t\t#endregion Update{Environment.NewLine}"); sb.AppendLine(sbUpdate.ToString()); sbDelete.AppendLine($"\t\t#endregion Delete{Environment.NewLine}"); sb.AppendLine(sbDelete.ToString()); sb.Append(GenerateFooter()); return(sb.ToString()); }
public string GenerateWebApiController( string baseNamespace, string namespacePostfix, string classNamespace, string baseControllerName, string apiHelpersNamespace, string iLoggingServiceNamespace, string repositoryNamespace, string factoryNamespace, string efEntityNamespacePrefix, string efEntityNamespace, string dtoNamespacePrefix, string dtoNamespace, string enumNamespace, string repositoryInterfaceName, string dbContextName, List <NameValue> maxRequestPerPageOverrides, bool prependSchemaNameIndicator, IEntityType entity, IList <IEntityNavigation> excludedNavigationProperties) { var className = $"{Inflector.Pluralize(entity.ClrType.Name)}{namespacePostfix}Controller"; string tableName = Inflector.Humanize(entity.ClrType.Name); string tablenameSchema = Inflector.Humanize(entity.ClrType.Name); string tablenameNoSchema = tablenameSchema; string tablenamePlural = Inflector.Pluralize(entity.ClrType.Name); // TODO: find equivalent //if (entity.TableSchema != null && !entity.TableSchema.Equals("dbo", System.StringComparison.OrdinalIgnoreCase)) //{ // tablenameSchema = $"{entity.TableSchema}_{tablenameNoSchema}"; // tablenamePlural = $"{entity.TableSchema}_{tablenamePlural}"; //} string entityTypeName = $"{efEntityNamespacePrefix}.{tablenameSchema}"; //set maxpage size var maxPageSize = 0; var maxRequestPerPageOverRideString = maxRequestPerPageOverrides .FirstOrDefault(x => x.Name == entity.ClrType.Name)?.Value; if (!string.IsNullOrWhiteSpace(maxRequestPerPageOverRideString)) { int.TryParse(maxRequestPerPageOverRideString, out maxPageSize); } if (maxPageSize <= 0) { maxPageSize = 100; } var sb = new IndentingStringBuilder(); var usings = new List <NamespaceItem> { new NamespaceItem("AutoMapper"), new NamespaceItem("System"), new NamespaceItem("System.Collections.Generic"), new NamespaceItem("Microsoft.EntityFrameworkCore"), new NamespaceItem("Microsoft.Extensions.Logging"), new NamespaceItem("System.Linq"), new NamespaceItem("System.Net"), new NamespaceItem("System.Threading.Tasks"), new NamespaceItem("System.Web"), new NamespaceItem("System.Web.Http"), new NamespaceItem("System.Web.Http.Routing"), new NamespaceItem("Marvin.JsonPatch"), new NamespaceItem($"cghEnums", "CodeGenHero.Repository.Enums"), new NamespaceItem($"coreEnums", "CodeGenHero.Core.Enums"), new NamespaceItem("CodeGenHero.DataService"), new NamespaceItem("CodeGenHero.Repository"), new NamespaceItem("CodeGenHero.Repository.AutoMapper"), new NamespaceItem("CodeGenHero.WebApi"), new NamespaceItem($"{baseNamespace}.Repository.Interface"), new NamespaceItem($"dto{namespacePostfix}", string.IsNullOrWhiteSpace(namespacePostfix) ? $"{baseNamespace}.DTO" : $"{baseNamespace}.DTO.{namespacePostfix}"), new NamespaceItem($"ent{namespacePostfix}", efEntityNamespace) }; sb.Append(GenerateHeader(usings, classNamespace)); sb.AppendLine($"\tpublic partial class {className} : {baseControllerName}"); sb.AppendLine("\t{"); sb.AppendLine($"\t\tprivate const string GET_LIST_ROUTE_NAME = \"{Inflector.Pluralize(entity.ClrType.Name)}{namespacePostfix}List\";"); sb.AppendLine($"\t\tprivate const int maxPageSize = {maxPageSize};"); sb.AppendLine($"\t\tprivate GenericFactory<{efEntityNamespacePrefix}.{tableName}, {dtoNamespacePrefix}.{tableName}> _factory;"); sb.AppendLine(string.Empty); sb.Append(GenerateConstructors(className: className, repositoryInterfaceName: repositoryInterfaceName, efEntityNamespacePrefix: efEntityNamespacePrefix, dtoNamespacePrefix: dtoNamespacePrefix, tableName: tableName)); sb.Append(GenerateDelete(entity: entity)); sb.Append(GenerateGet(entity: entity, tableName: tableName, entityTypeName: entityTypeName)); sb.Append(GenerateGetByPK(entity: entity, tableName: tableName)); sb.Append(GeneratePatch(entity: entity, tableName: tableName, dtoNamespacePrefix: dtoNamespacePrefix, entityTypeName: entityTypeName)); sb.Append(GeneratePost(entity: entity, tableName: tableName, dtoNamespacePrefix: dtoNamespacePrefix)); sb.Append(GeneratePut(entity: entity, tableName: tableName, dtoNamespacePrefix: dtoNamespacePrefix, entityTypeName: entityTypeName)); sb.Append(GenerateFooter(dbContextName: dbContextName, entity: entity, excludedNavigationProperties: excludedNavigationProperties, entityTypeName: entityTypeName)); sb.Append("\t}\r\n}"); // Close the class, close the namespace return(sb.ToString()); }
public string Generate( List <string> usings, string classNamespace, bool prependSchemaNameIndicator, IList <IEntityType> entityTypes) { StringBuilder sb = new StringBuilder(); sb.Append(GenerateUsings(usings)); sb.AppendLine(string.Empty); sb.AppendLine($"namespace {classNamespace}"); sb.AppendLine($"{{"); sb.AppendLine($"\tpublic static class ToModelMappers"); sb.AppendLine($"\t{{"); foreach (var entity in entityTypes) { var k = entity.FindPrimaryKey(); string entityName = Inflector.Pascalize(entity.ClrType.Name); var entityProperties = entity.GetProperties().OrderBy(n => n.Name).ToList(); bool hasMultiplePrimaryKeys = entity.FindPrimaryKey().Properties.Count > 1; string compositePKFieldName = string.Empty; string compositePKFieldValue = string.Empty; sb.AppendLine($"\t\tpublic static xModel.{entityName} ToModel(this xData.{entityName} obj, cEnums.RecordStatus recordStatus, bool removeSelfReferencingChildEntities = true)"); sb.AppendLine($"\t\t{{"); //Beginning of main method bracket //Null Check sb.AppendLine($"\t\t\tif (obj == null || (obj.StatusTypeId & (int)recordStatus) != obj.StatusTypeId)"); sb.AppendLine("\t\t\treturn null;"); //Remove self referencing child entities sb.AppendLine($"\t\t\tif(removeSelfReferencingChildEntities)"); sb.AppendLine($"\t\t\t{{ // Avoid circular references from causing infinite loops during serialization."); sb.AppendLine($"\t\t\t\t\tvar crr = new Service.CircularReferenceRemover<xData.{entityName}>();"); sb.AppendLine($"\t\t\t\t\tcrr.RemoveSelfReferencingChildEntities(obj);"); sb.AppendLine($"\t\t\t}}"); //Declaration of return mapped value sb.AppendLine($"\t\t\tvar retVal = new xModel.{entityName}()"); sb.AppendLine($"\t\t\t{{"); //Loop through properties for (int i = 0; i < entityProperties.Count(); i++) { var property = entityProperties[i]; string propertyName = Inflector.Pascalize(property.Name); string ctype = GetCType(property); var simpleType = ConvertToSimpleType(ctype); if (simpleType == "DateTime") { sb.AppendLine($"\t\t\t\t{propertyName} = DateTime.SpecifyKind(obj.{propertyName}, DateTimeKind.Utc),"); } else { sb.AppendLine($"\t\t\t\t{propertyName} = obj.{propertyName},"); } } //Loop through navigations foreach (var reverseFK in entity.Navigations) { string name = reverseFK.DeclaringType.ClrType.Name; string humanCase = Inflector.Humanize(name); string reverseFKName = reverseFK.ForeignKey.PrincipalEntityType.Name; if (!reverseFK.ClrType.Name.Equals("ICollection`1")) { sb.AppendLine($"\t\t\t\t{reverseFK.ClrType.Name} = obj.{reverseFK.ClrType.Name}.ToModel(recordStatus),"); } else { sb.AppendLine($"\t\t\t\t{Inflector.Pluralize(humanCase)} = obj.{Inflector.Pluralize(humanCase)}.ToModel<xData.{humanCase}, xModel.{humanCase}>(recordStatus),"); } } sb.AppendLine($"\t\t}};"); sb.AppendLine("\t\treturn retVal;"); sb.AppendLine($"}}"); sb.AppendLine(string.Empty); } GenerateFooter(sb); return(sb.ToString()); }
public string Generate( List <string> usings, string classNamespace, bool prependSchemaNameIndicator, IList <IEntityType> entityTypes) { StringBuilder sb = new StringBuilder(); sb.Append(GenerateUsings(usings)); sb.AppendLine(string.Empty); sb.AppendLine($"namespace {classNamespace}"); sb.AppendLine($"{{"); sb.AppendLine($"\tpublic static class ToDataMappers"); sb.AppendLine($"\t{{"); foreach (var entity in entityTypes) { var k = entity.FindPrimaryKey(); string entityName = Inflector.Pascalize(entity.ClrType.Name); var entityProperties = entity.GetProperties().OrderBy(n => n.Name).ToList(); bool hasMultiplePrimaryKeys = entity.FindPrimaryKey().Properties.Count > 1; string compositePKFieldName = string.Empty; string compositePKFieldValue = string.Empty; sb.AppendLine($"\t\tpublic static xData.{entityName} ToData(this xModel.{entityName} obj)"); sb.AppendLine($"\t\t{{"); //Beginning of main method bracket //Null Check sb.AppendLine($"\t\t\tif (obj == null)"); sb.AppendLine("\t\t\treturn null;"); //Declaration of return mapped value sb.AppendLine($"\t\t\tvar retVal = new xData.{entityName}()"); sb.AppendLine($"\t\t\t{{"); //Loop through properties for (int i = 0; i < entityProperties.Count(); i++) { var property = entityProperties[i]; string propertyName = Inflector.Pascalize(property.Name); string ctype = GetCType(property); var simpleType = ConvertToSimpleType(ctype); if (simpleType == "DateTime") { sb.AppendLine($"\t\t\t\t{propertyName} = DateTime.SpecifyKind(obj.{propertyName}, DateTimeKind.Utc),"); } else { sb.AppendLine($"\t\t\t\t{propertyName} = obj.{propertyName},"); } } //Loop through navigations foreach (var reverseFK in entity.Navigations) { string name = reverseFK.DeclaringType.ClrType.Name; string humanCase = Inflector.Humanize(name); string reverseFKName = reverseFK.ForeignKey.PrincipalEntityType.Name; if (!reverseFK.ClrType.Name.Equals("ICollection`1")) { sb.AppendLine($"\t\t\t\t{reverseFK.ClrType.Name} = obj.{reverseFK.ClrType.Name}.ToData(),"); } else { sb.AppendLine($"\t\t\t\t{Inflector.Pluralize(humanCase)} = obj.{Inflector.Pluralize(humanCase)}.ToData<xData.{humanCase}, xModel.{humanCase}>(),"); } } sb.AppendLine($"\t\t}};"); sb.AppendLine("\t\treturn retVal;"); sb.AppendLine($"}}"); sb.AppendLine(string.Empty); } GenerateFooter(sb); return(sb.ToString()); }
public string GenerateDataAccessEF( IEntityType entity, string useNamespace, string dbContextName) { var sb = new StringBuilder(); string entityName = Inflector.Humanize(entity.ClrType.Name); string entityNamePluralized = Inflector.Pluralize(entityName); string entityNameCamelized = Inflector.Camelize(entityName); string signature = GetSignature(entity); sb.AppendLine(GetUsings()); sb.AppendLine($"namespace {useNamespace}"); sb.AppendLine($"{{"); sb.AppendLine($"\tpublic class {entityName}EFDal: I{entityName}Dal"); sb.AppendLine($"\t{{"); sb.AppendLine(string.Empty); sb.AppendLine($"\t\tprivate readonly {dbContextName} _context;"); sb.AppendLine(""); sb.AppendLine($"\t\tpublic {entityName}EFDal({dbContextName} context)"); sb.AppendLine("\t\t{"); sb.AppendLine("\t\t\t_context = context;"); sb.AppendLine("\t\t}"); sb.AppendLine(string.Empty); string whereClause = BuildWhereClause("p", entity); // DELETE sb.AppendLine($"\t\tpublic bool Delete({signature})"); //TODO: We probably need to get the primary keys and and calculate the signature sb.AppendLine("\t\t{"); sb.AppendLine($"\t\t\tvar {entityNameCamelized} = _context.{entityNamePluralized}.FirstOrDefault(p => {whereClause});"); sb.AppendLine($"\t\t\tif ({entityNameCamelized} != null)"); sb.AppendLine($"\t\t\t{{"); sb.AppendLine($"\t\t\t\t_context.{entityNamePluralized}.Remove({entityNameCamelized});"); sb.AppendLine($"\t\t\t\t_context.SaveChanges();"); sb.AppendLine($"\t\t\t\treturn true;"); sb.AppendLine("\t\t\t}"); sb.AppendLine("\t\t\telse"); sb.AppendLine("\t\t\t{"); sb.AppendLine($"\t\t\t\treturn false;"); sb.AppendLine("\t\t\t}"); sb.AppendLine($"\t\t}}"); sb.AppendLine(string.Empty); // EXISTS sb.AppendLine($"\t\tpublic bool Exists({signature})"); sb.AppendLine("\t\t{"); sb.AppendLine($"\t\t\tvar {entityNameCamelized} = _context.{entityNamePluralized}.FirstOrDefault(p => {whereClause});"); sb.AppendLine($"\t\t\treturn !({entityNameCamelized} == null);"); sb.AppendLine($"\t\t}}"); sb.AppendLine(string.Empty); sb.AppendLine(string.Empty); // GET sb.AppendLine($"\t\tpublic {entityName}Entity Get({signature})"); sb.AppendLine("\t\t{"); sb.AppendLine($"\t\t\tvar {entityNameCamelized} = _context.{entityNamePluralized}.FirstOrDefault(p => {whereClause});"); sb.AppendLine($"\t\t\tif ({entityNameCamelized} != null)"); sb.AppendLine($"\t\t\t{{"); sb.AppendLine($"\t\t\t\treturn {entityNameCamelized};"); sb.AppendLine("\t\t\t}"); sb.AppendLine("\t\t\telse"); sb.AppendLine("\t\t\t{"); sb.AppendLine($"\t\t\t\tthrow new KeyNotFoundException($\"Id {{id}}\");"); sb.AppendLine("\t\t\t}"); sb.AppendLine($"\t\t}}"); sb.AppendLine(string.Empty); // GET (all) sb.AppendLine($"\t\tpublic List<{entityName}Entity> Get()"); sb.AppendLine("\t\t{"); sb.AppendLine($"\t\t\treturn _context.{entityNamePluralized}.Where(r => true).ToList();"); sb.AppendLine($"\t\t}}"); sb.AppendLine(string.Empty); // INSERT sb.AppendLine($"\t\tpublic {entityName}Entity Insert({entityName}Entity {entityNameCamelized})"); sb.AppendLine("\t\t{"); sb.AppendLine($"\t\t\tif (Exists({entityNameCamelized}.Id))"); sb.AppendLine($"\t\t\t{{"); sb.AppendLine($"\t\t\t\tthrow new InvalidOperationException($\"Key exists {{ {entityNameCamelized}.Id}}\");"); sb.AppendLine("\t\t\t}"); sb.AppendLine("\t\t\telse"); sb.AppendLine("\t\t\t{"); sb.AppendLine("\t\t\tint lastId = 0;"); sb.AppendLine($"\t\t\t\ttry"); sb.AppendLine("\t\t\t\t{"); sb.AppendLine("\t\t\t\t\tlastId = _context.Person.Max(m => m.Id);"); sb.AppendLine("\t\t\t\t}"); sb.AppendLine("\t\t\t\tcatch(Exception ex)"); sb.AppendLine("\t\t\t\t{"); sb.AppendLine(string.Empty); sb.AppendLine("\t\t\t\t}"); sb.AppendLine($"\t\t\t\t{entityNameCamelized}.Id = ++lastId;"); // Not sure how we want to handle this if the key is an Identity field, or not called Id, or using several primary keys sb.AppendLine($"\t\t\t\t_context.{entityNamePluralized}.Add({entityNameCamelized});"); sb.AppendLine("\t\t\t\t_context.SaveChanges();"); sb.AppendLine("\t\t\t}"); sb.AppendLine($"\t\t\treturn {entityNameCamelized};"); sb.AppendLine($"\t\t}}"); sb.AppendLine(string.Empty); // UPDATE var properties = GetPropertiesExcludingKeys(entity); sb.AppendLine($"\t\tpublic {entityName}Entity Update({entityName}Entity {entityNameCamelized})"); sb.AppendLine("\t\t{"); sb.AppendLine($"\t\t\tvar old = Get({entityNameCamelized}.Id);"); foreach (var propertyName in properties) { sb.AppendLine($"\t\t\told.{propertyName} = {entityNameCamelized}.{propertyName};"); } sb.AppendLine("\t\t\t_context.SaveChanges();"); sb.AppendLine($"\t\t\treturn old;"); sb.AppendLine($"\t\t}}"); sb.AppendLine("\t}"); sb.AppendLine("}}"); return(sb.ToString()); }
internal string GenerateActions(string baseNamespace, string namespacePostfix, string classNamespace, IList <IEntityNavigation> excludeCircularReferenceNavigationProperties, IEntityType entity, bool InludeRelatedObjects, bool prependSchemaNameIndicator) { var sb = new StringBuilder(); string entityName = Inflector.Humanize(entity.ClrType.Name); sb.AppendLine($"using System;"); sb.AppendLine($"using System.Collections.Generic;"); sb.AppendLine($"using System.Text;"); sb.AppendLine($"using Csla; //https://github.com/MarimerLLC/csla"); sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"using {baseNamespace}.DataAccess;" : $"using {baseNamespace}.DataAccess.{namespacePostfix};"); sb.AppendLine($""); sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"namespace {baseNamespace}.Shared" : $"namespace {baseNamespace}.Shared.{namespacePostfix}"); sb.AppendLine($"{{"); sb.AppendLine("\t[Serializable]"); sb.AppendLine($"\tpublic class {entityName}Edit : BusinessBase<{entityName}Edit>"); sb.AppendLine($"\t{{"); var primaryKeyList = GetPrimaryKeys(entity); var entityProperties = entity.GetProperties(); //////////////////Properties foreach (var property in entityProperties) { string ctype = GetCType(property); var simpleType = ConvertToSimpleType(ctype); string propertyName = property.Name; sb.AppendLine($"\t\tpublic static readonly PropertyInfo<{simpleType}> {propertyName}Property = RegisterProperty<{simpleType}>(nameof({propertyName}));"); sb.AppendLine($"\t\tpublic {simpleType} {propertyName}"); sb.AppendLine("\t\t{"); sb.AppendLine($"\t\t\tget {{return GetProperty({propertyName}Property);}}"); sb.AppendLine($"\t\t\tprivate set {{ LoadProperty({propertyName}Property, value);}}"); sb.AppendLine("\t\t}"); sb.AppendLine(string.Empty); } //////////////////AddBusinessRules sb.AppendLine("\t\tprotected override void AddBusinessRules()"); sb.AppendLine("\t\t{"); sb.AppendLine("\t\t\tbase.AddBusinessRules();"); sb.AppendLine("\t\t}"); //////////////////Create var k = entity.FindPrimaryKey(); var kctype = k.Properties[0].ClrType; var ksimpleType = ConvertToSimpleType(kctype.Name); sb.AppendLine(""); sb.AppendLine("\t\t[Create]"); sb.AppendLine("\t\tprivate void Create()"); sb.AppendLine("\t\t{"); sb.AppendLine($"\t\t\t{k.Properties[0].Name} = -1;"); sb.AppendLine("\t\t\tbase.DataPortal_Create();"); sb.AppendLine("\t\t}"); //////////////////Fetch sb.AppendLine(""); sb.AppendLine("\t\t[Fetch]"); sb.AppendLine($"\t\tprivate void Fetch({ksimpleType} {k.Properties[0].Name}, [Inject]I{entityName}Dal dal)"); sb.AppendLine("\t\t{"); sb.AppendLine($"\t\t\tvar data = dal.Get({k.Properties[0].Name});"); sb.AppendLine("\t\t\tusing (BypassPropertyChecks)"); sb.AppendLine("\t\t\t{"); sb.AppendLine("\t\t\t\tCsla.Data.DataMapper.Map(data, this);"); sb.AppendLine("\t\t\t}"); sb.AppendLine("\t\t\tBusinessRules.CheckRules();"); sb.AppendLine("\t\t}"); //////////////////Insert sb.AppendLine(""); sb.AppendLine("\t\t[Insert]"); sb.AppendLine($"\t\tprivate void Insert([Inject]I{entityName}Dal dal)"); sb.AppendLine("\t\t{"); sb.AppendLine("\t\t\tusing (BypassPropertyChecks)"); sb.AppendLine("\t\t\t{"); sb.AppendLine("\t\t\t\tvar data = new PersonEntity"); sb.AppendLine("\t\t\t\t{"); foreach (var property in entityProperties) { string ctype = GetCType(property); var simpleType = ConvertToSimpleType(ctype); string propertyName = property.Name; if (propertyName != k.Properties[0].Name) //don't assign the key inside this, it is assigned to the return of insert data below { sb.AppendLine($"\t\t\t\t\t{propertyName} = {propertyName},"); } } sb.AppendLine("\t\t\t\t};"); sb.AppendLine("\t\t\tvar result = dal.Insert(data);"); sb.AppendLine($"\t\t\t{k.Properties[0].Name} = result.{k.Properties[0].Name};"); sb.AppendLine("\t\t\t}"); sb.AppendLine("\t\t}"); //////////////////Update sb.AppendLine(""); sb.AppendLine("\t\t[Update]"); sb.AppendLine($"\t\tprivate void Update([Inject]I{entityName}Dal dal)"); sb.AppendLine("\t\t{"); sb.AppendLine("\t\t\tusing (BypassPropertyChecks)"); sb.AppendLine("\t\t\t{"); sb.AppendLine("\t\t\t\tvar data = new PersonEntity"); sb.AppendLine("\t\t\t\t{"); foreach (var property in entityProperties) { string ctype = GetCType(property); var simpleType = ConvertToSimpleType(ctype); string propertyName = property.Name; if (propertyName != k.Properties[0].Name) //don't assign the key inside this, it is assigned to the return of insert data below { sb.AppendLine($"\t\t\t\t\t{propertyName} = {propertyName},"); } } sb.AppendLine("\t\t\t\t};"); sb.AppendLine("\t\t\tvar result = dal.Update(data);"); sb.AppendLine($"\t\t\t{k.Properties[0].Name} = result.{k.Properties[0].Name};"); sb.AppendLine("\t\t\t}"); sb.AppendLine("\t\t}"); //////////////////Delete Self sb.AppendLine(""); sb.AppendLine("\t\t[DeleteSelf]"); sb.AppendLine($"\t\tprivate void DeleteSelf([Inject]I{entityName}Dal dal)"); sb.AppendLine("\t\t{"); sb.AppendLine($"\t\t\tDelete(ReadProperty({k.Properties[0].Name}Property), dal);"); sb.AppendLine("\t\t}"); //////////////////Delete sb.AppendLine(""); sb.AppendLine("\t\t[Delete]"); sb.AppendLine($"\t\tprivate void Delete({ksimpleType} {k.Properties[0].Name}, [Inject]I{entityName}Dal dal)"); sb.AppendLine("\t\t{"); sb.AppendLine($"\t\t\tdal.Delete({k.Properties[0].Name});"); sb.AppendLine("\t\t}"); sb.AppendLine($"\t}}"); sb.AppendLine($"}}"); return(sb.ToString()); }
public override TemplateOutput Generate() { TemplateOutput retVal = new TemplateOutput(); try { foreach (var entity in ProcessModel.MetadataSourceModel.EntityTypes) { string outputfile = TemplateVariablesManager.GetOutputFile(templateIdentity: ProcessModel.TemplateIdentity, fileName: Consts.OUT_webApiController); outputfile = outputfile.Replace("[tablename]", Inflector.Humanize(entity.ClrType.Name)).Replace("[tablepluralname]", Inflector.Pluralize(entity.ClrType.Name)); string filepath = outputfile; var maxRequestPerPageOverrides = DeserializeJsonObject <List <NameValue> >(MaxRequestPerPageOverrideByTableName); if (maxRequestPerPageOverrides == null) { maxRequestPerPageOverrides = new List <NameValue>(); } string baseControllerName = $"{NamespacePostfix}BaseApiController"; if (UseAuthorizedBaseController) //!string.IsNullOrEmpty(UseAuthorizedBaseController) && UseAuthorizedBaseController.ToLowerInvariant() == "true") { baseControllerName = $"{NamespacePostfix}BaseApiControllerAuthorized"; } WebApiControllerGenerator webApiControllerGenerator = new WebApiControllerGenerator(inflector: Inflector); string generatedCode = webApiControllerGenerator.GenerateWebApiController( baseNamespace: BaseNamespace, namespacePostfix: NamespacePostfix, classNamespace: WebApiControllerNamespace, baseControllerName: baseControllerName, apiHelpersNamespace: ApiHelpersNamespace, iLoggingServiceNamespace: ILoggingServiceNamespace, repositoryNamespace: RepositoryNamespace, factoryNamespace: FactoryNamespace, efEntityNamespacePrefix: $"ent{NamespacePostfix}", efEntityNamespace: RepositoryEntitiesNamespace, dtoNamespacePrefix: $"dto{NamespacePostfix}", dtoNamespace: DtoNamespace, enumNamespace: EnumNamespace, repositoryInterfaceName: $"I{NamespacePostfix}Repository", dbContextName: DbContextName, maxRequestPerPageOverrides: maxRequestPerPageOverrides, prependSchemaNameIndicator: PrependSchemaNameIndicator, entity: entity, excludedNavigationProperties: ProcessModel.ExcludedNavigationProperties ); retVal.Files.Add(new OutputFile() { Content = generatedCode, Name = filepath }); } } catch (Exception ex) { base.AddError(ref retVal, ex, Enums.LogLevel.Error); } AddTemplateVariablesManagerErrorsToRetVal(ref retVal, Enums.LogLevel.Error); return(retVal); }
public void TestHumanize() { Assert.AreEqual("Employee salary", Inflector.Humanize("employee_salary")); }
private void BuildForwardNavigation(IList <IEntityNavigation> excludedNavigationProperties, IEntityType entity, IForeignKey foreignKey, ref StringBuilder sbPrivateProperties, ref StringBuilder sbPublicProperties) { string entityName = Inflector.Humanize(entity.ClrType.Name); string name = foreignKey.PrincipalEntityType.ClrType.Name; string nameHumanized = name; if (nameHumanized.Length >= 2) { nameHumanized = Inflector.Humanize(nameHumanized); } bool excludeCircularReferenceNavigationIndicator = IsEntityInExcludedReferenceNavigionationProperties(excludedNavigationProperties, name); if (excludeCircularReferenceNavigationIndicator) { sbPrivateProperties.AppendLine($"\t\t// Excluding '{name}' per configuration setting."); return; } //TODO: Not sure if we have the schema name available. If we do, then we want to remove it from the start of the foreign key name below string publicPropertyName = name; // foreignKey.RefTableHumanCase.Replace($"{foreignKey.RefTableSchema}_", string.Empty); string privateVariableName = $"_{publicPropertyName.Substring(0, 1).ToLower()}{publicPropertyName.Substring(1)}"; bool useCollection = (foreignKey.PrincipalEntityType.ClrType.Name.Equals("ICollection`1")); //bool useCollection = foreignKey.Relationship == Library.Enums.Relationship.ManyToOne; string modelTypeName = name; // foreignKey.RefTable; string objectType; if (excludeCircularReferenceNavigationIndicator) { // This item is configured to be excluded from navigation properties. sbPrivateProperties.Append($"\t\t// "); } else { sbPrivateProperties.Append($"\t\t"); } if (useCollection) { //publicPropertyName = foreignKey.RefTableHumanCase.Replace($"{foreignKey.RefTableSchema}_", string.Empty); objectType = $"List<I{modelTypeName}>"; sbPrivateProperties.AppendLine($"private {objectType} {privateVariableName} = null; // Foreign Key"); } else { objectType = $"I{modelTypeName}"; sbPrivateProperties.AppendLine($"private {objectType} {privateVariableName} = null; // Foreign Key"); } string dtoName = nameHumanized; string initializer = useCollection ? "()" : ""; if (entityName == publicPropertyName) { publicPropertyName = $"{entityName}1"; } sbPublicProperties.AppendLine($"\t\tpublic virtual {objectType} {publicPropertyName}"); sbPublicProperties.AppendLine($"\t\t{{"); sbPublicProperties.AppendLine($"\t\t\tget"); sbPublicProperties.AppendLine($"\t\t\t{{"); if (excludeCircularReferenceNavigationIndicator) { sbPublicProperties.AppendLine($"\t\t\t\tif ({privateVariableName} == null)"); sbPublicProperties.AppendLine($"\t\t\t\t{{"); sbPublicProperties.AppendLine($"\t\t\t\t\tOnLazyLoadRequest(this, new LoadRequest{entityName}(nameof({publicPropertyName})));"); } else { sbPublicProperties.AppendLine($"\t\t\t\tif ({privateVariableName} == null && _dto != null && _dto.{dtoName} != null)"); sbPublicProperties.AppendLine($"\t\t\t\t{{"); if (useCollection) { sbPublicProperties.AppendLine($"\t\t\t\t\t{privateVariableName} = new {objectType}();"); sbPublicProperties.AppendLine($"\t\t\t\t\tforeach (var dtoItem in _dto.{name})"); sbPublicProperties.AppendLine($"\t\t\t\t\t{{"); sbPublicProperties.AppendLine($"\t\t\t\t\t\t{privateVariableName}.Add(new {modelTypeName}(Log, DataService, dtoItem));"); sbPublicProperties.AppendLine($"\t\t\t\t\t}}"); } else { sbPublicProperties.AppendLine($"\t\t\t\t\t{privateVariableName} = new {modelTypeName}(Log, DataService, _dto.{dtoName});"); } } sbPublicProperties.AppendLine($"\t\t\t\t}}"); sbPublicProperties.AppendLine(string.Empty); sbPublicProperties.AppendLine($"\t\t\t\treturn {privateVariableName};"); sbPublicProperties.AppendLine($"\t\t\t}}"); sbPublicProperties.AppendLine($"\t\t}}"); sbPublicProperties.AppendLine(string.Empty); }
private string GeneratePartialMethods(string dbContextName, IEntityType entity, string efEntityNamespacePrefix, IList <IEntityNavigation> excludedNavigationProperties, bool allowUpsertDuringPut) { StringBuilder sb = new StringBuilder(); string tablenameSchema = Inflector.Humanize(entity.ClrType.Name); string tablenameNoSchema = tablenameSchema; string tablenamePlural = Inflector.Pluralize(entity.ClrType.Name); string entityTypeName = $"{efEntityNamespacePrefix}.{tablenameSchema}"; sb.AppendLine(string.Empty); sb.AppendLine($"\t\t//partial void RunCustomLogicAfterInsert(ref {entityTypeName} newDBItem, ref IRepositoryActionResult<{entityTypeName}> result) {{}}"); sb.AppendLine(string.Empty); sb.AppendLine($"\t\t//partial void RunCustomLogicAfterUpdatePatch(ref {entityTypeName} updatedDBItem, ref IRepositoryActionResult<{entityTypeName}> result) {{}}"); sb.AppendLine(string.Empty); if (allowUpsertDuringPut) { sb.AppendLine($"\t\tpartial void RunCustomLogicAfterUpdatePut(ref {entityTypeName} updatedDBItem, ref IRepositoryActionResult<{entityTypeName}> result)"); sb.AppendLine($"\t\t{{"); sb.AppendLine($"\t\t\tif (result.Status == Enums.RepositoryActionStatus.NotFound)"); sb.AppendLine($"\t\t\t{{\t// An update/PUT was attempted when it should have been a create/POST."); sb.AppendLine($"\t\t\t\tvar localDBItem = updatedDBItem;"); sb.AppendLine($"\t\t\t\tvar insertResult = RunSync<IRepositoryActionResult<{entityTypeName}>>(() => Repo.InsertAsync(localDBItem));"); sb.AppendLine($"\t\t\t\tif (insertResult.Status == Enums.RepositoryActionStatus.Created)"); sb.AppendLine($"\t\t\t\t{{ // Insert worked"); sb.AppendLine($"\t\t\t\t\tresult = new RepositoryActionResult<{entityTypeName}>(insertResult.Entity, Enums.RepositoryActionStatus.Updated);"); sb.AppendLine($"\t\t\t\t}}"); sb.AppendLine($"\t\t\t}}"); sb.AppendLine($"\t\t}}"); } else { sb.AppendLine($"\t\t//partial void RunCustomLogicAfterUpdatePut(ref {entityTypeName} updatedDBItem, ref IRepositoryActionResult<{entityTypeName}> result) {{}}"); } string signatureWithFieldTypes = GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey()); string signatureWithoutFieldTypes = GetSignatureWithoutFieldTypes(string.Empty, entity.FindPrimaryKey(), lowercasePkNameFirstChar: true); sb.AppendLine(string.Empty); sb.AppendLine($"\t\t// partial void RunCustomLogicBeforeUpdatePut(ref {entityTypeName} updatedDBItem, {signatureWithFieldTypes})"); sb.AppendLine($"\t\t// {{"); sb.AppendLine($"\t\t// \tvar existingDBItem = Utils.AsyncHelper.RunSync<{entityTypeName}>(() => Repo.Get_{tablenameSchema}Async({signatureWithoutFieldTypes}, 1));"); sb.AppendLine($"\t\t// \tif (existingDBItem != null)"); sb.AppendLine($"\t\t// \t{{\t// Do not allow the user to change the \"MySpecialField\" value."); sb.AppendLine($"\t\t// \t\tupdatedDBItem.MySpecialField = existingDBItem.MySpecialField;"); sb.AppendLine($"\t\t// \t}}"); sb.AppendLine($"\t\t// }}"); sb.AppendLine(string.Empty); sb.AppendLine("\t\t///// <summary>"); sb.AppendLine("\t\t///// A sample implementation of custom logic used to either manipulate a DTO item or include related entities."); sb.AppendLine("\t\t///// </summary>"); sb.AppendLine("\t\t///// <param name=\"dbItem\"></param>"); sb.AppendLine("\t\t///// <param name=\"id\"></param>"); sb.AppendLine("\t\t///// <param name=\"numChildLevels\"></param>"); sb.AppendLine($"\t\t// partial void RunCustomLogicOnGetEntityByPK(ref {entityTypeName} dbItem, {GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())}, int numChildLevels)"); sb.AppendLine("\t\t// {"); sb.AppendLine($"\t\t\t// if (numChildLevels > 1)"); sb.AppendLine($"\t\t\t// {{"); sb.AppendLine($"\t\t\t\t// int[] orderLineItemIds = dbItem.OrderLineItems.Select(x => x.OrderLineItemId).ToArray();"); sb.AppendLine(string.Empty); sb.AppendLine($"\t\t\t\t// var lineItemDiscounts = Repo.{dbContextName}.OrderLineItemDiscounts.Where(x => orderLineItemIds.Contains(x.OrderLineItemId)).ToList();"); sb.AppendLine(string.Empty); sb.AppendLine($"\t\t\t\t// foreach (var lineItemDiscount in lineItemDiscounts)"); sb.AppendLine($"\t\t\t\t// {{ // Find the match and add the item to it."); sb.AppendLine($"\t\t\t\t\t// var orderLineItem = dbItem.OrderLineItems.Where(x => x.OrderLineItemId == lineItemDiscount.OrderLineItemId).FirstOrDefault();"); sb.AppendLine(string.Empty); sb.AppendLine($"\t\t\t\t\t// if (orderLineItem == null)"); sb.AppendLine($"\t\t\t\t\t// {{"); sb.AppendLine($"\t\t\t\t\t\t// throw new Microsoft.EntityFrameworkCore.ObjectNotFoundException($\"Unable to locate matching OrderLineItem record for {{lineItemDiscount.OrderLineItemId}}.\""); sb.AppendLine($"\t\t\t\t\t// }}"); sb.AppendLine(string.Empty); sb.AppendLine($"\t\t\t\t\t// orderLineItem.LineItemDiscounts.Add(lineItemDiscount);"); sb.AppendLine($"\t\t\t\t// }}"); sb.AppendLine($"\t\t\t// }}"); sb.AppendLine(string.Empty); sb.AppendLine("\t\t// }"); sb.AppendLine(string.Empty); sb.AppendLine("\t\t///// <summary>"); sb.AppendLine("\t\t///// A sample implementation of custom logic used to filter on a field that exists in a related, parent, table."); sb.AppendLine("\t\t///// </summary>"); sb.AppendLine("\t\t///// <param name=\"dbItems\"></param>"); sb.AppendLine("\t\t///// <param name=\"filterList\"></param>"); sb.AppendLine($"\t\t//partial void RunCustomLogicAfterGetQueryableList(ref IQueryable<{efEntityNamespacePrefix}.{tablenameNoSchema}> dbItems, ref List<string> filterList)"); sb.AppendLine("\t\t//{"); sb.AppendLine($"\t\t//\tvar queryableFilters = filterList.ToQueryableFilter();"); sb.AppendLine($"\t\t//\tvar myFilterCriterion = queryableFilters.Where(y => y.Member.ToLowerInvariant() == \"<myFieldName>\").FirstOrDefault(); // Examine the incoming filter for the presence of a field name which does not exist on the target entity."); sb.AppendLine(string.Empty); sb.AppendLine($"\t\t//\tif (myFilterCriterion != null)"); sb.AppendLine($"\t\t//\t{{ // myFieldName is a criterion that has to be evaluated at a level other than our target entity."); sb.AppendLine("\t\t//\t\tdbItems = dbItems.Include(x => x.myFKRelatedEntity).Where(x => x.myFKRelatedEntity.myFieldName == new Guid(myFilterCriterion.Value));"); sb.AppendLine($"\t\t//\t\tqueryableFilters.Remove(myFilterCriterion); // The evaluated criterion needs to be removed from the list of filters before we invoke the ApplyFilter() extension method."); sb.AppendLine($"\t\t//\t\tfilterList = queryableFilters.ToQueryableStringList();"); sb.AppendLine("\t\t//\t}"); sb.AppendLine("\t\t//}"); sb.AppendLine($"\t}}\r\n}}"); return(sb.ToString()); }
private void BuildReverseNavigation(IList <IEntityNavigation> excludedNavigationProperties, IEntityType entity, INavigation foreignKey, ref StringBuilder sbPrivateProperties, ref StringBuilder sbPublicProperties) { //string tableName = table.GetNameHumanCaseSingular(false); string entityName = foreignKey.Name; string name = foreignKey.ClrType.Name; string nameHumanized = name; if (nameHumanized.Length >= 2) { nameHumanized = Inflector.Humanize(nameHumanized); } bool useCollection = (name.Equals("ICollection`1")); //if (foreignKey.Relationship == Relationship.ManyToOne) if (useCollection) { name = Inflector.Humanize(foreignKey.Name); // foreignKey.RefTableHumanCase; } //bool excludeCircularReferenceNavigationIndicator = foreignKey.ExcludeCircularReferenceNavigationIndicator(excludedNavigationProperties); bool excludeCircularReferenceNavigationIndicator = IsEntityInExcludedReferenceNavigionationProperties(excludedNavigationProperties, name); if (excludeCircularReferenceNavigationIndicator) { sbPrivateProperties.AppendLine($"\t\t// Excluding '{name}' per configuration setting."); return; } //string publicPropertyName = foreignKey.RefTableHumanCase.Replace($"{foreignKey.TableSchema}_", string.Empty); string publicPropertyName = name; // foreignKey.RefTableHumanCase.Replace($"{foreignKey.RefTableSchema}_", string.Empty); string privateVariableName = $"_{publicPropertyName.Substring(0, 1).ToLower()}{publicPropertyName.Substring(1)}"; //bool useCollection = foreignKey.Relationship == Library.Enums.Relationship.ManyToOne; //string modelTypeName = modelTypeName = foreignKey.FullTableName.Replace($"{foreignKey.TableSchema}_", string.Empty); string modelTypeName = foreignKey.ForeignKey.PrincipalEntityType.ClrType.Name; string objectType; if (excludeCircularReferenceNavigationIndicator) { // This item is configured to be excluded from navigation properties. sbPrivateProperties.Append($"\t\t// "); } else { sbPrivateProperties.Append($"\t\t"); } if (useCollection) { objectType = $"List<I{foreignKey.ForeignKey.DeclaringEntityType.ClrType.Name}>"; sbPrivateProperties.AppendLine($"private {objectType} {privateVariableName} = null; // Reverse Navigation"); } else { objectType = $"I{modelTypeName}"; //objectType = foreignKey.FullTableName.Replace($"{foreignKey.TableSchema}_", string.Empty); sbPrivateProperties.AppendLine($"private {modelTypeName} {privateVariableName} = null; // Reverse Navigation"); } string dtoName = nameHumanized; string initializer = useCollection ? "()" : ""; if (entityName == publicPropertyName) { publicPropertyName = $"{entityName}1"; } sbPublicProperties.AppendLine($"\t\tpublic virtual {objectType} {publicPropertyName}"); sbPublicProperties.AppendLine($"\t\t{{"); sbPublicProperties.AppendLine($"\t\t\tget"); sbPublicProperties.AppendLine($"\t\t\t{{"); if (excludeCircularReferenceNavigationIndicator) { sbPublicProperties.AppendLine($"\t\t\t\tif ({privateVariableName} == null)"); sbPublicProperties.AppendLine($"\t\t\t\t{{"); sbPublicProperties.AppendLine($"\t\t\t\t\tOnLazyLoadRequest(this, new LoadRequest{entityName}(nameof({publicPropertyName})));"); sbPublicProperties.AppendLine($"\t\t\t\t}}"); } else { sbPublicProperties.AppendLine($"\t\t\t\tif ({privateVariableName} == null && _dto != null)"); sbPublicProperties.AppendLine($"\t\t\t\t{{\t// The core DTO object is loaded, but this property is not loaded."); sbPublicProperties.AppendLine($"\t\t\t\t\tif (_dto.{dtoName} != null)"); sbPublicProperties.AppendLine($"\t\t\t\t\t{{\t// The core DTO object has data for this property, load it into the model."); if (useCollection) { sbPublicProperties.AppendLine($"\t\t\t\t\t\t{privateVariableName} = new {objectType}();"); sbPublicProperties.AppendLine($"\t\t\t\t\t\tforeach (var dtoItem in _dto.{name})"); sbPublicProperties.AppendLine($"\t\t\t\t\t\t{{"); sbPublicProperties.AppendLine($"\t\t\t\t\t\t\t{privateVariableName}.Add(new {modelTypeName}(Log, DataService, dtoItem));"); sbPublicProperties.AppendLine($"\t\t\t\t\t\t}}"); } else { sbPublicProperties.AppendLine($"\t\t\t\t\t\t{privateVariableName} = new {modelTypeName}(Log, DataService, _dto.{dtoName});"); } sbPublicProperties.AppendLine($"\t\t\t\t\t}}"); sbPublicProperties.AppendLine($"\t\t\t\t\telse"); sbPublicProperties.AppendLine($"\t\t\t\t\t{{\t// Trigger the load data request - The core DTO object is loaded and does not have data for this property."); sbPublicProperties.AppendLine($"\t\t\t\t\t\tOnLazyLoadRequest(this, new LoadRequest{entityName}(nameof({publicPropertyName})));"); sbPublicProperties.AppendLine($"\t\t\t\t\t}}"); sbPublicProperties.AppendLine($"\t\t\t\t}}"); } sbPublicProperties.AppendLine(string.Empty); sbPublicProperties.AppendLine($"\t\t\t\treturn {privateVariableName};"); sbPublicProperties.AppendLine($"\t\t\t}}"); sbPublicProperties.AppendLine($"\t\t}}"); sbPublicProperties.AppendLine(string.Empty); }
public string GenerateReverseNav(bool prependSchemaNameIndicator, bool dtoIncludeRelatedObjects, IEntityType entity, IList <IEntityNavigation> excludedNavigationProperties) { StringBuilder sb = new StringBuilder(); SortedSet <IForeignKey> fklist = entity.ForeignKeys; // CGHInflector myInflector = new CGHInflector(); if (dtoIncludeRelatedObjects) { foreach (var reverseFK in entity.Navigations) { string name = reverseFK.DeclaringType.ClrType.Name; string humanCase = Inflector.Humanize(name); sb.Append("\t\t"); //bool excludeCircularReferenceNavigationIndicator = reverseFK.ExcludeCircularReferenceNavigationIndicator(excludedNavigationProperties); bool excludeCircularReferenceNavigationIndicator = IsEntityInExcludedReferenceNavigionationProperties(excludedNavigationProperties, name); if (excludeCircularReferenceNavigationIndicator) { // Include the line, but comment it out. sb.Append("// "); } string reverseFKName = reverseFK.ForeignKey.PrincipalEntityType.ClrType.Name; // We don't have the same Relationship.OneToOne status as from the reverse poco type. EntityFramework just gives us the type of ICollection'1 or the field name //if (reverseFK.ClrType == Library.Enums.Relationship.OneToOne) if (!reverseFK.ClrType.Name.Equals("ICollection`1")) { sb.Append($"public virtual {reverseFKName} {Inflector.Pascalize(reverseFKName)} {{ get; set; }} // One to One mapping"); // Foreign Key } else { sb.Append($"public virtual System.Collections.Generic.ICollection<{reverseFK.ForeignKey.DeclaringEntityType.ClrType.Name}> {reverseFK.Name} {{ get; set; }} // Many to many mapping"); // Foreign Key } if (excludeCircularReferenceNavigationIndicator) { sb.AppendLine(EXCLUDEPERNAVIGATIONPROPERTYCONFIGURATION); } else { sb.AppendLine(string.Empty); } } // With Reverse POCO, we had to go forward and backward. However, by using entity.Navigations, the following seems duplicative. //var orderedFKs = entity.ForeignKeys.OrderBy(x => x.DependentToPrincipal.Name).ToList(); //foreach (var fk in orderedFKs) //{ // string principalEntityTypeName = fk.PrincipalEntityType.ClrType.Name; // string propertyName = ""; // if (string.IsNullOrEmpty(principalEntityTypeName)) // { // sb.AppendLine($"// ERROR: {entity.Name} foreign key for {fk.PrincipalEntityType.Name}: A PrincipalEntityType.Name is null"); // } // else // { // propertyName = principalEntityTypeName.Humanize(); // Humanize the name // } // sb.Append("\t\t"); // // TODO: Not sure if this is correct. Does the excludedNavigationProperties exclude by table/ref or just by table? Or just by column? // //bool excludeCircularReferenceNavigationIndicator = fk.ExcludeCircularReferenceNavigationIndicator(excludedNavigationProperties); // bool excludeCircularReferenceNavigationIndicator = IsEntityInExcludedReferenceNavigionationProperties(excludedNavigationProperties, propertyName); // if (excludeCircularReferenceNavigationIndicator) // { // Include the line, but comment it out. // sb.Append("// "); // } // sb.Append($"public virtual {principalEntityTypeName} {propertyName} {{ get; set; }} "); // Foreign Key // if (excludeCircularReferenceNavigationIndicator) // { // sb.AppendLine(EXCLUDEPERNAVIGATIONPROPERTYCONFIGURATION); // } // else // { // sb.AppendLine(string.Empty); // } //} } return(sb.ToString()); }
public string GenerateWebApiDataServiceInterfaceBody( string dtoNamespacePrefix, string defaultCriteria, bool prependSchemaNameIndicator, IList <IEntityType> EntityTypes) { StringBuilder sb = new StringBuilder(); StringBuilder sbGetAllPages = new StringBuilder(); StringBuilder sbGetPageData = new StringBuilder(); StringBuilder sbGetByPK = new StringBuilder(); StringBuilder sbCreate = new StringBuilder(); StringBuilder sbUpdate = new StringBuilder(); StringBuilder sbDelete = new StringBuilder(); sbGetAllPages.AppendLine($"\t\t#region GetAllPages{Environment.NewLine}"); sbGetPageData.AppendLine($"\t\t#region GetPageData{Environment.NewLine}"); sbGetByPK.AppendLine($"\t\t#region Get By PK{Environment.NewLine}"); sbCreate.AppendLine($"\t\t#region Create{Environment.NewLine}"); sbUpdate.AppendLine($"\t\t#region Update{Environment.NewLine}"); sbDelete.AppendLine($"\t\t#region Delete{Environment.NewLine}"); foreach (var entity in EntityTypes) { string defaultCriteriaTableNameSubstituted = defaultCriteria.Replace("[tablename]", Inflector.Humanize(entity.ClrType.Name)); var defaultCriteriaAsTypeAndFieldNameList = GetDefaultCriteriaListForWebApi(defaultCriteriaTableNameSubstituted); string tableName = Inflector.Pascalize(entity.ClrType.Name); var criteriaFieldsThatExistInTable = FilterFieldTypeAndNamesByExistingColumns(entity, defaultCriteriaAsTypeAndFieldNameList); var criteriaTypeAndFieldNamesConcatenated = GetFieldTypeAndNamesConcatenated(criteriaFieldsThatExistInTable); string keylist = string.Join("}/{", entity.GetKeys().Select(k => k.Properties[0].Name)); // Get All Pages sbGetAllPages.Append($"\t\tTask<IList<{dtoNamespacePrefix}.{tableName}>> GetAllPages{Inflector.Pluralize(entity.ClrType.Name)}Async("); if (!string.IsNullOrEmpty(criteriaTypeAndFieldNamesConcatenated)) { sbGetAllPages.Append($"{criteriaTypeAndFieldNamesConcatenated}, "); } sbGetAllPages.AppendLine($"string sort = null);{Environment.NewLine}"); // Get One Page - Part 1 sbGetPageData.AppendLine($"\t\tTask<IHttpCallResultCGHT<IPageDataT<IList<{dtoNamespacePrefix}.{tableName}>>>> Get{Inflector.Pluralize(entity.ClrType.Name)}Async(IPageDataRequest pageDataRequest);{Environment.NewLine}"); // Get One Page - Part 2 sbGetPageData.Append($"\t\tTask<IHttpCallResultCGHT<IPageDataT<IList<{dtoNamespacePrefix}.{tableName}>>>> Get{Inflector.Pluralize(entity.ClrType.Name)}Async("); if (!string.IsNullOrEmpty(criteriaTypeAndFieldNamesConcatenated)) { sbGetPageData.Append($"{criteriaTypeAndFieldNamesConcatenated}, "); } sbGetPageData.AppendLine($"string sort = null, int page = 1, int pageSize = 100);{Environment.NewLine}"); sbGetByPK.AppendLine($"\t\tTask<IHttpCallResultCGHT<{dtoNamespacePrefix}.{tableName}>> Get{Inflector.Humanize(entity.ClrType.Name)}Async({GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())}, int numChildLevels);{Environment.NewLine}"); sbCreate.AppendLine($"\t\tTask<IHttpCallResultCGHT<{dtoNamespacePrefix}.{tableName}>> Create{Inflector.Humanize(entity.ClrType.Name)}Async({dtoNamespacePrefix}.{tableName} item);{Environment.NewLine}"); sbUpdate.AppendLine($"\t\tTask<IHttpCallResultCGHT<{dtoNamespacePrefix}.{tableName}>> Update{Inflector.Humanize(entity.ClrType.Name)}Async({dtoNamespacePrefix}.{tableName} item);{Environment.NewLine}"); sbDelete.AppendLine($"\t\tTask<IHttpCallResultCGHT<{dtoNamespacePrefix}.{tableName}>> Delete{Inflector.Humanize(entity.ClrType.Name)}Async({GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())});{Environment.NewLine}"); } sbGetAllPages.AppendLine($"{Environment.NewLine}\t\t#endregion GetAllPages{Environment.NewLine}"); sb.AppendLine(sbGetAllPages.ToString()); sbGetPageData.AppendLine($"{Environment.NewLine}\t\t#endregion GetPageData{Environment.NewLine}"); sb.AppendLine(sbGetPageData.ToString()); sbGetByPK.AppendLine($"{Environment.NewLine}\t\t#endregion Get By PK{Environment.NewLine}"); sb.AppendLine(sbGetByPK.ToString()); sbCreate.AppendLine($"{Environment.NewLine}\t\t#endregion Create{Environment.NewLine}"); sb.AppendLine(sbCreate.ToString()); sbUpdate.AppendLine($"{Environment.NewLine}\t\t#endregion Update{Environment.NewLine}"); sb.AppendLine(sbUpdate.ToString()); sbDelete.AppendLine($"{Environment.NewLine}\t\t#endregion Delete{Environment.NewLine}"); sb.AppendLine(sbDelete.ToString()); return(sb.ToString()); }