/// <summary> /// Singularizes a word /// </summary> /// <param name="Word">Word to singularize</param> /// <param name="Culture"> /// Culture info used to singularize the word (defaults to current culture) /// </param> /// <returns>The word singularized</returns> public static string Singularize(this string Word, CultureInfo Culture = null) { if (string.IsNullOrEmpty(Word)) return ""; Culture = Culture.Check(CultureInfo.CurrentCulture); return PluralizationService.CreateService(Culture).Singularize(Word); }
public void WhenFormatLowerCase_ThenTurnsFirstLetterLowerCase() { var pluralizer = new PluralizerResourceConvention( PluralizationService.CreateService(new System.Globalization.CultureInfo("en-US")), PluralizerResourceFormat.CamelCase); Assert.Equal("helloWorlds", pluralizer.GetResourceName(typeof(HelloWorld))); }
public TableStorageBase(string connectionStringName, string tableName = "") { if (connectionStringName.Clean() == null) { throw new ArgumentNullException(nameof(connectionStringName)); } var connString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; if (connString.Clean() == null) { throw new Exception($"The connection string for '{connectionStringName}' is empty"); } var cloudStorageAccount = CloudStorageAccount.Parse(connString); var tableClient = cloudStorageAccount.CreateCloudTableClient(); tableClient.DefaultRequestOptions = new TableRequestOptions(tableClient.DefaultRequestOptions) { RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(2), 10) }; var pluralizationService = PluralizationService.CreateService(new CultureInfo("en-GB")); var tsTableName = string.IsNullOrEmpty(tableName) ? pluralizationService.Pluralize(typeof(T).Name) : tableName; Table = tableClient.GetTableReference(tsTableName); Table.CreateIfNotExists(); }
private static string Singularize(string value) { if (value.EndsWith("List")) { return(value.Substring(0, value.Length - 4)); } if (value.EndsWith("Data")) { return(value); } for (int i = 1; i < value.Length; i++) { if (char.IsUpper(value[i])) { var firstWord = value.Substring(0, i); var lastWord = Singularize(value.Substring(i, value.Length - i)); return(firstWord + lastWord); } } var pluralizer = PluralizationService.CreateService(new CultureInfo("en-us")); return(pluralizer.Singularize(value)); }
public ActionResult Create(string id, int?containerId) { if (string.IsNullOrEmpty(id)) { return(CreatableTypeList(containerId)); } var pluralService = PluralizationService.CreateService(new CultureInfo("en-US")); id = pluralService.Singularize(id); var contentItem = Services.ContentManager.New(id); if (!Services.Authorizer.Authorize(Permissions.EditContent, contentItem, T("Cannot create content"))) { return(new HttpUnauthorizedResult()); } if (containerId.HasValue && contentItem.Is <ContainablePart>()) { var common = contentItem.As <CommonPart>(); if (common != null) { common.Container = Services.ContentManager.Get(containerId.Value); } } dynamic model = Services.ContentManager.BuildEditor(contentItem); model.Layout = GetLayout(contentItem); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return(View((object)model)); }
public static string AtLeastOne(string argumentName) { var singularizedArgumentName = PluralizationService.Singularize(argumentName); var expandedArgumentName = singularizedArgumentName.ToExpandedString().ToLower(); return($"At least one {expandedArgumentName} must be provided."); }
private void WriteDbSetsEFCore(ModelRoot modelRoot) { Output("#region DbSets"); PluralizationService pluralizationService = ModelRoot.PluralizationService; foreach (ModelClass modelClass in modelRoot.Classes.Where(x => !x.IsDependentType).OrderBy(x => x.Name)) { string dbSetName; if (!string.IsNullOrEmpty(modelClass.DbSetName)) { dbSetName = modelClass.DbSetName; } else { dbSetName = pluralizationService?.IsSingular(modelClass.Name) == true ? pluralizationService.Pluralize(modelClass.Name) : modelClass.Name; } if (!string.IsNullOrEmpty(modelClass.Summary)) { NL(); Output("/// <summary>"); WriteCommentBody($"Repository for {modelClass.FullName} - {modelClass.Summary}"); Output("/// </summary>"); } Output($"{modelRoot.DbSetAccess.ToString().ToLower()} virtual Microsoft.EntityFrameworkCore.DbSet<{modelClass.FullName}> {dbSetName} {{ get; set; }}"); } Output("#endregion DbSets"); NL(); }
public void AddEventName(HttpActionContext actionContext, PluralizationService pluralizationService) { string eventName; object eventNameProperty; if (actionContext.Request.Properties.TryGetValue(Constants.EventNamePropertyKey, out eventNameProperty)) { eventName = (string)eventNameProperty; } else { var controllerName = actionContext.ControllerContext.ControllerDescriptor.ControllerName; if (actionContext.ActionDescriptor.ReturnType != null && EnumerableType.IsAssignableFrom(actionContext.ActionDescriptor.ReturnType)) { controllerName = pluralizationService.Pluralize(controllerName); } var methodType = actionContext.Request.Method; var actionName = actionContext.ActionDescriptor.ActionName; eventName = GetEventName(methodType, actionName, controllerName); actionContext.Request.Properties[Constants.EventNamePropertyKey] = eventName; } }
public object Post(string id, ListQueryModel model) { if (string.IsNullOrEmpty(id)) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest)); } var part = GetProjectionPartRecord(model.ViewId); if (part == null) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest)); } var pluralService = PluralizationService.CreateService(new CultureInfo("en-US")); id = pluralService.Singularize(id); string filterDescription = null; return(GetFilteredRecords(id, part, out filterDescription, model, p => { _gridService.GenerateSortCriteria(id, model.Sidx, model.Sord, p.Record.QueryPartRecord.Id); var totalRecords = _projectionManager.GetCount(p.Record.QueryPartRecord.Id); var pageSize = model.Rows; var totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize); var pager = new Pager(Services.WorkContext.CurrentSite, model.Page, pageSize); var records = GetLayoutComponents(p, pager.GetStartIndex(), pager.PageSize); return new { totalPages = totalPages, page = model.Page, totalRecords = totalRecords, rows = records, filterDescription = filterDescription }; })); }
public JSONProperty GetStructure(Options options) { this.reference = options.ReferenceTable; pluralization = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en")); Table table = null; foreach (Table t in tables) { if (t.Name == reference) { table = t; break; } } JSONProperty property = ProcessTables(table, new JSONProperty() { type = "object", title = reference, schema = "http://json-schema.org/draft-07/schema#" }, new HashSet <string>(), options, options.Verbose == 1); if (options.Multiple == 1) { JSONProperty array = new JSONProperty(); array.type = "array"; array.title = property.title; array.schema = property.schema; property.title = null; property.schema = null; array.items = property; return(array); } return(property); }
protected override void OnModelCreating(DbModelBuilder modelBuilder) { var service = PluralizationService.CreateService(new System.Globalization.CultureInfo("en-En")); modelBuilder.Types().Configure(entity => entity.ToTable(EligoDbConfiguration.TablePrefix + service.Pluralize(entity.ClrType.Name))); base.OnModelCreating(modelBuilder); }
/// <summary> /// </summary> /// <param name="extraPluralizationWords"> /// A string containing extra pluralization words /// in the form Singular1,Plural1|Singular2,Plural2|Singular3,Plural3 ... /// </param> public DefaultConvention(string extraPluralizationWords) { this.pluralizer = PluralizationService.CreateService(new CultureInfo("en-GB")); // ok, damned EnglishPluralizationService is an internal class so bit of reflection... var addWordMethod = typeof(PluralizationService).Assembly.GetType("System.Data.Entity.Design.PluralizationServices.EnglishPluralizationService") .GetMethod("AddWord"); if (!string.IsNullOrWhiteSpace(extraPluralizationWords)) { try { var pairs = extraPluralizationWords.Split('|'); foreach (var pair in pairs) { var words = pair.Split(','); if (words.Length == 2) { addWordMethod.Invoke(this.pluralizer, new object[] { words[0], words[1] }); } } } catch (Exception e) { throw new Exception("At the moment only English pluralization is supported", e); } } }
public object Get(string id, int page, int rows) { var pluralService = PluralizationService.CreateService(new CultureInfo("en-US")); if (pluralService.IsPlural(id)) { id = pluralService.Singularize(id); } var query = Services.ContentManager.Query <ListViewPart, ListViewPartRecord>("ListViewPage") .Where(v => v.ItemContentType == id).List().Select(record => new { ContentId = record.Id, DisplayName = record.As <TitlePart>().Title, Default = record.IsDefault }).ToList(); var totalRecords = query.Count(); return(new { total = Convert.ToInt32(Math.Ceiling((double)totalRecords / rows)), page = page, records = totalRecords, rows = query }); }
public IEnumerable <JObject> Get(string id) { var pluralService = PluralizationService.CreateService(new CultureInfo("en-US")); if (pluralService.IsPlural(id)) { id = pluralService.Singularize(id); } var entityFilters = new List <JObject>(); var entityFilterRecords = _entityFilterRepository.Table.Where(x => x.EntityName == id); foreach (var entityFilterRecord in entityFilterRecords) { var filterGroup = new JObject(); filterGroup["Id"] = entityFilterRecord.Id; filterGroup["FilterGroupId"] = entityFilterRecord.FilterGroupRecord.Id; filterGroup["Title"] = entityFilterRecord.Title; var filters = new JArray(); foreach (var filterRecord in entityFilterRecord.FilterGroupRecord.Filters) { var filter = new JObject(); filter["Type"] = filterRecord.Type; filter["State"] = FormParametersHelper.ToDynamic(filterRecord.State); filters.Add(filter); } filterGroup["Filters"] = filters; entityFilters.Add(filterGroup); } return(entityFilters); }
public SimoPluralizer() { _specificPluralizations = new Dictionary <string, string>(); _service = PluralizationService.CreateService(new CultureInfo("en")); IsEnabled = true; InitializeSpecificPluralizations(); }
static void Main(string[] args) { Console.WriteLine("Enter path to file with item IDs and names"); var path = Console.ReadLine(); var lines = File.ReadAllLines(path); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); var pluralizer = PluralizationService.CreateService(CultureInfo.CurrentCulture); foreach (var line in lines) { int colonIndex = line.IndexOf(':'); var beforeColon = line.Substring(0, colonIndex); var afterColon = line.Substring(colonIndex + 1); Console.WriteLine($@"[""{beforeColon}""]".PadRight(50) + $@" = (""{afterColon}"", ""{pluralizer.Pluralize(afterColon)}""),"); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("done. Press any key to close."); Console.ReadKey(); }
// ******************************************************************* // Constructors. // ******************************************************************* #region Constructors /// <summary> /// This constructor creates a new instance of the <see cref="MongoDbCrudRepository{TOptions, TModel, TKey}"/> /// class. /// </summary> /// <param name="options">The options to use for the repository.</param> /// <param name="client">The CosmoDb client to use with the repository.</param> protected MongoDbCrudRepository( TOptions options, MongoClient client ) : base(options) { // Validate the parameters before attempting to use them. Guard.Instance().ThrowIfNull(client, nameof(client)); // Save the references. Client = client; // We'll tie the collection back to the model type here by pluralizing // the model's type name and using that as the collection name. ContainerName = PluralizationService.CreateService( new CultureInfo("en") // Always pluralize in english ).Pluralize(typeof(TModel).Name); // Get the database. Database = Client.GetDatabase( Options.Value.DatabaseId ); // Get the collection. Collection = Database.GetCollection <TModel>(ContainerName); }
public static string ToPlural(string targetValue) { if (_service == null) { _service = PluralizationService.CreateService(System.Globalization.CultureInfo.GetCultureInfo(CultureInfo)); } var word = GetLastWord(targetValue); string newWord; if (!Dictionary1.TryGetValue(word.ToLower(), out newWord)) { newWord = _service.IsPlural(word) ? word : _service.Pluralize(word); } if (string.Compare(word, newWord, true) != 0) { if (char.IsUpper(word[0])) { newWord = char.ToUpper(newWord[0]) + newWord.Substring(1, newWord.Length - 1); } if (word == targetValue) { return(newWord); } return(targetValue.Substring(0, targetValue.Length - word.Length) + newWord); } return(targetValue); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultConvention" /> class. /// </summary> /// <param name="stringLength"> /// The string length. /// </param> /// <param name="decimalPrecision"> /// The decimal precision. /// </param> /// <param name="decimalScale"> /// The decimal scale. /// </param> public DefaultConvention(ushort stringLength = 255, byte decimalPrecision = 18, byte decimalScale = 10) { this.stringLength = stringLength; this.decimalPrecision = decimalPrecision; this.decimalScale = decimalScale; this.Pluralizer = PluralizationService.CreateService(new CultureInfo("en-GB")); // <-- Americans, back in your box. }
public static IContainer Initialize() { var pluralizer = PluralizationService.CreateService(CultureInfo.CurrentCulture); ObjectFactory.Initialize(x => { x.Scan(scan => { scan.TheCallingAssembly(); scan.WithDefaultConventions(); }); x.For <MongoDatabase>().Use(() => MongoDatabase.Create(Config.MongoUrl)); x.For(typeof(MongoCollection <>)).Use(context => { var db = context.GetInstance <MongoDatabase>(); var type = context.BuildStack.Current.RequestedType; var modelType = type.GetGenericArguments()[0]; var collectionName = pluralizer.Pluralize(modelType.Name); return(db.GetCollection(modelType, collectionName)); }); x.For <IMailSender>().Use <SendGridMailSender>(); x.For <NetworkCredential>().Use(new NetworkCredential(Config.SendGrid.User, Config.SendGrid.Password)); }); return(ObjectFactory.Container); }
public static string ToPlural(this string source) { var cultureInfo = new CultureInfo("en-us"); var pluralizationService = PluralizationService.CreateService(cultureInfo); return(pluralizationService.Pluralize(source)); }
public WordnikManager() { plurService = PluralizationService.CreateService(System.Globalization.CultureInfo.CreateSpecificCulture("en-US")); #if LOG_DATA DataLogger.Log("[WordnikManager] PluralizationService created with culture: " + plurService.Culture.Name, LoggingMode.Message); #endif }
public ActionResult CreateNavigationItemPOST(int perspectiveId, int navigationId, NavigationViewModel model) { var pluralService = PluralizationService.CreateService(new CultureInfo("en-US")); string pluralContentTypeName = pluralService.Pluralize(model.EntityName); if (string.IsNullOrWhiteSpace(model.IconClass)) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Content(T("Icon is required.").ToString())); } //add var moduleMenuPart = Services.ContentManager.New <MenuPart>("ModuleMenuItem"); // load the menu var menu = Services.ContentManager.Get(perspectiveId); moduleMenuPart.MenuText = pluralContentTypeName; moduleMenuPart.MenuPosition = Position.GetNext(_navigationManager.BuildMenu(menu)); moduleMenuPart.Menu = menu; //menuPart.As<MenuItemPart>().Url = "~/Coevery#/" + pluralContentTypeName; moduleMenuPart.As <ModuleMenuItemPart>().ContentTypeDefinitionRecord = _contentTypeDefinitionRepository.Table.FirstOrDefault(x => x.Name == model.EntityName); moduleMenuPart.As <ModuleMenuItemPart>().IconClass = model.IconClass; //menuPart.As<MenuItemPart>().FeatureId = "Coevery." + pluralContentTypeName; Services.ContentManager.Create(moduleMenuPart); if (!moduleMenuPart.ContentItem.Has <IPublishingControlAspect>() && !moduleMenuPart.ContentItem.TypeDefinition.Settings.GetModel <ContentTypeSettings>().Draftable) { _contentManager.Publish(moduleMenuPart.ContentItem); } return(Json(new { id = moduleMenuPart.ContentItem.Id })); }
private void ButtonConvertToCSharp_Click(object sender, EventArgs e) { if (isFileLoaded == false) { return; } string serializeText = ""; if (CheckBoxIsSerializable.Checked) { serializeText = "[Serializable]\r\n"; } PluralizationService pluralizationService = PluralizationService.CreateService(new CultureInfo("en-us")); string TEXTCSHARP = ""; string items = ""; for (int tableIndex = 0; tableIndex < result.Tables.Count; tableIndex++) { items = serializeText; items += "public class " + pluralizationService.Singularize("" + result.Tables[tableIndex].TableName) + "\r\n{"; var table = result.Tables[tableIndex]; for (int columnIndex = 0; columnIndex < table.Columns.Count; columnIndex++) { items += "\r\n\tpublic " + GetVariableType(tableIndex, table, columnIndex) + " " + table.Rows[0][columnIndex] + ";"; } items += "\r\n}"; TEXTCSHARP += items + "\r\n\r\n"; } items = serializeText + "public class RootObject\r\n{\r\n"; for (int tableIndex = 0; tableIndex < result.Tables.Count; tableIndex++) { items += "\tpublic List<" + pluralizationService.Singularize("" + result.Tables[tableIndex].TableName) + "> " + result.Tables[tableIndex].TableName + ";\r\n"; } items += "}"; TEXTCSHARP += items; string fileName = path + "/CSharpData.txt"; try { FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); fs.Close(); File.AppendAllText(fileName, Environment.NewLine + TEXTCSHARP); labelCSharpConverted.Text = "Converted!"; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private static void ParseAttack(Model.CreatureAttributes attributes, string str, Types.Attack attackType) { Model.AttackSet attackSet = new Model.AttackSet { Name = "Full Attack", }; string attacksPattern = @"(?<NumAttacks>\d+)?\s?(?<Name>\D+)\s(?<HitMod>[+-]\d+)(\seach)?\s(\((?<Damage>[^\(]*)\))?"; Regex attacksRegex = new Regex(attacksPattern, RegexOptions.IgnoreCase); MatchCollection attackMatches = attacksRegex.Matches(str); foreach (Match attackMatch in attackMatches) { int numAttacks = 1; string name = attackMatch.Groups["Name"].Value; if (attackMatch.Groups["NumAttacks"].Value != "") { numAttacks = Convert.ToInt32(attackMatch.Groups["NumAttacks"].Value); PluralizationService ps = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en-us")); name = ps.Singularize(name); } name = char.ToUpper(name[0]) + name.Substring(1); for (int i = 0; i < numAttacks; ++i) { Model.Attack attack = new Model.Attack(); attack.Name = name; attack.Modifier = Convert.ToInt32(attackMatch.Groups["HitMod"].Value); attack.Type = attackType; string damageStr = attackMatch.Groups["Damage"].Value; string damagePattern = @"(?<NumDice>\d+)(?<Die>d\d+)(?<DamageMod>[\+\-]?\d*)\s?(?<DamageType>(?!plus\b)\b\w+)?"; Regex damageRegex = new Regex(damagePattern, RegexOptions.IgnoreCase); MatchCollection damageMatches = damageRegex.Matches(damageStr); foreach (Match damageMatch in damageMatches) { Model.Damage damage = new Model.Damage(); damage.NumDice = Convert.ToInt32(damageMatch.Groups["NumDice"].Value); damage.Die = Methods.GetDieTypeFromString(damageMatch.Groups["Die"].Value); if (damageMatch.Groups["DamageMod"].Value != "") { damage.Modifier = Convert.ToInt32(damageMatch.Groups["DamageMod"].Value); } if (damageMatch.Groups["DamageType"].Value != "") { damage.DamageDescriptorSet.Add(Methods.GetDamageTypeFromString(damageMatch.Groups["DamageType"].Value)); } attack.Damages.Add(damage); } attackSet.Attacks.Add(attack); } } attributes.AttackSets.Add(attackSet); }
public void Apply(IClassInstance instance) { string typeName = instance.EntityType.Name; var tableName = PluralizationService.CreateService(CultureInfo.CurrentCulture).Pluralize(typeName); var tableNameLowerCase = tableName.ToLower(); instance.Table(tableNameLowerCase); }
protected static string GetTableName(Type t) { var pluralizer = PluralizationService.CreateService(CultureInfo.CurrentCulture); var tableName = pluralizer.Pluralize(t.Name); return(tableName); }
/// <summary> /// Singularize word. /// </summary> public static string Singularize(string word) { var singularword = PluralizationService.CreateService( CultureInfo.GetCultureInfo("en-us")).Singularize(word); return(singularword); }
public static string Plural(this string value, int count) { return(count == 1 ? value : PluralizationService .CreateService(new CultureInfo("en-US")) .Pluralize(value)); }
public IMongoCollection <T> Collection <T>() where T : MongoEntity { //Pluralize class name var pluralizeService = PluralizationService.CreateService(new System.Globalization.CultureInfo("en-US")); string tableName = PluralizeDocumentName ? pluralizeService.Pluralize(typeof(T).Name) : typeof(T).Name; return(database.GetCollection <T>(typeof(T).Name)); }
static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(@" _ _ "); Console.WriteLine(@" /\ | | (_) "); Console.WriteLine(@" / \ _ __ ___| |_ _ _ _ _ __ ___ "); Console.WriteLine(@" / /\ \ | '__/ __| __| | | | | '_ ` _ \ "); Console.WriteLine(@" / ____ \| | | (__| |_| | |_| | | | | | |"); Console.WriteLine(@"/_/ \_\_| \___|\__|_|\__,_|_| |_| |_|"); Console.WriteLine(@" _ "); Console.WriteLine(@" |_._ _ | __|_ o _._ "); Console.WriteLine(@" |_| | |_||(_||_ |(_| | "); Console.WriteLine(); //Console.WriteLine($"{"www.arctium-emulation.com",33}"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; ReadConsoleArgs(args); if (isMacOrUnix && string.IsNullOrEmpty(appFolder)) Console.WriteLine ("Please use your '.app' folder as start parameter."); else { pluralService = new PluralizationService(); pluralService.AddException("gtNpcTotalHp"); Console.WriteLine("Initializing CASC library..."); if (string.IsNullOrEmpty(appFolder)) cascHandler = new CASCHandler(appFolder = Environment.CurrentDirectory); else cascHandler = new CASCHandler(Directory.GetParent(appFolder).ToString()); Console.WriteLine("Done."); ExtractClientDBData(); Console.WriteLine("Done."); ExtractMapData(); Console.WriteLine(); Console.WriteLine("Press any key to exit..."); } Console.ReadKey(true); }