private (string Cut, string Singular, string Plural) GetActionGroup(AppNode action, Pluralizer pluralizer = null) { pluralizer = pluralizer ?? new Pluralizer(); switch (action.NodeType) { case AppNodeType.Query: case AppNodeType.ListQuery: var cut = GetQueryBaseName(action, trimGet: true, trimList: true); return(cut, pluralizer.Singularize(cut), pluralizer.Pluralize(cut)); case AppNodeType.BoolQuery: // Is... supposed form: Question + Entity + Adjectives // others supposed form: Question + Action + Entity cut = string.Join("", action.NameWords.Skip(2)); return(cut, pluralizer.Singularize(cut), pluralizer.Pluralize(cut)); case AppNodeType.Command: case AppNodeType.InsertCommand: case AppNodeType.UpdateCommand: case AppNodeType.DeleteCommand: // supposed form: Action + Entity cut = string.Join("", action.NameWords.Skip(1)); return(cut, pluralizer.Singularize(cut), pluralizer.Pluralize(cut)); default: return(null, null, null); } }
public static SyntaxNode CreatEFCoreDefaultInterfaceService(DatabaseServiceModel model, GeneratorModel generator) { IPluralize pluralizer = new Pluralizer(); string namespace_string = generator.NamespaceString; List <String> usingStrings = model.ServiceUsingList; string serviceName = model.ServiceName; string dbName = generator.ApplicationDbName; var EFCoreString = new StringBuilder(); if (usingStrings.Count > 0) { foreach (var usingstring in usingStrings) { EFCoreString.Append($@"using {usingstring};"); } } EFCoreString.Append($@" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace {namespace_string}.Service.Factory {{ public interface I{serviceName}Service {{ Task<{model.ClassName}> Get{serviceName}Async(Guid id); Task<List<{model.ClassName}>> Get{pluralizer.Pluralize(serviceName)}Async(string query); "); if (model.RelationDbList.Count > 0) { foreach (var item in model.RelationDbList) { EFCoreString.Append($@" Task<List<{model.ClassName}>> Get{pluralizer.Pluralize(serviceName)}From{item.RelationItemName}IdAsync(Guid id); "); } } EFCoreString.Append($@" Task<int> Update{serviceName}Async({model.ClassName} {model.ClassName.ToLower()}); Task<int> Delete{serviceName}Async(params {model.ClassName}[] {model.DbName.ToLower()}); }} }}"); var newNode = SyntaxFactory.ParseSyntaxTree(EFCoreString.ToString()).GetRoot().NormalizeWhitespace(); return(newNode); }
public void InputData() { var input = Resources.InputData.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in input) { var singular = line.Split(',')[0]; var plural = line.Split(',')[1]; Assert.Equal(plural, _pluralizer.Pluralize(singular)); Assert.Equal(plural, _pluralizer.Pluralize(plural)); Assert.Equal(singular, _pluralizer.Singularize(plural)); Assert.Equal(singular, _pluralizer.Singularize(singular)); } }
public SelectTests(Northwind northwind) { this.northwind = northwind; IPluralize pluralize = new Pluralizer(); Jaunty.TableNameMapper += type => pluralize.Pluralize(type.Name); }
private IEnumerable <T> MapInvocation(IInvocationStatement invocation, IClass source, CodeFirstMetadata parent) { var newItems = new List <T>(); if (invocation == null) { return(newItems); } if (source == null) { return(newItems); } var name = invocation.MethodName; // English language convention used here if (name.StartsWith("Add")) { name = name.SubstringAfter("Add"); var plural = Pluralizer.Pluralize(name); var current = source; if (current != null) { var property = GetPropertyUseBase(plural, ref current); if (property != null) { var newItem = Activator.CreateInstance <T>(); newItem.Parent = parent; SetNewItemProperties(newItem, invocation); newItems.Add(newItem); } } } return(newItems); }
private void ImportData <T>(T modelType, string rootPath) { if (db.GetCollection <T>((modelType as Type).Name).EstimatedDocumentCount() == 0) { var options = new { WriteIndented = true, }; Pluralizer pluralizer = new Pluralizer(); var fileName = pluralizer.Pluralize((modelType as Type).Name); var path = Path.Combine(rootPath, "Data", "Test", $"{fileName}.json"); if (File.Exists(path)) { var command = $" /d Beauty /c {fileName} /file {path} /mode:merge --jsonArray"; var p = Process.Start("mongoimport", command); p.StartInfo.FileName = "mongoimport.exe"; p.StartInfo.Arguments = command; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data); p.Start(); p.BeginOutputReadLine(); } } }
ContentTypeGroupResponseItem GetItem(ContentTypeGroupDescriptor contentTypeGroup) { var name = contentTypeGroup.Type.GetCustomAttribute <DisplayAttribute>()?.Name ?? contentTypeGroup.Type.Name; string pluralName; if (name.Contains(':') && !contentTypeGroup.Id.Contains(':')) { var nameSplit = name.Split(':'); name = nameSplit.First(); pluralName = nameSplit.Last(); } else { if (name.Length >= 2 && name.StartsWith('I') && char.IsUpper(name[1])) { name = name.Substring(1); } name = Humanizer.Humanize(name); pluralName = Pluralizer.Pluralize(name); } var item = new ContentTypeGroupResponseItem { Id = contentTypeGroup.Id, Name = name, LowerCaseName = name.Substring(0, 1).ToLower() + name.Substring(1), PluralName = pluralName, LowerCasePluralName = pluralName.Substring(0, 1).ToLower() + pluralName.Substring(1), ContentTypes = ContentTypeGroupMatcher.GetContentTypesFor(contentTypeGroup.Id).Select(t => t.Id).ToList().AsReadOnly(), }; return(item); }
private static IEnumerable <string> GenerateCsharpSource(string xmlContent, string @namespace = null, AccessorType accessorType = AccessorType.Public) { IPluralize pluralizer = new Pluralizer(); var result = new List <string>(); var hasNamespace = !string.IsNullOrEmpty(@namespace); var list = Parse(xmlContent, accessorType); list.Reverse(); // From child to parent foreach (var item in list) { var sb = new StringBuilder(); sb.AppendLine($"{(!hasNamespace ? Tabs(0) : Tabs(1))}{GetAccessor(accessorType)} class {item.CsharpName}"); sb.AppendLine($"{(!hasNamespace ? Tabs(0) : Tabs(1))}{{"); foreach (var mem in item.Members) { if (mem.IsList) { var plMemName = pluralizer.Pluralize(mem.CsharpName); sb.AppendLine($"{(!hasNamespace ? Tabs(1) : Tabs(2))}{GetAccessor(accessorType)} List<{mem.Type}> {plMemName} {{ get; set; }}"); } else { sb.AppendLine($"{(!hasNamespace ? Tabs(1) : Tabs(2))}{GetAccessor(accessorType)} {mem.Type} {mem.CsharpName} {{ get; set; }}"); } } sb.AppendLine($"{(!hasNamespace ? Tabs(0) : Tabs(1))}}}"); result.Add(sb.ToString()); } return(result); }
/// <summary> /// Constructs the Context with the Database Options values provided /// </summary> /// <param name="options">The connection string and name of the Database to use</param> public ContextProvider(IDatabaseOptions options) { // Create the (Singleton) Client, Database and then return the Context ready for use Context = MongoProvider .CreateMongoClient(options.ConnectionString) .GetDatabase(options.DatabaseName) .GetCollection <T>(Pluralizer.Pluralize(typeof(T).Name)); }
public CategoryViewModel(DbObject model, MetadataViewModelBase parent, MetadataType type) : base(parent, true) { Type = type; _model = model; _categoryName = _pluralizer.Pluralize(type.ToString()); ExpandChanged += OnExpandChanged; }
public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance) { string typeName = instance.EntityType.Name; IPluralize pluralizer = new Pluralizer(); instance.Table(pluralizer.Pluralize(typeName)); }
public virtual void Configure(EntityTypeBuilder <T> builder) { var tableName = typeof(T).Name; var ps = new Pluralizer(); builder.ToTable(ps.Pluralize(tableName)); builder.HasKey(e => e.Id); builder.Ignore(e => e.Events); }
public BaseMongoRepository(IMongoDatabase database) { Database = database; var pluralizer = new Pluralizer(); _collectionName = pluralizer.Pluralize(typeof(T).Name.Replace("Entity", "")); Collection = Database.GetCollection <T>(_collectionName); CreateIndex(AttributeProcessor.GetUniqueFields <T>(typeof(UniqueFieldAttribute))); }
public static string Pluralize(this string singular) { if (singular == null) { throw new ArgumentNullException(nameof(singular)); } return(Pluralizer.Pluralize(singular)); }
public void AddPluralizingTableName() { Pluralizer pluralizer = new Pluralizer(); foreach (IMutableEntityType entityType in _modelBuilder.Model.GetEntityTypes()) { string tableName = entityType.Relational().TableName; entityType.Relational().TableName = pluralizer.Pluralize(tableName); } }
/// <summary> /// Pluralizing table name like Post to Posts or Person to People /// </summary> /// <param name="modelBuilder"></param> public static void AddPluralizingTableNameConvention(this Microsoft.EntityFrameworkCore.ModelBuilder modelBuilder) { Pluralizer pluralizer = new Pluralizer(); foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes()) { string tableName = entityType.Relational().TableName; entityType.Relational().TableName = pluralizer.Pluralize(tableName); } }
public static string PluralizeIfNeeded(this string toPluralizeIfNeeded, IList pluralizeIfMoreThanOne) { if (pluralizeIfMoreThanOne == null || pluralizeIfMoreThanOne.Count < 1) { return(toPluralizeIfNeeded); } var toPlural = new Pluralizer(); return(toPlural.Pluralize(toPluralizeIfNeeded)); }
/// <summary> /// Pluralizing table name like Post to Posts or Person to People /// </summary> /// <param name="modelBuilder"></param> public static void AddPluralizingTableNameConvention(this ModelBuilder modelBuilder) { Pluralizer pluralizer = new Pluralizer(); foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes()) { string tableName = entityType.GetTableName(); entityType.SetTableName(pluralizer.Pluralize(tableName)); } }
public IEnumerable <FieldResponse> GetAllForForm(string id) { var result = new List <FieldResponse>(); foreach (var field in FieldProvider.GetAllFor(id)) { if (!field.AutoGenerate) { continue; } var control = ControlMatcher.GetFor(field.Type, field.UIHints); var embeddedFormId = FormProvider.GetAll().FirstOrDefault(f => f.Type == field.Type); if (control == null && embeddedFormId == null) { Logger.LogInformation($"Could not find control for {id} {field.Id}"); continue; } var label = field.Label; if (label == null) { label = field.Id; label = Humanizer.Humanize(field.Id); if (label.EndsWith(" ids")) { label = label.Substring(0, label.Length - " ids".Length); label = Pluralizer.Pluralize(label); } else if (label.EndsWith(" id")) { label = label.Substring(0, label.Length - " id".Length); } } var singularLabel = Singularizer.Singularize(label); result.Add(new FieldResponse { Id = field.Id, Label = label, SingularLabel = singularLabel, CamelCaseId = CamelCaseNamingStrategy.GetPropertyName(field.Id, false), Control = control, EmbeddedFormId = embeddedFormId?.Id, IsSortable = field.IsSortable, Group = field.Group, }); } return(result); }
public async override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { XElement HandleExpandoField(XElement acc, KeyValuePair <string, object> fields) { XElement element = null; if (fields.Value is IEnumerable <object> innerList) { var children = innerList.Select((i) => ((ExpandoObject)i).Aggregate(new XElement($"{_pluralizer.Singularize(fields.Key)}"), HandleExpandoField)); element = new XElement(_pluralizer.Pluralize(fields.Key), children); } else { element = fields.Value is ExpandoObject expando ? expando.Aggregate(new XElement(fields.Key), HandleExpandoField) : new XElement(fields.Key, fields.Value); } acc.Add(element); return(acc); }; XElement MultipleItemsToXml(string name, IEnumerable <object> itemCollection) { var children = itemCollection.Select((i) => ((ExpandoObject)i).Aggregate(new XElement($"{_pluralizer.Singularize(name)}"), HandleExpandoField)); var root = new XElement(_pluralizer.Pluralize(name), children); return(root); } XElement SingleItemToXml(string name, ExpandoObject obj) { return(obj.Aggregate(new XElement(name), HandleExpandoField)); } var itemName = _pluralizer.Singularize(ObjectHelper.GetCollectionFromPath(context.HttpContext.Request.Path.Value)); var xml = context.Object is IEnumerable <object> col?MultipleItemsToXml(itemName, col) : SingleItemToXml(itemName, context.Object as ExpandoObject); await context.HttpContext.Response.WriteAsync(xml.ToString()); }
public void PlurallyShouldUseSameEnglishLocaleForAll() { var plurallyGB = new Pluralizer(new CultureInfo("en-GB")); var plurallyUS = new Pluralizer(new CultureInfo("en-US")); // Assert the results are the same on the pluralization var pluralGB = plurallyGB.Pluralize("test"); var pluralUS = plurallyUS.Pluralize("test"); // Same results for English Assert.Equal(pluralGB, pluralUS); }
private string GetQueryApiUrl(AppNode queryNode) { var domain = queryNode.GetDomainName(); var pluralizer = new Pluralizer(); var route = GetQueryRoutePlaceholder(queryNode, pluralizer.Pluralize(domain), pluralizer.Singularize(domain)); var suffix = queryNode.IsListQuery ? "" : "1"; var url = $"{_config.ApiUrlPrefix}/{domain.ToLower()}/{route}/{suffix}" .TrimEnd('/') .Replace("//", "/"); return(url); }
public virtual void Configure(EntityTypeBuilder <TEntity> builder) { builder.ToTable(Pluralizer.Pluralize(typeof(TEntity).Name)); builder.Property <bool>(nameof(DataModel <TId> .IsDeleted)) .IsRequired(true) .HasDefaultValue(false); builder.Property <DateTime?>(nameof(DataModel <TId> .DeletedOn)) .IsRequired(false); builder.HasQueryFilter(x => Microsoft.EntityFrameworkCore.EF.Property <bool>(x, nameof(DataModel <TId> .IsDeleted)) == false); }
private SwaggerRoot DeleteAllPathsNotRelatedTo(SwaggerRoot swaggerRoot, string entityName) { var entityNamePlural = pluralizer.Pluralize(entityName); var prefix = $"/{entityNamePlural.ToLowerInvariant()}/"; var swaggerCopy = Utils.Utils.Clone(swaggerRoot); swaggerRoot .Paths .Keys .Where(p => !Utils.Utils.InvariantStartsWith(p, prefix)) .ToList() .ForEach(p => swaggerCopy.Paths.Remove(p)); return(swaggerCopy.Paths.Any() ? swaggerCopy : null); }
private string Pluralize(string word) { string pluralForm = word; try { IPluralize pluralizer = new Pluralizer(); pluralForm = pluralizer.Pluralize(word); } catch { // sometimes VS has problems with loading Pluralize dll pluralForm = GetPlural(word); } return(pluralForm); }
public virtual void Configure(EntityTypeBuilder <TEntity> builder) { builder.ToTable(Pluralizer.Pluralize(typeof(TEntity).Name)); builder .Property <bool>(nameof(IDeletable.IsDeleted)) .IsRequired(true) .HasDefaultValue(false); builder .Property <DateTime?>(nameof(IDeletable.DeletedOn)) .IsRequired(false); builder .HasQueryFilter(x => EF.Property <bool>(x, nameof(IDeletable.IsDeleted)) == false); builder.HasKey(x => x.Id); builder.Property(x => x.Id).UseHiLo(); }
public async Task <IEnumerable <T> > GetItemsAsync(bool forceRefresh = false) { IEnumerable <T> _items = items; try { if (null == db) { throw new Exception($"GetItemsAsync<{typeof(T).Name}>: Database was not created"); } db.Database.EnsureCreated(); // TODO: Pluralize class name conveniently IPluralize plural = new Pluralizer(); string _class = plural.Pluralize($"{typeof(T).Name}"); var propertyInfo = db.GetType().GetProperty(_class); IEnumerable <T> _dbItems = null; if (null != propertyInfo) { IEnumerable <T> dbObject = (IEnumerable <T>)propertyInfo.GetValue(db); if (null != dbObject) { _dbItems = dbObject.ToList(); } else { System.Diagnostics.Debug.WriteLine($"Db: {_class} object is null reference"); } } else { System.Diagnostics.Debug.WriteLine($"Db: {_class} not found as public member of database"); } _items = null == _dbItems ? items : await Task.FromResult(_dbItems); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } return(await Task.FromResult(_items)); }
public DeleteTests() { var connectionString = "server=.;database=Northwind;trusted_connection=true;"; connection = new SqlConnection(connectionString); var pluralizer = new Pluralizer(); //Speedy.Pluralize = pluralizer.Pluralize; Speedy.SqlDialect = Speedy.Dialects.SqlServer; Speedy.TableNameMapper += type => { if (type == typeof(CustomerCustomerDemo)) { return("CustomerCustomerDemo"); } return(pluralizer.Pluralize(type.Name)); }; }
public void CaseChangeTests() { var EzDbConfig = AppSettings.Instance.ConfigurationFileName; if (File.Exists(EzDbConfig)) { var ezDbConfig = Core.Config.Configuration.FromFile(EzDbConfig); foreach (var item in ezDbConfig.PluralizerCrossReference) { Pluralizer.Instance.AddWord(item.SingleWord, item.PluralWord); } } CaseTestPluralize("ProductCurve", "ProductCurves"); CaseTestSingularize("ProductCurves", "ProductCurve"); var str = "PrioritizationCriterion".ToSingular(); var strPlural = "PrioritizationCriterion".ToPlural(); CaseTestSingularize("ConstructionStatus", "ConstructionStatus"); var pl = new Pluralizer(); Assert.True(pl.IsPlural("constructionStatuses"), "constructionStatuses should be Plural"); Assert.True(pl.IsPlural("OpStatuses"), "OpStatuses should be Plural"); Assert.True(pl.IsPlural("ScenarioCases"), "ScenarioCases should be Plural"); Assert.True(pl.IsPlural("IncreaseDecreases"), "IncreaseDecreases should be Plural"); Assert.False(pl.IsPlural("Virii"), "Virii should not be Plural"); Assert.False(pl.IsPlural("Car"), "Car should not be Plural"); Assert.True(pl.IsSingular("IncreaseDecrease"), "IncreaseDecrease should be Singular"); Assert.True(pl.IsSingular("lease"), "lease should be Singular"); Assert.True(pl.IsSingular("ScenarioCase"), "ScenarioCase should be Singular"); Assert.True(pl.IsSingular("OpStatus"), "OpStatus should be Singular"); Assert.True(pl.IsSingular("ConstructionStatus"), "ConstructionStatus should be Singular"); Assert.True(pl.IsSingular("Virus"), "Virus should be Singular"); Assert.False(pl.IsSingular("ScenarioCases"), "Virus should be not Singular"); Assert.True(!pl.Pluralize("Virus").Equals("Viruses"), "Virus plural should not be Viruses"); Assert.True(pl.Singularize("Viruses").Equals("Virus"), "Viruses singular should be Virus"); Assert.True("ThisIsWCFLand".ToSentenceCase().Equals("This Is WCF Land"), "ThisIsWCFLand should be 'This Is WCF Land'"); Assert.True("BOSSIsDACost".ToSentenceCase().Equals("BOSS Is DA Cost"), "BOSSIsDACost should be 'BOSS Is DA Cost'"); }
ContentTypeResponseItem GetItem(ContentTypeDescriptor contentType) { var name = contentType.Type.GetCustomAttribute <DisplayAttribute>()?.Name ?? contentType.Type.Name; string pluralName; if (name.Contains(':') && !contentType.Id.Contains(':')) { var nameSplit = name.Split(':'); name = nameSplit.First(); pluralName = nameSplit.Last(); } else { name = Humanizer.Humanize(name); pluralName = Pluralizer.Pluralize(name); } var singleton = SingletonProvider.Get(contentType.Id); var item = new ContentTypeResponseItem { Id = contentType.Id, Name = name, LowerCaseName = name.Substring(0, 1).ToLower() + name.Substring(1), PluralName = pluralName, LowerCasePluralName = pluralName.Substring(0, 1).ToLower() + pluralName.Substring(1), IsNameable = typeof(INameable).IsAssignableFrom(contentType.Type), NameablePropertyName = typeof(INameable).IsAssignableFrom(contentType.Type) ? CamelCaseNamingStrategy.GetPropertyName(NameExpressionParser.Parse(contentType.Type), false) : null, IsImageable = typeof(IImageable).IsAssignableFrom(contentType.Type), ImageablePropertyName = typeof(IImageable).IsAssignableFrom(contentType.Type) ? CamelCaseNamingStrategy.GetPropertyName(ImageExpressionParser.Parse(contentType.Type), false) : null, IsRoutable = typeof(IRoutable).IsAssignableFrom(contentType.Type), IsSingleton = singleton != null, Count = -1, ContentTypeActionModules = ContentTypeActionModuleProvider.GetContentTypeActionModulesFor(contentType.Id), ListActionModules = ListActionModuleProvider.GetListActionModulesFor(contentType.Id), ContentTypeGroups = ContentTypeGroupMatcher.GetContentTypeGroupsFor(contentType.Id).Select(t => t.Id).ToList().AsReadOnly(), }; return(item); }