Skip to content

Instantly share code, notes, and snippets.

@ChrisMcKee
Created January 4, 2013 11:24
Show Gist options
  • Select an option

  • Save ChrisMcKee/4451876 to your computer and use it in GitHub Desktop.

Select an option

Save ChrisMcKee/4451876 to your computer and use it in GitHub Desktop.
Common Extensions for CSharp (.net)
namespace Helper
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
public static class Strings
{
public static bool StringIsNumeric(this string source)
{
int result;
return int.TryParse(source, out result);
}
public static bool Matches(this string source, string compare)
{
return String.Equals(source, compare, StringComparison.InvariantCultureIgnoreCase);
}
public static bool MatchesTrimmed(this string source, string compare)
{
return String.Equals(source.Trim(), compare.Trim(), StringComparison.InvariantCultureIgnoreCase);
}
public static bool MatchesRegex(this string inputString, string matchPattern)
{
return Regex.IsMatch(inputString, matchPattern,
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
}
/// <summary>
/// Strips the last specified chars from a string.
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <param name="removeFromEnd"> The remove from end. </param>
/// <returns> </returns>
public static string Chop(this string sourceString, int removeFromEnd)
{
string result = sourceString;
if ((removeFromEnd > 0) && (sourceString.Length > removeFromEnd - 1))
result = result.Remove(sourceString.Length - removeFromEnd, removeFromEnd);
return result;
}
/// <summary>
/// Strips the last specified chars from a string.
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <param name="backDownTo"> The back down to. </param>
/// <returns> </returns>
public static string Chop(this string sourceString, string backDownTo)
{
int removeDownTo = sourceString.LastIndexOf(backDownTo, StringComparison.Ordinal);
int removeFromEnd = 0;
if (removeDownTo > 0)
removeFromEnd = sourceString.Length - removeDownTo;
string result = sourceString;
if (sourceString.Length > removeFromEnd - 1)
result = result.Remove(removeDownTo, removeFromEnd);
return result;
}
/// <summary>
/// Plurals to singular.
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <returns> </returns>
public static string PluralToSingular(this string sourceString)
{
return sourceString.MakeSingular();
}
/// <summary>
/// Singulars to plural.
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <returns> </returns>
public static string SingularToPlural(this string sourceString)
{
return sourceString.MakePlural();
}
/// <summary>
/// Make plural when count is not one
/// </summary>
/// <param name="number"> The number of things </param>
/// <param name="sourceString"> The source string. </param>
/// <returns> </returns>
public static string Pluralize(this int number, string sourceString)
{
if (number == 1)
return String.Concat(number, " ", sourceString.MakeSingular());
return String.Concat(number, " ", sourceString.MakePlural());
}
/// <summary>
/// Removes the specified chars from the beginning of a string.
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <param name="removeFromBeginning"> The remove from beginning. </param>
/// <returns> </returns>
public static string Clip(this string sourceString, int removeFromBeginning)
{
string result = sourceString;
if (sourceString.Length > removeFromBeginning)
result = result.Remove(0, removeFromBeginning);
return result;
}
/// <summary>
/// Removes chars from the beginning of a string, up to the specified string
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <param name="removeUpTo"> The remove up to. </param>
/// <returns> </returns>
public static string Clip(this string sourceString, string removeUpTo)
{
int removeFromBeginning = sourceString.IndexOf(removeUpTo);
string result = sourceString;
if (sourceString.Length > removeFromBeginning && removeFromBeginning > 0)
result = result.Remove(0, removeFromBeginning);
return result;
}
/// <summary>
/// Strips the last char from a a string.
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <returns> </returns>
public static string Chop(this string sourceString)
{
return Chop(sourceString, 1);
}
/// <summary>
/// Strips the last char from a a string.
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <returns> </returns>
public static string Clip(this string sourceString)
{
return Clip(sourceString, 1);
}
/// <summary>
/// Fasts the replace.
/// </summary>
/// <param name="original"> The original. </param>
/// <param name="pattern"> The pattern. </param>
/// <param name="replacement"> The replacement. </param>
/// <returns> </returns>
public static string FastReplace(this string original, string pattern, string replacement)
{
return FastReplace(original, pattern, replacement, StringComparison.InvariantCultureIgnoreCase);
}
/// <summary>
/// Fasts the replace.
/// </summary>
/// <param name="original"> The original. </param>
/// <param name="pattern"> The pattern. </param>
/// <param name="replacement"> The replacement. </param>
/// <param name="comparisonType"> Type of the comparison. </param>
/// <returns> </returns>
public static string FastReplace(this string original, string pattern, string replacement,
StringComparison comparisonType)
{
if (original == null)
return null;
if (String.IsNullOrEmpty(pattern))
return original;
int lenPattern = pattern.Length;
int idxPattern = -1;
int idxLast = 0;
StringBuilder result = new StringBuilder();
while (true)
{
idxPattern = original.IndexOf(pattern, idxPattern + 1, comparisonType);
if (idxPattern < 0)
{
result.Append(original, idxLast, original.Length - idxLast);
break;
}
result.Append(original, idxLast, idxPattern - idxLast);
result.Append(replacement);
idxLast = idxPattern + lenPattern;
}
return result.ToString();
}
/// <summary>
/// Returns text that is located between the startText and endText tags.
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <param name="startText"> The text from which to start the crop </param>
/// <param name="endText"> The endpoint of the crop </param>
/// <returns> </returns>
public static string Crop(this string sourceString, string startText, string endText)
{
int startIndex = sourceString.IndexOf(startText, StringComparison.CurrentCultureIgnoreCase);
if (startIndex == -1)
return String.Empty;
startIndex += startText.Length;
int endIndex = sourceString.IndexOf(endText, startIndex, StringComparison.CurrentCultureIgnoreCase);
if (endIndex == -1)
return String.Empty;
return sourceString.Substring(startIndex, endIndex - startIndex);
}
/// <summary>
/// Removes excess white space in a string.
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <returns> </returns>
public static string Squeeze(this string sourceString)
{
char[] delim = { ' ' };
string[] lines = sourceString.Split(delim, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
foreach (string s in lines)
{
if (!String.IsNullOrEmpty(s.Trim()))
sb.Append(s + " ");
}
//remove the last pipe
string result = Chop(sb.ToString());
return result.Trim();
}
/// <summary>
/// Removes all non-alpha numeric characters in a string
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <returns> </returns>
public static string ToAlphaNumericOnly(this string sourceString)
{
return Regex.Replace(sourceString, @"\W*", "");
}
/// <summary>
/// Creates a string array based on the words in a sentence
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <returns> </returns>
public static string[] ToWords(this string sourceString)
{
string result = sourceString.Trim();
return result.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
/// <summary>
/// Capitalise Each Word
/// </summary>
/// <param name="s">string</param>
/// <returns>Capitalised String</returns>
public static string Capitalise(String s)
{
string x = s.ToLower();
string result = String.Empty;
foreach (char c in x)
result = result.Length == 0 && c != ' ' ? c.ToString().ToUpper() : (result.EndsWith(" ") ? result + c.ToString().ToUpper() : result + c.ToString());
return result;
}
/// <summary>
/// Strips all HTML tags from a string
/// </summary>
/// <param name="htmlString"> The HTML string. </param>
/// <returns> </returns>
public static string StripHTML(this string htmlString)
{
return StripHTML(htmlString, String.Empty);
}
/// <summary>
/// Strips all HTML tags from a string and replaces the tags with the specified replacement
/// </summary>
/// <param name="htmlString"> The HTML string. </param>
/// <param name="htmlPlaceHolder"> The HTML place holder. </param>
/// <returns> </returns>
public static string StripHTML(this string htmlString, string htmlPlaceHolder)
{
const string pattern = @"<(.|\n)*?>";
string sOut = Regex.Replace(htmlString, pattern, htmlPlaceHolder);
sOut = sOut.Replace("&nbsp;", String.Empty);
sOut = sOut.Replace("&amp;", "&");
sOut = sOut.Replace("&gt;", ">");
sOut = sOut.Replace("&lt;", "<");
return sOut;
}
public static List<string> FindMatches(this string source, string find)
{
Regex reg = new Regex(find, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
List<string> result = new List<string>();
foreach (Match m in reg.Matches(source))
result.Add(m.Value);
return result;
}
/// <summary>
/// Converts a generic List collection to a single comma-delimitted string.
/// </summary>
/// <param name="list"> The list. </param>
/// <returns> </returns>
public static string ToDelimitedList(this IEnumerable<string> list)
{
return ToDelimitedList(list, ",");
}
/// <summary>
/// Converts a generic List collection to a single string using the specified delimitter.
/// </summary>
/// <param name="list"> The list. </param>
/// <param name="delimiter"> The delimiter. </param>
/// <returns> </returns>
public static string ToDelimitedList(this IEnumerable<string> list, string delimiter)
{
StringBuilder sb = new StringBuilder();
foreach (string s in list)
sb.Append(String.Concat(s, delimiter));
string result = sb.ToString();
result = Chop(result);
return result;
}
/// <summary>
/// Strips the specified input.
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <param name="stripValue"> The strip value. </param>
/// <returns> </returns>
public static string Strip(this string sourceString, string stripValue)
{
if (!String.IsNullOrEmpty(stripValue))
{
string[] replace = stripValue.Split(new[] { ',' });
for (int i = 0; i < replace.Length; i++)
{
if (!String.IsNullOrEmpty(sourceString))
sourceString = Regex.Replace(sourceString, replace[i], String.Empty);
}
}
return sourceString;
}
/// <summary>
/// Converts ASCII encoding to Unicode
/// </summary>
/// <param name="asciiCode"> The ASCII code. </param>
/// <returns> </returns>
public static string AsciiToUnicode(this int asciiCode)
{
Encoding ascii = Encoding.UTF32;
char c = (char)asciiCode;
Byte[] b = ascii.GetBytes(c.ToString());
return ascii.GetString((b));
}
/// <summary>
/// Formats the args using String.Format with the target string as a format string.
/// </summary>
/// <param name="fmt"> The format string passed to String.Format </param>
/// <param name="args"> The args passed to String.Format </param>
/// <returns> </returns>
public static string ToFormattedString(this string fmt, params object[] args)
{
return String.Format(fmt, args);
}
/// <summary>
/// Strings to enum.
/// </summary>
/// <typeparam name="T"> </typeparam>
/// <param name="Value"> The value. </param>
/// <returns> </returns>
public static T ToEnum<T>(this string Value)
{
T oOut = default(T);
Type t = typeof(T);
foreach (FieldInfo fi in t.GetFields())
{
if (fi.Name.Matches(Value))
oOut = (T)fi.GetValue(null);
}
return oOut;
}
}
public static class DateTimeExtensions
{
/// <summary>
/// Date is between date1 + date2 (inclusive)
/// </summary>
/// <param name="input"></param>
/// <param name="date1"></param>
/// <param name="date2"></param>
/// <returns></returns>
public static bool IsBetween(this DateTime input, DateTime date1, DateTime date2)
{
return (input >= date1 && input <= date2);
}
/// <summary>
/// Date passed has less than a month remaining
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsLessThanAMonthRemaining(this DateTime input)
{
return input.Subtract(SystemTime.Now()).Days / (365.25 / 12) < 1;
}
/// <summary>
/// Returns the first day of the month
/// </summary>
/// <example>
/// DateTime firstOfThisMonth = DateTime.Now.FirstOfMonth;
/// </example>
/// <param name="dt">Start date</param>
/// <returns></returns>
public static DateTime FirstOfMonth(this DateTime dt)
{
return (dt.AddDays(1 - dt.Day)).AtMidnight();
}
/// <summary>
/// Returns the first specified day of the week in the current month
/// </summary>
/// <example>
/// DateTime firstTuesday = DateTime.Now.FirstDayOfMonth(DayOfWeek.Tuesday);
/// </example>
/// <param name="dt">Start date</param>
/// <param name="dayOfWeek">The required day of week</param>
/// <returns></returns>
public static DateTime FirstOfMonth(this DateTime dt, DayOfWeek dayOfWeek)
{
DateTime firstDayOfMonth = dt.FirstOfMonth();
return (firstDayOfMonth.DayOfWeek == dayOfWeek ? firstDayOfMonth :
firstDayOfMonth.NextDayOfWeek(dayOfWeek)).AtMidnight();
}
/// <summary>
/// Returns the last day in the current month
/// </summary>
/// <example>
/// DateTime endOfMonth = DateTime.Now.LastDayOfMonth();
/// </example>
/// <param name="dt" />
/// Start date
/// <returns />
public static DateTime LastOfMonth(this DateTime dt)
{
int daysInMonth = DateTime.DaysInMonth(dt.Year, dt.Month);
return dt.FirstOfMonth().AddDays(daysInMonth - 1).AtMidnight();
}
/// <summary>
/// Returns the last specified day of the week in the current month
/// </summary>
/// <example>
/// DateTime finalTuesday = DateTime.Now.LastDayOfMonth(DayOfWeek.Tuesday);
/// </example>
/// <param name="dt" />
/// Start date
/// <param name="dayOfWeek" />
/// The required day of week
/// <returns />
public static DateTime LastOfMonth(this DateTime dt, DayOfWeek dayOfWeek)
{
DateTime lastDayOfMonth = dt.LastOfMonth();
return lastDayOfMonth.AddDays(lastDayOfMonth.DayOfWeek < dayOfWeek ?
dayOfWeek - lastDayOfMonth.DayOfWeek - 7 :
dayOfWeek - lastDayOfMonth.DayOfWeek);
}
/// <summary>
/// Returns the next date which falls on the given day of the week
/// </summary>
/// <example>
/// DateTime nextTuesday = DateTime.Now.NextDayOfWeek(DayOfWeek.Tuesday);
/// </example>
/// <param name="dt">Start date</param>
/// <param name="dayOfWeek">The required day of week</param>
public static DateTime NextDayOfWeek(this DateTime dt, DayOfWeek dayOfWeek)
{
int offsetDays = dayOfWeek - dt.DayOfWeek;
return dt.AddDays(offsetDays > 0 ? offsetDays : offsetDays + 7).AtMidnight();
}
/// <summary>
/// Returns the same day, at midnight
/// </summary>
/// <example>
/// DateTime startOfDay = DateTime.Now.AtMidnight();
/// </example>
/// <param name="dt">Start date</param>
public static DateTime AtMidnight(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0);
}
/// <summary>
/// Returns the same day, at midday
/// </summary>
/// <example>
/// DateTime startOfAfternoon = DateTime.Now.AtMidday();
/// </example>
/// <param name="dt">Start date</param>
public static DateTime AtMidday(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day, 12, 0, 0);
}
}
public static class Inflector
{
private static readonly List<InflectorRule> _plurals = new List<InflectorRule>();
private static readonly List<InflectorRule> _singulars = new List<InflectorRule>();
private static readonly List<string> _uncountables = new List<string>();
/// <summary>
/// Initializes the <see cref="Inflector" /> class.
/// </summary>
static Inflector()
{
AddPluralRule("$", "s");
AddPluralRule("s$", "s");
AddPluralRule("(ax|test)is$", "$1es");
AddPluralRule("(octop|vir)us$", "$1i");
AddPluralRule("(alias|status)$", "$1es");
AddPluralRule("(bu)s$", "$1ses");
AddPluralRule("(buffal|tomat)o$", "$1oes");
AddPluralRule("([ti])um$", "$1a");
AddPluralRule("sis$", "ses");
AddPluralRule("(?:([^f])fe|([lr])f)$", "$1$2ves");
AddPluralRule("(hive)$", "$1s");
AddPluralRule("([^aeiouy]|qu)y$", "$1ies");
AddPluralRule("(x|ch|ss|sh)$", "$1es");
AddPluralRule("(matr|vert|ind)ix|ex$", "$1ices");
AddPluralRule("([m|l])ouse$", "$1ice");
AddPluralRule("^(ox)$", "$1en");
AddPluralRule("(quiz)$", "$1zes");
AddSingularRule("s$", String.Empty);
AddSingularRule("ss$", "ss");
AddSingularRule("(n)ews$", "$1ews");
AddSingularRule("([ti])a$", "$1um");
AddSingularRule("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis");
AddSingularRule("(^analy)ses$", "$1sis");
AddSingularRule("([^f])ves$", "$1fe");
AddSingularRule("(hive)s$", "$1");
AddSingularRule("(tive)s$", "$1");
AddSingularRule("([lr])ves$", "$1f");
AddSingularRule("([^aeiouy]|qu)ies$", "$1y");
AddSingularRule("(s)eries$", "$1eries");
AddSingularRule("(m)ovies$", "$1ovie");
AddSingularRule("(x|ch|ss|sh)es$", "$1");
AddSingularRule("([m|l])ice$", "$1ouse");
AddSingularRule("(bus)es$", "$1");
AddSingularRule("(o)es$", "$1");
AddSingularRule("(shoe)s$", "$1");
AddSingularRule("(cris|ax|test)es$", "$1is");
AddSingularRule("(octop|vir)i$", "$1us");
AddSingularRule("(alias|status)$", "$1");
AddSingularRule("(alias|status)es$", "$1");
AddSingularRule("^(ox)en", "$1");
AddSingularRule("(vert|ind)ices$", "$1ex");
AddSingularRule("(matr)ices$", "$1ix");
AddSingularRule("(quiz)zes$", "$1");
AddIrregularRule("person", "people");
AddIrregularRule("man", "men");
AddIrregularRule("child", "children");
AddIrregularRule("sex", "sexes");
AddIrregularRule("tax", "taxes");
AddIrregularRule("move", "moves");
AddUnknownCountRule("equipment");
AddUnknownCountRule("information");
AddUnknownCountRule("rice");
AddUnknownCountRule("money");
AddUnknownCountRule("species");
AddUnknownCountRule("series");
AddUnknownCountRule("fish");
AddUnknownCountRule("sheep");
}
/// <summary>
/// Adds the irregular rule.
/// </summary>
/// <param name="singular"> The singular. </param>
/// <param name="plural"> The plural. </param>
private static void AddIrregularRule(string singular, string plural)
{
AddPluralRule(String.Concat("(", singular[0], ")", singular.Substring(1), "$"),
String.Concat("$1", plural.Substring(1)));
AddSingularRule(String.Concat("(", plural[0], ")", plural.Substring(1), "$"),
String.Concat("$1", singular.Substring(1)));
}
/// <summary>
/// Adds the unknown count rule.
/// </summary>
/// <param name="word"> The word. </param>
private static void AddUnknownCountRule(string word)
{
_uncountables.Add(word.ToLower());
}
/// <summary>
/// Adds the plural rule.
/// </summary>
/// <param name="rule"> The rule. </param>
/// <param name="replacement"> The replacement. </param>
private static void AddPluralRule(string rule, string replacement)
{
_plurals.Add(new InflectorRule(rule, replacement));
}
/// <summary>
/// Adds the singular rule.
/// </summary>
/// <param name="rule"> The rule. </param>
/// <param name="replacement"> The replacement. </param>
private static void AddSingularRule(string rule, string replacement)
{
_singulars.Add(new InflectorRule(rule, replacement));
}
/// <summary>
/// Makes the plural.
/// </summary>
/// <param name="word"> The word. </param>
/// <returns> </returns>
public static string MakePlural(this string word)
{
return ApplyRules(_plurals, word);
}
/// <summary>
/// Makes the singular.
/// </summary>
/// <param name="word"> The word. </param>
/// <returns> </returns>
public static string MakeSingular(this string word)
{
return ApplyRules(_singulars, word);
}
/// <summary>
/// Applies the rules.
/// </summary>
/// <param name="rules"> The rules. </param>
/// <param name="word"> The word. </param>
/// <returns> </returns>
private static string ApplyRules(IList<InflectorRule> rules, string word)
{
string result = word;
if (!_uncountables.Contains(word.ToLower()))
{
for (int i = rules.Count - 1; i >= 0; i--)
{
string currentPass = rules[i].Apply(word);
if (currentPass != null)
{
result = currentPass;
break;
}
}
}
return result;
}
/// <summary>
/// Converts the string to title case.
/// </summary>
/// <param name="word"> The word. </param>
/// <returns> </returns>
public static string ToTitleCase(this string word)
{
return Regex.Replace(Humanize(AddUnderscores(word)), @"\b([a-z])",
match => match.Captures[0].Value.ToUpper());
}
/// <summary>
/// Converts the string to human case.
/// </summary>
/// <param name="lowercaseAndUnderscoredWord"> The lowercase and underscored word. </param>
/// <returns> </returns>
public static string Humanize(this string lowercaseAndUnderscoredWord)
{
return MakeInitialCaps(Regex.Replace(lowercaseAndUnderscoredWord, @"_", " "));
}
/// <summary>
/// Convert string to proper case
/// </summary>
/// <param name="sourceString"> The source string. </param>
/// <returns> </returns>
public static string ToProper(this string sourceString)
{
string propertyName = sourceString.ToPascalCase();
return propertyName;
}
/// <summary>
/// Converts the string to pascal case.
/// </summary>
/// <param name="lowercaseAndUnderscoredWord"> The lowercase and underscored word. </param>
/// <returns> </returns>
public static string ToPascalCase(this string lowercaseAndUnderscoredWord)
{
return ToPascalCase(lowercaseAndUnderscoredWord, true);
}
/// <summary>
/// Converts text to pascal case...
/// </summary>
/// <param name="text"> The text. </param>
/// <param name="removeUnderscores">
/// if set to <c>true</c> [remove underscores].
/// </param>
/// <returns> </returns>
public static string ToPascalCase(this string text, bool removeUnderscores)
{
if (String.IsNullOrEmpty(text))
return text;
text = text.Replace("_", " ");
string joinString = removeUnderscores ? String.Empty : "_";
string[] words = text.Split(' ');
if (words.Length > 1 || words[0].IsUpperCase())
{
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length > 0)
{
string word = words[i];
string restOfWord = word.Substring(1);
if (restOfWord.IsUpperCase())
restOfWord = restOfWord.ToLower(CultureInfo.CurrentUICulture);
char firstChar = char.ToUpper(word[0], CultureInfo.CurrentUICulture);
words[i] = String.Concat(firstChar, restOfWord);
}
}
return String.Join(joinString, words);
}
return String.Concat(words[0].Substring(0, 1).ToUpper(CultureInfo.CurrentUICulture), words[0].Substring(1));
}
/// <summary>
/// Converts the string to camel case.
/// </summary>
/// <param name="lowercaseAndUnderscoredWord"> The lowercase and underscored word. </param>
/// <returns> </returns>
public static string ToCamelCase(this string lowercaseAndUnderscoredWord)
{
return MakeInitialLowerCase(ToPascalCase(lowercaseAndUnderscoredWord));
}
/// <summary>
/// Adds the underscores.
/// </summary>
/// <param name="pascalCasedWord"> The pascal cased word. </param>
/// <returns> </returns>
public static string AddUnderscores(this string pascalCasedWord)
{
return
Regex.Replace(
Regex.Replace(Regex.Replace(pascalCasedWord, @"([A-Z]+)([A-Z][a-z])", "$1_$2"), @"([a-z\d])([A-Z])",
"$1_$2"), @"[-\s]", "_").ToLower();
}
/// <summary>
/// Makes the initial caps.
/// </summary>
/// <param name="word"> The word. </param>
/// <returns> </returns>
public static string MakeInitialCaps(this string word)
{
return String.Concat(word.Substring(0, 1).ToUpper(), word.Substring(1).ToLower());
}
/// <summary>
/// Makes the initial lower case.
/// </summary>
/// <param name="word"> The word. </param>
/// <returns> </returns>
public static string MakeInitialLowerCase(this string word)
{
return String.Concat(word.Substring(0, 1).ToLower(), word.Substring(1));
}
/// <summary>
/// Adds the ordinal suffix.
/// </summary>
/// <param name="number"> The number. </param>
/// <returns> </returns>
public static string AddOrdinalSuffix(this string number)
{
if (number.IsNumeric())
{
int n = int.Parse(number);
int nMod100 = n % 100;
if (nMod100 >= 11 && nMod100 <= 13)
return String.Concat(number, "th");
switch (n % 10)
{
case 1:
return String.Concat(number, "st");
case 2:
return String.Concat(number, "nd");
case 3:
return String.Concat(number, "rd");
default:
return String.Concat(number, "th");
}
}
return number;
}
/// <summary>
/// Converts the underscores to dashes.
/// </summary>
/// <param name="underscoredWord"> The underscored word. </param>
/// <returns> </returns>
public static string ConvertUnderscoresToDashes(this string underscoredWord)
{
return underscoredWord.Replace('_', '-');
}
#region Nested type: InflectorRule
/// <summary>
/// Summary for the InflectorRule class
/// </summary>
private class InflectorRule
{
/// <summary>
/// </summary>
public readonly Regex regex;
/// <summary>
/// </summary>
public readonly string replacement;
/// <summary>
/// Initializes a new instance of the <see cref="InflectorRule" /> class.
/// </summary>
/// <param name="regexPattern"> The regex pattern. </param>
/// <param name="replacementText"> The replacement text. </param>
public InflectorRule(string regexPattern, string replacementText)
{
regex = new Regex(regexPattern, RegexOptions.IgnoreCase);
replacement = replacementText;
}
/// <summary>
/// Applies the specified word.
/// </summary>
/// <param name="word"> The word. </param>
/// <returns> </returns>
public string Apply(string word)
{
if (!regex.IsMatch(word))
return null;
string replace = regex.Replace(word, replacement);
if (word == word.ToUpper())
replace = replace.ToUpper();
return replace;
}
}
#endregion
}
public static class IO
{
/// <summary>
/// Read a text file and obtain it's contents.
/// </summary>
/// <param name="absolutePath"> The complete file path to write to. </param>
/// <returns> String containing the content of the file. </returns>
public static string GetFileText(this string absolutePath)
{
using (StreamReader sr = new StreamReader(absolutePath))
return sr.ReadToEnd();
}
/// <summary>
/// Creates or opens a file for writing and writes text to it.
/// </summary>
/// <param name="absolutePath"> The complete file path to write to. </param>
/// <param name="fileText"> A String containing text to be written to the file. </param>
public static void CreateToFile(this string fileText, string absolutePath)
{
using (StreamWriter sw = File.CreateText(absolutePath))
sw.Write(fileText);
}
/// <summary>
/// Update text within a file by replacing a substring within the file.
/// </summary>
/// <param name="absolutePath"> The complete file path to write to. </param>
/// <param name="lookFor"> A String to be replaced. </param>
/// <param name="replaceWith"> A String to replace all occurrences of lookFor. </param>
public static void UpdateFileText(this string absolutePath, string lookFor, string replaceWith)
{
string newText = GetFileText(absolutePath).Replace(lookFor, replaceWith);
WriteToFile(absolutePath, newText);
}
/// <summary>
/// Writes out a string to a file.
/// </summary>
/// <param name="absolutePath"> The complete file path to write to. </param>
/// <param name="fileText"> A String containing text to be written to the file. </param>
public static void WriteToFile(this string absolutePath, string fileText)
{
using (StreamWriter sw = new StreamWriter(absolutePath, false))
sw.Write(fileText);
}
/// <summary>
/// Fetches a web page
/// </summary>
/// <param name="url"> The URL. </param>
/// <returns> </returns>
public static string ReadWebPage(string url)
{
return ReadWebResponse(GetWebResponse(url));
}
public static string ReadWebResponse(WebResponse response)
{
string result = "";
using (Stream stream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
}
return result;
}
/// <summary>
/// Fetches a web page
/// </summary>
/// <param name="url"> The URL. </param>
/// <returns> </returns>
public static HttpWebResponse GetWebResponse(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
return (HttpWebResponse)request.GetResponse();
}
}
public static class Validation
{
/// <summary>
/// Determines whether the specified eval string contains only alpha characters.
/// </summary>
/// <param name="evalString"> The eval string. </param>
/// <returns>
/// <c>true</c> if the specified eval string is alpha; otherwise, <c>false</c> .
/// </returns>
public static bool IsAlpha(this string evalString)
{
return !Regex.IsMatch(evalString, RegexPattern.ALPHA);
}
/// <summary>
/// Determines whether the specified eval string contains only alphanumeric characters
/// </summary>
/// <param name="evalString"> The eval string. </param>
/// <returns>
/// <c>true</c> if the string is alphanumeric; otherwise, <c>false</c> .
/// </returns>
public static bool IsAlphaNumeric(this string evalString)
{
return !Regex.IsMatch(evalString, RegexPattern.ALPHA_NUMERIC);
}
/// <summary>
/// Determines whether the specified eval string contains only alphanumeric characters
/// </summary>
/// <param name="evalString"> The eval string. </param>
/// <param name="allowSpaces">
/// if set to <c>true</c> [allow spaces].
/// </param>
/// <returns>
/// <c>true</c> if the string is alphanumeric; otherwise, <c>false</c> .
/// </returns>
public static bool IsAlphaNumeric(this string evalString, bool allowSpaces)
{
if (allowSpaces)
return !Regex.IsMatch(evalString, RegexPattern.ALPHA_NUMERIC_SPACE);
return IsAlphaNumeric(evalString);
}
/// <summary>
/// Determines whether the specified eval string contains only numeric characters
/// </summary>
/// <param name="evalString"> The eval string. </param>
/// <returns>
/// <c>true</c> if the string is numeric; otherwise, <c>false</c> .
/// </returns>
public static bool IsNumeric(this string evalString)
{
return !Regex.IsMatch(evalString, RegexPattern.NUMERIC);
}
/// <summary>
/// Determines whether the specified email address string is valid based on regular expression evaluation.
/// </summary>
/// <param name="emailAddressString"> The email address string. </param>
/// <returns>
/// <c>true</c> if the specified email address is valid; otherwise, <c>false</c> .
/// </returns>
public static bool IsEmail(this string emailAddressString)
{
return !string.IsNullOrWhiteSpace(emailAddressString) && Regex.IsMatch(emailAddressString, RegexPattern.EMAIL, RegexOptions.IgnoreCase);
}
/// <summary>
/// Check if an input-value is of type DateTime
/// </summary>
/// <param name="value">input</param>
/// <returns>bool</returns>
public static bool IsDateTime(object value)
{
try
{
if (value == null)
return false;
DateTime dateTime = DateTime.Parse(value.ToString());
return true;
}
catch (FormatException)
{
return false;
}
}
/// <summary>
/// Returns true if date passed is valid for current date - number years range
/// </summary>
/// <param name="inDate"></param>
/// <param name="numberOfYears"></param>
/// <returns></returns>
public static bool IsDateWithinNoYears(this DateTime inDate, int numberOfYears)
{
var minDate = SystemTime.Now().AddYears(-numberOfYears).Date;
return DateTime.Compare(minDate, inDate) < 1;
}
/// <summary>
/// Determines whether the specified string is lower case.
/// </summary>
/// <param name="inputString"> The input string. </param>
/// <returns>
/// <c>true</c> if the specified string is lower case; otherwise, <c>false</c> .
/// </returns>
public static bool IsLowerCase(this string inputString)
{
return Regex.IsMatch(inputString, RegexPattern.LOWER_CASE);
}
/// <summary>
/// Determines whether the specified string is upper case.
/// </summary>
/// <param name="inputString"> The input string. </param>
/// <returns>
/// <c>true</c> if the specified string is upper case; otherwise, <c>false</c> .
/// </returns>
public static bool IsUpperCase(this string inputString)
{
return Regex.IsMatch(inputString, RegexPattern.UPPER_CASE);
}
/// <summary>
/// Determines whether the specified string is a valid GUID.
/// </summary>
/// <param name="guid"> The GUID. </param>
/// <returns>
/// <c>true</c> if the specified string is a valid GUID; otherwise, <c>false</c> .
/// </returns>
public static bool IsGuid(this string guid)
{
return Regex.IsMatch(guid, RegexPattern.GUID);
}
/// <summary>
/// Determines whether the specified string is a valid US Zip Code, using either 5 or 5+4 format.
/// </summary>
/// <param name="zipCode"> The zip code. </param>
/// <returns>
/// <c>true</c> if it is a valid zip code; otherwise, <c>false</c> .
/// </returns>
public static bool IsZIPCodeAny(this string zipCode)
{
return Regex.IsMatch(zipCode, RegexPattern.US_ZIPCODE_PLUS_FOUR_OPTIONAL);
}
/// <summary>
/// Determines whether the specified string is a valid US Zip Code, using the 5 digit format.
/// </summary>
/// <param name="zipCode"> The zip code. </param>
/// <returns>
/// <c>true</c> if it is a valid zip code; otherwise, <c>false</c> .
/// </returns>
public static bool IsZIPCodeFive(this string zipCode)
{
return Regex.IsMatch(zipCode, RegexPattern.US_ZIPCODE);
}
/// <summary>
/// Determines whether the specified string is a valid US Zip Code, using the 5+4 format.
/// </summary>
/// <param name="zipCode"> The zip code. </param>
/// <returns>
/// <c>true</c> if it is a valid zip code; otherwise, <c>false</c> .
/// </returns>
public static bool IsZIPCodeFivePlusFour(this string zipCode)
{
return Regex.IsMatch(zipCode, RegexPattern.US_ZIPCODE_PLUS_FOUR);
}
/// <summary>
/// Determines whether the specified string is a valid Social Security number. Dashes are optional.
/// </summary>
/// <param name="socialSecurityNumber"> The Social Security Number </param>
/// <returns>
/// <c>true</c> if it is a valid Social Security number; otherwise, <c>false</c> .
/// </returns>
public static bool IsSocialSecurityNumber(this string socialSecurityNumber)
{
return Regex.IsMatch(socialSecurityNumber, RegexPattern.SOCIAL_SECURITY);
}
/// <summary>
/// Determines whether the specified string is a valid IP address.
/// </summary>
/// <param name="ipAddress"> The ip address. </param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c> .
/// </returns>
public static bool IsIPAddress(this string ipAddress)
{
return Regex.IsMatch(ipAddress, RegexPattern.IP_ADDRESS);
}
/// <summary>
/// Determines whether the specified string is a valid US phone number using the referenced regex string.
/// </summary>
/// <param name="telephoneNumber"> The telephone number. </param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c> .
/// </returns>
public static bool IsUSTelephoneNumber(this string telephoneNumber)
{
return Regex.IsMatch(telephoneNumber, RegexPattern.US_TELEPHONE);
}
/// <summary>
/// Determines whether the specified string is a valid currency string using the referenced regex string.
/// </summary>
/// <param name="currency"> The currency string. </param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c> .
/// </returns>
public static bool IsUSCurrency(this string currency)
{
return Regex.IsMatch(currency, RegexPattern.US_CURRENCY);
}
/// <summary>
/// Determines whether the specified string is a valid URL string using the referenced regex string.
/// </summary>
/// <param name="url"> The URL string. </param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c> .
/// </returns>
public static bool IsURL(this string url)
{
return Regex.IsMatch(url, RegexPattern.URL);
}
/// <summary>
/// Determines whether the specified string is consider a strong password based on the supplied string.
/// </summary>
/// <param name="password"> The password. </param>
/// <returns>
/// <c>true</c> if strong; otherwise, <c>false</c> .
/// </returns>
public static bool IsStrongPassword(this string password)
{
return Regex.IsMatch(password, RegexPattern.STRONG_PASSWORD);
}
}
/// <summary>
/// Summary for the RegexPattern class
/// </summary>
public class RegexPattern
{
public const string ALPHA = "[^a-zA-Z]";
public const string ALPHA_NAME = "^[a-zA-Z ']+$";
public const string ALPHA_NUMERIC = "[^a-zA-Z0-9]";
public const string ALPHA_NUMERIC_SPACE = @"[^a-zA-Z0-9\s]";
public const string CREDIT_CARD_AMERICAN_EXPRESS = @"^(?:(?:[3][4|7])(?:\d{13}))$";
public const string CREDIT_CARD_CARTE_BLANCHE = @"^(?:(?:[3](?:[0][0-5]|[6|8]))(?:\d{11,12}))$";
public const string CREDIT_CARD_DINERS_CLUB = @"^(?:(?:[3](?:[0][0-5]|[6|8]))(?:\d{11,12}))$";
public const string CREDIT_CARD_DISCOVER = @"^(?:(?:6011)(?:\d{12}))$";
public const string CREDIT_CARD_EN_ROUTE = @"^(?:(?:[2](?:014|149))(?:\d{11}))$";
public const string CREDIT_CARD_JCB = @"^(?:(?:(?:2131|1800)(?:\d{11}))$|^(?:(?:3)(?:\d{15})))$";
public const string CREDIT_CARD_MASTER_CARD = @"^(?:(?:[5][1-5])(?:\d{14}))$";
public const string CREDIT_CARD_STRIP_NON_NUMERIC = @"(\-|\s|\D)*";
public const string CREDIT_CARD_VISA = @"^(?:(?:[4])(?:\d{12}|\d{15}))$";
//public const string EMAIL = @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
// @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$";
public const string EMBEDDED_CLASS_NAME_MATCH = "(?<=^_).*?(?=_)";
public const string EMBEDDED_CLASS_NAME_REPLACE = "^_.*?_";
public const string EMBEDDED_CLASS_NAME_UNDERSCORE_MATCH = "(?<=^UNDERSCORE).*?(?=UNDERSCORE)";
public const string EMBEDDED_CLASS_NAME_UNDERSCORE_REPLACE = "^UNDERSCORE.*?UNDERSCORE";
public const string GUID = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
public const string EMAIL = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
public const string IP_ADDRESS =
@"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
public const string LOWER_CASE = @"^[a-z]+$";
public const string NUMERIC = "[^0-9]";
public const string SOCIAL_SECURITY = @"^\d{3}[-]?\d{2}[-]?\d{4}$";
public const string SQL_EQUAL = @"\=";
public const string SQL_GREATER = @"\>";
public const string SQL_GREATER_OR_EQUAL = @"\>.*\=";
public const string SQL_IS = @"\x20is\x20";
public const string SQL_IS_NOT = @"\x20is\x20not\x20";
public const string SQL_LESS = @"\<";
public const string SQL_LESS_OR_EQUAL = @"\<.*\=";
public const string SQL_LIKE = @"\x20like\x20";
public const string SQL_NOT_EQUAL = @"\<.*\>";
public const string SQL_NOT_LIKE = @"\x20not\x20like\x20";
public const string STRONG_PASSWORD =
@"(?=^.{8,255}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*";
public const string UPPER_CASE = @"^[A-Z]+$";
public const string URL =
@"^^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_=]*)?$";
public const string US_CURRENCY = @"^\$(([1-9]\d*|([1-9]\d{0,2}(\,\d{3})*))(\.\d{1,2})?|(\.\d{1,2}))$|^\$[0](.00)?$";
public const string US_TELEPHONE = @"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$";
public const string US_ZIPCODE = @"^\d{5}$";
public const string US_ZIPCODE_PLUS_FOUR = @"^\d{5}((-|\s)?\d{4})$";
public const string US_ZIPCODE_PLUS_FOUR_OPTIONAL = @"^\d{5}((-|\s)?\d{4})?$";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment