Created
February 28, 2020 18:29
-
-
Save yashsway/716a775845e6b153b82747a777209bb0 to your computer and use it in GitHub Desktop.
C# Basic Label Class ready for Localization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Text.RegularExpressions; | |
using System.Globalization; | |
namespace BrainstationShared.Helpers { | |
public class LabelBook { | |
public Dictionary<string, LanguageBook> Book { get; set; } | |
public string SetLang { get; set; } = "en"; | |
public const string NoLabelPlaceholder = "NOT_SET"; | |
public LabelBook(Dictionary<string, LanguageBook> book) { | |
this.Book = book; | |
} | |
public LabelBook(Dictionary<string, LanguageBook> book, string lang) { | |
this.Book = book; | |
this.SetLang = lang; | |
} | |
public LanguageBook this[string id] { | |
get { | |
return this.Book.ContainsKey(id) ? this.Book[id] : new LanguageBook() { en = LabelBook.NoLabelPlaceholder }; | |
} | |
set { | |
this.Book.Add(id, value); | |
} | |
} | |
public string GetLabel(string id) { | |
return this.Book.ContainsKey(id) ? this.Book[id][this.SetLang] : LabelBook.NoLabelPlaceholder; | |
} | |
public string GetLabel(string id, string lang) { | |
return this.Book.ContainsKey(id) ? this.Book[id][string.IsNullOrEmpty(lang) ? this.SetLang : lang] : LabelBook.NoLabelPlaceholder; | |
} | |
// always in 'en'. camel-cased. Example Text => exampleText | |
public string GetHtmlId(string key, bool isTitlecase = false) { | |
LanguageBook labelEntry; | |
Book.TryGetValue(key, out labelEntry); | |
TextInfo tcId = new CultureInfo("en-US", false).TextInfo; | |
// change to titlecase | |
string titlecasedId = labelEntry != null && !string.IsNullOrEmpty(labelEntry["en"]) ? tcId.ToTitleCase(labelEntry["en"].ToLower()) : null; | |
// strip out all symbols except numbers and characters, lowercase the first character | |
return titlecasedId != null ? Regex.Replace(isTitlecase ? titlecasedId : char.ToLower(titlecasedId[0]) + titlecasedId.Substring(1), @"[^a-zA-Z0-9]+", "") : null; | |
} | |
} | |
public class LanguageBook { | |
public string en; | |
public string fr; | |
public const string NoLangPlaceholder = "NOT_SET_IN_LANG"; | |
public string this[string lang] { | |
get { | |
string finalStr; | |
switch (lang) { | |
case "en": | |
finalStr = this.en; | |
break; | |
case "fr": | |
finalStr = this.fr; | |
break; | |
default: | |
finalStr = this.en; | |
break; | |
} | |
return finalStr ?? LanguageBook.NoLangPlaceholder; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment