public string ClassToTableName(string fullClassName) { string className = GetClassName(fullClassName); string toPlural = Inflector.Pluralize(className); return(toPlural); }
public static MigrationAction CreateForType <T>(Func <RavenJObject, RavenJObject> getReplacement) { var ma = new MigrationAction("Raven/DocumentsByEntityName", "Tag:" + Inflector.Pluralize(typeof(T).Name), getReplacement); return(ma); }
public NursingHomeAuditMap() { // ReSharper disable DoNotCallOverridableMethodsInConstructor var indexName = string.Format("IDX_{0}", EntityTableName); // ReSharper restore DoNotCallOverridableMethodsInConstructor Map(x => x.Action) .CustomType <EnumStringType <AuditType> >() .Length(20).Not.Nullable(); Map(x => x.OwnerType, "EntityTypeName") .Length(50) .Not.Nullable() .Index(indexName); Map(x => x.OwnerId, "Owner_Id") .Not.Nullable() .Index(indexName); Map(x => x.PropertyName) .Length(150) .Index(indexName); Map(x => x.OldPropertyValue).Length(500); Map(x => x.NewPropertyValue).Length(500); Map(x => x.CreateDate).Not.Nullable(); Map(x => x.ProviderId).Index(indexName); Cache.NonStrictReadWrite().Region(Inflector.Pluralize(typeof(NursingHomeAuditLog).Name)); }
public void Pluralize() { foreach (var pair in TestData) { Assert.AreEqual(Inflector.Pluralize(pair.Key), pair.Value); } }
public string GenerateSerializeCallFor(string namespacePostfix, string dtoNamespacePrefix, string httpVerb, bool prependSchemaNameIndicator, IEntityType entity) { StringBuilder sb = new StringBuilder(); string clientMethodCallPrefix = httpVerb.ToLowerInvariant() == "post" ? "Create" : "Update"; string serializeCallPostfix = httpVerb.ToLowerInvariant() == "post" ? "Post" : "Put"; string entityName = Inflector.Pascalize(entity.ClrType.Name); string tablenamePlural = Inflector.Pluralize(entity.ClrType.Name); string keylist = "item." + string.Join("}/{item.", entity.GetKeys().Select(k => k.Properties[0].Name)); sb.AppendLine($"\t\t\tpublic async Task<IHttpCallResultCGHT<{dtoNamespacePrefix}.{entityName}>> {clientMethodCallPrefix}{entityName}Async({dtoNamespacePrefix}.{entityName} item)"); sb.AppendLine("\t\t\t{"); sb.AppendLine($"\t\t\t\tvar retVal = await SerializationHelper.Instance.SerializeCallResults{serializeCallPostfix}<{dtoNamespacePrefix}.{entityName}>("); sb.AppendLine("\t\t\t\t\tLog, HttpClient,"); sb.Append($"\t\t\t\t\t$\"{namespacePostfix}/{tablenamePlural}/"); if (httpVerb.ToLowerInvariant() != "post") { sb.Append($"{{{keylist}}}"); } sb.AppendLine($"\", item);"); sb.AppendLine("\t\t\t\treturn retVal;"); sb.AppendLine("\t\t\t}"); sb.AppendLine(string.Empty); return(sb.ToString()); }
protected EntityMap() { Table(Inflector.Pluralize(typeof(T).Name)); Id(x => x.Id) .GeneratedBy.GuidComb() .Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore); }
public void Apply(IManyToManyCollectionInstance instance) { var parentName = instance.EntityType.Name; var childName = instance.ChildType.Name; if (parentName.CompareTo(childName) < 0) { instance.Table( string.Format( CultureInfo.InvariantCulture, FluentConfiguration.TableNameTemplate, string.Format( CultureInfo.InvariantCulture, FluentConfiguration.ManyToManyTemplate, Inflector.Pluralize(parentName), Inflector.Pluralize(childName)))); } else { instance.Table( string.Format( CultureInfo.InvariantCulture, FluentConfiguration.TableNameTemplate, string.Format( CultureInfo.InvariantCulture, FluentConfiguration.ManyToManyTemplate, Inflector.Pluralize(childName), Inflector.Pluralize(parentName)))); } }
public string GenerateWebApiControllerPartialMethods( string namespacePostfix, string classNamespace, string baseControllerName, string efEntityNamespacePrefix, string efEntityNamespace, string dbContextName, IEntityType entity, IList <IEntityNavigation> excludedNavigationProperties, bool allowUpsertDuringPut) { var className = $"{Inflector.Pluralize(entity.ClrType.Name)}{namespacePostfix}Controller"; var sb = new IndentingStringBuilder(); var usings = new List <NamespaceItem> { new NamespaceItem("CodeGenHero.Repository"), //new NamespaceItem("Microsoft.EntityFrameworkCore"), //new NamespaceItem("System.Linq"), new NamespaceItem(efEntityNamespacePrefix, efEntityNamespace) }; sb.Append(GenerateHeader(usings, classNamespace)); sb.AppendLine($"\tpublic partial class {className} : {baseControllerName}"); sb.AppendLine("\t{"); sb.Append(GeneratePartialMethods(dbContextName: dbContextName, entity: entity, efEntityNamespacePrefix: efEntityNamespacePrefix, excludedNavigationProperties: excludedNavigationProperties, allowUpsertDuringPut: allowUpsertDuringPut)); return(sb.ToString()); }
protected ResourcesMapperBase() { ControllerName = GetControllerName <TController>(); PluralResourceName = Inflector.Pluralize(ControllerName); SingularResourceName = Inflector.Singularize(PluralResourceName); As(PluralResourceName); }
public void UnsupportedCulture() { Assert.Catch<NotSupportedException>(() => { var inflector = new Inflector(new CultureInfo("fr")); var hommes = inflector.Pluralize("homme"); }); }
protected virtual string DecideTableName() { if (String.IsNullOrWhiteSpace(this.TableName)) { this.TableName = Inflector.Pluralize(typeof(T).Name.ToLower()); } return(this.TableName); }
public void UnsupportedCulture() { Assert.Catch <NotSupportedException>(() => { var inflector = new Inflector(new CultureInfo("fr")); var hommes = inflector.Pluralize("homme"); }); }
/// <summary> /// Initializes a new instance of the <see cref="DatasetRecordMap{T}"/> class and defines the foreign key relationship with <see cref="Dataset"/> /// </summary> protected DatasetRecordMap() { References(m => m.Dataset, "Dataset_Id") .ForeignKey(string.Format("FK_TARGETS_{0}_DATASETS", Inflector.Pluralize(typeof(T).Name))) .Nullable() .Cascade.All() .Not.LazyLoad(); }
public void TestPluralize() { Assert.AreEqual("posts", Inflector.Pluralize("post")); Assert.AreEqual("octopi", Inflector.Pluralize("octopus")); Assert.AreEqual("sheep", Inflector.Pluralize("sheep")); Assert.AreEqual("words", Inflector.Pluralize("words")); Assert.AreEqual("the blue mailmen", Inflector.Pluralize("the blue mailman")); Assert.AreEqual("CamelOctopi", Inflector.Pluralize("CamelOctopus")); }
public void Pluralize() { foreach (var dictionaryEntry in singularToPlural) { Assert.Equal(dictionaryEntry.Value, Inflector.Pluralize((string)dictionaryEntry.Key)); Assert.Equal(Inflector.Capitalize((string)dictionaryEntry.Value), Inflector.Pluralize(Inflector.Capitalize((string)dictionaryEntry.Key))); } }
public void PluralizeTest() { foreach (var pair in Words) { var p = Inflector.Pluralize("en", pair.Key); Assert.AreEqual(pair.Value, p); } }
public void Apply(IOneToManyCollectionInstance instance) { instance.Key.ForeignKey( string.Format( CultureInfo.InvariantCulture, FluentConfiguration.ForeignKeyTemplate, instance.EntityType.Name, Inflector.Pluralize(instance.Member.Name))); }
public string GenerateGet(IEntityType entity, string tableName, string entityTypeName) { IndentingStringBuilder sb = new IndentingStringBuilder(2); sb.AppendLine("[HttpGet]"); sb.AppendLine($"[VersionedRoute(template: \"{Inflector.Pluralize(entity.ClrType.Name)}\", allowedVersion: 1, Name = GET_LIST_ROUTE_NAME)]"); sb.AppendLine("#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously"); sb.AppendLine("public async Task<IHttpActionResult> Get(string sort = null,"); sb.AppendLine("string fields = null, string filter = null, int page = 1, int pageSize = maxPageSize)"); sb.AppendLine("#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously"); sb.AppendLine("{"); sb.AppendLine("try"); sb.AppendLine("{"); sb.AppendLine("if (!base.OnActionExecuting(out HttpStatusCode httpStatusCode, out string message)) { return Content(httpStatusCode, message); }"); sb.AppendLine(string.Empty); sb.AppendLine("var fieldList = GetListByDelimiter(fields);"); sb.AppendLine("bool childrenRequested = false; // TODO: set this based upon actual fields requested."); sb.AppendLine(string.Empty); sb.AppendLine("var filterList = GetListByDelimiter(filter);"); sb.AppendLine($"var dbItems = Repo.GetQueryable_{tableName}().AsNoTracking();"); sb.AppendLine($"RunCustomLogicAfterGetQueryableList(ref dbItems, ref filterList);"); sb.AppendLine($"dbItems = dbItems.ApplyFilter(filterList);"); sb.AppendLine($"dbItems = dbItems.ApplySort(sort ?? (typeof({entityTypeName}).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)).First().Name);"); sb.AppendLine(string.Empty); sb.AppendLine("if (pageSize > maxPageSize)"); sb.AppendLine("{ // ensure the page size isn't larger than the maximum."); sb.AppendLine("pageSize = maxPageSize;"); sb.AppendLine("}"); sb.AppendLine(string.Empty); sb.AppendLine("var urlHelper = new UrlHelper(Request);"); sb.AppendLine("PageData paginationHeader = BuildPaginationHeader(urlHelper, GET_LIST_ROUTE_NAME, page: page, totalCount: dbItems.Count(), pageSize: pageSize, sort: sort);"); sb.AppendLine("HttpContext.Current.Response.Headers.Add(\"X-Pagination\", Newtonsoft.Json.JsonConvert.SerializeObject(paginationHeader));"); sb.AppendLine(string.Empty); sb.AppendLine("// return result"); sb.AppendLine("return Ok(dbItems"); sb.AppendLine(".Skip(pageSize * (page - 1))"); sb.AppendLine(".Take(pageSize)"); sb.AppendLine(".ToList()"); sb.AppendLine(".Select(x => _factory.CreateDataShapedObject(x, fieldList, childrenRequested)));"); sb.AppendLine("}"); sb.AppendLine("catch (Exception ex)"); sb.AppendLine("{"); sb.AppendLine("Log.LogError(eventId: (int)coreEnums.EventId.Exception_WebApi,"); sb.AppendLine("\texception: ex,"); sb.AppendLine("\tmessage: \"Unable to get object via Web API for RequestUri {{RequestUri}}\","); sb.AppendLine("\tRequest.RequestUri.ToString());"); sb.AppendLine(string.Empty); sb.AppendLine("if (System.Diagnostics.Debugger.IsAttached)"); sb.AppendLine("\tSystem.Diagnostics.Debugger.Break();"); sb.AppendLine(string.Empty); sb.AppendLine("return InternalServerError();"); sb.AppendLine("}"); sb.AppendLine("}"); sb.AppendLine(string.Empty); return(sb.ToString()); }
protected override void ConfigureApplicationContainer(IContainer existingContainer) { // Perform registation that should have an application lifetime ApplicationBootstrapper.Init(); var documentStore = new DocumentStore { Url = "http://localhost:8080", DefaultDatabase = "Todo" }; documentStore.Conventions.FindTypeTagName = type => { if (typeof(Domain.IEvent).IsAssignableFrom(type)) { return(type.Name); } //Crude way of making the State id's a little bit prettier if (type.Name.EndsWith("State")) { return(Inflector.Pluralize(type.Name.Remove(type.Name.LastIndexOf("State", StringComparison.InvariantCulture), 5))); } return(DocumentConvention.DefaultTypeTagName(type)); }; documentStore.Initialize(); existingContainer.Configure(cfg => { cfg.For <IDocumentStore>().Use(documentStore).Singleton(); cfg.Scan(scanner => { scanner.AssemblyContainingType <CreateTodoItem>(); scanner.AssemblyContainingType <IMediator>(); scanner.AddAllTypesOf(typeof(IRequestHandler <,>)); scanner.AddAllTypesOf(typeof(IEventHandler <>)); scanner.AddAllTypesOf(typeof(IPreRequestHandler <>)); scanner.AddAllTypesOf(typeof(IPostRequestHandler <,>)); scanner.WithDefaultConventions(); }); cfg.For <IDocumentSession>() .Use(ctx => ctx.GetInstance <IDocumentStore>() .OpenSession()); cfg.For <IManageUnitOfWork>() .Use <RavenDbUnitOfWork>(); cfg.For(typeof(IRequestHandler <,>)) .DecorateAllWith(typeof(MediatorPipeline <,>)); cfg.For <ITodoItemRepository>().Use <TodoItemRepository>(); }); }
public string GetNameForCollection(string collectingClass, int progressive) { string cname = Inflector.Pluralize(collectingClass); if (progressive > 0) { cname += progressive.ToString(); } return(cname); }
public FlutterMap() { _indexName = string.Format("IDX_{0}", EntityTableName); Map(x => x.ConfigurationId).Length(256); Map(x => x.AssociatedReportsTypes).Length(500); Map(x => x.InstallPath).Length(255); Map(x => x.OutputPath).Length(255); Cache.NonStrictReadWrite().Region(Inflector.Pluralize(typeof(Flutter).Name)); }
//private BaseDataVersionStrategy GetVersioningStrategy() //{ // var entityType = typeof (TEntity); // var attributes = entityType.GetCustomAttributes(typeof(BaseDataImportAttribute), true) as BaseDataImportAttribute[]; // if (attributes == null || !attributes.Any()) // return null; // or throw exception // return attributes[0].CreateVersionStrategy<TEntity>(); //} /// <summary> /// Loads the data. /// </summary> public virtual void LoadData() { try { ProvideFeedback(string.Format("Loading {0}", Inflector.Pluralize(Inflector.Titleize2(typeof(TEntity).Name)))); string tableName = typeof(TEntity).EntityTableName(); using (var session = this.SessionProvider.SessionFactory.OpenStatelessSession()) { session.CreateSQLQuery(EnableDisableNonClusteredIndexes(tableName, true)) //ALL .ExecuteUpdate(); } using (var session = this.SessionProvider.SessionFactory.OpenStatelessSession()) { EntityStrategy.CurrentSession = session; using (var reader = DataProvider[Reader.Name]) { if (!reader.AlreadyImported()) { using (var bulkImporter = new BulkInsert <TEntity, TKey>(session.Connection)) { bulkImporter.ConnectionRequested += (o, e) => { e.Data = session.Connection as SqlConnection; }; bulkImporter.Prepare(); bulkImporter.BatchSize = BatchSize;; while (reader.Read()) { var temp = EntityStrategy.LoadFromReader(reader); bulkImporter.Insert(temp); } } } } } Task.Factory.StartNew(() => { using (var session = this.SessionProvider.SessionFactory.OpenStatelessSession()) { session.CreateSQLQuery(EnableDisableNonClusteredIndexes(tableName)) //ALL .SetTimeout(600) .ExecuteUpdate(); } }, TaskCreationOptions.LongRunning); } catch (Exception ex) { Logger.Write(ex, $"Error importing data for entity type {typeof(TEntity).Name} using strategy {typeof(TStrategy).Name}"); } }
public void Apply(IManyToManyCollectionInstance instance) { var entityName = Inflector.Pluralize(instance.EntityType.Name); var childName = Inflector.Pluralize(instance.ChildType.Name); var tableName = string.Format("{0}X{1}", entityName, childName); instance.Table(tableName); instance.Key.Column(entityName + "ID"); instance.Relationship.Column(childName + "ID"); }
public static string Resolve <T>(int id) { if (id < 1) { return(null); } var entityName = Inflector.Pluralize(typeof(T).Name).ToLowerInvariant(); return(string.Format("{0}/{1}", entityName, id)); }
public static string PluralizeIf(this string target, Expression <Func <bool> > expression) { if (expression.Invoke()) { return(Inflector.Pluralize(target)); } else { return(target); } }
/// <summary> /// Returns the plural form of a word if necessary. (ie. there is more than one item) /// </summary> /// <param name="word">The singular form to pluralise</param> /// <param name="count">The number of items</param> /// <returns>Either the plural or singular form of the word (depending on the count)</returns> public static string Pluralise(string word, int count, bool includeArticle = false) { if (count != 1) { return(Inflector.Pluralize(word)); } if (includeArticle) { return(AddArticle(word)); } return(word); }
/// <summary> /// Called when [save internal]. /// </summary> /// <param name="session">The session.</param> /// <param name="model">The model.</param> protected override void OnSaveInternal(ISession session, NursingHome model) { base.OnSaveInternal(session, model); if (string.IsNullOrEmpty(_previousProviderId)) { return; } session.CreateSQLQuery( string.Format("UPDATE {0} SET NursingHome_ProviderId = '{1}' WHERE NursingHome_ProviderId = '{2}'", Inflector.Pluralize(WebsiteTableNames.WebsiteNursingHomesTable), model.ProviderId, _previousProviderId)) .ExecuteUpdate(); }
public string GenerateDelete(IEntityType entity) { string keylist = string.Join("}/{", entity.FindPrimaryKey()); string classmodel = MakeModel(entity.FindPrimaryKey(), "", "", ", ", false, false, lowercaseVariableName: false); //string signature = table.Signature(""); IndentingStringBuilder sb = new IndentingStringBuilder(2); sb.AppendLine("[HttpDelete]"); sb.AppendLine($"[VersionedRoute(template: \"{Inflector.Pluralize(entity.ClrType.Name)}/{{{GetSignatureWithoutFieldTypes("", entity.FindPrimaryKey(), lowercasePkNameFirstChar: true)}}}\", allowedVersion: 1)]"); sb.AppendLine($"public async Task<IHttpActionResult> Delete({GetSignatureWithFieldTypes("", entity.FindPrimaryKey())})"); sb.AppendLine("{"); sb.AppendLine("try"); sb.AppendLine("{"); sb.AppendLine("if (!base.OnActionExecuting(out HttpStatusCode httpStatusCode, out string message)) { return Content(httpStatusCode, message); }"); sb.AppendLine(string.Empty); sb.AppendLine($"var result = await Repo.Delete_{entity.ClrType.Name}Async({GetSignatureWithoutFieldTypes("", entity.FindPrimaryKey(), lowercasePkNameFirstChar: true)});"); sb.AppendLine(string.Empty); sb.AppendLine($"if (result.Status == cghEnums.RepositoryActionStatus.Deleted)"); sb.AppendLine("{"); sb.AppendLine("return StatusCode(HttpStatusCode.NoContent);"); sb.AppendLine("}"); sb.AppendLine($"else if (result.Status == cghEnums.RepositoryActionStatus.NotFound)"); sb.AppendLine("{"); sb.AppendLine("return NotFound();"); sb.AppendLine("}"); sb.AppendLine(string.Empty); sb.AppendLine("Log.LogWarning(eventId: (int)coreEnums.EventId.Warn_WebApi,"); sb.AppendLine("\texception: result.Exception,"); sb.AppendLine("\tmessage: \"Unable to delete object via Web API for RequestUri {{RequestUri}}\","); sb.AppendLine("\tRequest.RequestUri.ToString());"); sb.AppendLine(string.Empty); sb.AppendLine("return BadRequest();"); sb.AppendLine("}"); sb.AppendLine("catch (Exception ex)"); sb.AppendLine("{"); sb.AppendLine("Log.LogError(eventId: (int)coreEnums.EventId.Exception_WebApi,"); sb.AppendLine("\texception: ex,"); sb.AppendLine("\tmessage: \"Unable to delete object via Web API for RequestUri {{RequestUri}}\","); sb.AppendLine("\tRequest.RequestUri.ToString());"); sb.AppendLine(string.Empty); sb.AppendLine("if (System.Diagnostics.Debugger.IsAttached)"); sb.AppendLine("\tSystem.Diagnostics.Debugger.Break();"); sb.AppendLine(string.Empty); sb.AppendLine("return InternalServerError();"); sb.AppendLine("}"); sb.AppendLine("}"); sb.AppendLine(string.Empty); return(sb.ToString()); }
private void GeneralizationPropertyChanged(object entity, string message = null) { var idLabel = BindingHelper.TryGetDescription(NHibernateUtil.GetClass(entity), "Id"); if (idLabel == null) { idLabel = "Код " + GetEntityName(entity); } From = "*****@*****.**"; PropertyBag["message"] = message; PropertyBag["admin"] = SecurityContext.Administrator; PropertyBag["entity"] = entity; PropertyBag["type"] = Inflector.Pluralize(NHibernateUtil.GetClass(entity).Name); PropertyBag["idLabel"] = idLabel; }
public ImportImpl(StreamReader reader, string file, TaskModel taskModel, Action <string> output, IAsyncDatabaseCommands databaseCommands) { this.taskModel = taskModel; this.output = output; this.databaseCommands = databaseCommands; csvReader = new CsvReader(reader); header = csvReader.ReadHeaderRecord(); entity = Inflector.Pluralize(Path.GetFileNameWithoutExtension(file)); if (entity.Length > 0 && char.IsLower(entity[0])) { entity = char.ToUpper(entity[0]) + entity.Substring(1); } sw = Stopwatch.StartNew(); enumerator = csvReader.DataRecords.GetEnumerator(); }
public void CreateOneToManyMappings(Dictionary <string, ClassMapping> allMappings) { foreach (IColumn column in table.Columns) { if (column.IsFK) { if (allMappings.ContainsKey(column.FkTableName)) { if (!HasColumn(Inflector.Pluralize(table.Name))) { allMappings[column.FkTableName].AddOneToMany(new OneToManyMapping(Inflector.Pluralize(table.Name), table, column)); } } } } }
public void EnglishCulture() { var inflector = new Inflector(new CultureInfo("en")); Assert.AreEqual("cats", inflector.Pluralize("cat")); }