using System; using System.Collections.Specialized; using System.Text; using System.Text.RegularExpressions; using System.Xml.Linq; namespace Neo.Afx.ComponentModel { /// /// Contains string extension methods /// public static partial class Extensions { #region ToNameValueCollection /// /// Creates a name value collection from the given query string. /// /// The query string to be converted. /// A name value collection. public static NameValueCollection ToNameValueCollection(this string queryString) { var result = new NameValueCollection(); if(string.IsNullOrEmpty(queryString)) { return result; } var nameValues = queryString.TrimStart(new[] { '?' }).Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries); foreach(var nameValue in nameValues) { var option = nameValue.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); switch(option.Length) { case 1: result.Add(option[0], string.Empty); break; case 2: result.Add(option[0], option[1]); break; } } return result; } #endregion #region Cleanse /// /// Cleanses the specified string by removing characters below value 32 and above value 255. /// /// Special characters are characters above value 255, /// all characters below this value are ANSI compatible, /// also, characters below 32 are non-printable. /// /// /// The string to be cleansed. /// The cleansed string. public static string Cleanse(this String str) { if(String.IsNullOrEmpty(str)) { return String.Empty; } var sb = new StringBuilder(); foreach(var c in str) { if(c >= 32 && c <= 255) { sb.Append(c); } else { sb.Append(""); // some replacement character } } return sb.ToString().Trim(); } #endregion #region IsEmail /// /// Determines whether the specified string is an email address. /// /// The string to be validated. /// /// true if the specified string is an email address; false otherwise. /// public static bool IsEmail(this string s) { var rx = new Regex(@"^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$"); return rx.IsMatch(s); } #endregion #region ToEnum ///// ///// Converts the string to an enum value. ///// ///// The string to be queried. ///// The enum value. //public static T ToEnum(this string s) //{ // return (T)s.ToEnum(typeof(T)); //} /// /// Converts the string to an enum value. /// /// The string to be queried. /// The type of the enum. /// The enum value. public static object ToEnum(this string s, Type enumType) { int i; return Int32.TryParse(s, out i) ? Enum.ToObject(enumType, i) : Enum.Parse(enumType, s, true); } #endregion #region ToDbValue /// /// Converts the string to Convert.DBNull if it is null or empty. /// /// The string to be queried. /// Convert.DBNull if the string is null or empty. public static object ToDbValue(this string s) { return String.IsNullOrEmpty(s) ? Convert.DBNull : s; } #endregion #region ToXElement /// /// Converts the string to an . /// /// The string to be queried. /// The or null if the string is null or empty. public static XElement ToXElement(this string s) { return String.IsNullOrEmpty(s) ? null : XElement.Parse(s); } #endregion #region AppendBracketed /// /// Appends the given string surround by square brackets. /// /// The StringBuilder to be appended. /// The string to be appended. public static void AppendBracketed(this StringBuilder sb, string s) { sb.Append('['); sb.Append(s); sb.Append(']'); } #endregion #region ToStringAll /// /// Returns a string containing all inner exception stack traces. /// /// The exception to be queried. /// A string containing all inner exception stack traces. public static string ToStringAll(this Exception ex) { var err = new StringBuilder(); do { err.AppendLine(ex.Message); err.Append(Environment.NewLine); err.Append(ex.StackTrace); err.Append(Environment.NewLine); } while((ex = ex.InnerException) != null); return err.ToString(); } #endregion #region Replace /// /// Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string. /// /// The string to be searched. /// The string to be replaced. /// The string that replaces , or null. /// One of the enumeration values that specifies the rules for the search. /// A string that is equivalent to the current string except that all instances of oldValue are replaced with newValue. public static string Replace(this string searchString, string oldValue, string newValue, StringComparison comparisonType) { return Replace(searchString, oldValue, newValue, comparisonType, -1); } static string Replace(this string searchString, string oldValue, string newValue, StringComparison comparisonType, int stringBuilderInitialSize) { if(searchString == null) { return null; } if(String.IsNullOrEmpty(oldValue)) { return searchString; } var posCurrent = 0; var lenPattern = oldValue.Length; var idxNext = searchString.IndexOf(oldValue, comparisonType); var result = new StringBuilder(stringBuilderInitialSize < 0 ? Math.Min(4096, searchString.Length) : stringBuilderInitialSize); while(idxNext >= 0) { result.Append(searchString, posCurrent, idxNext - posCurrent); result.Append(newValue); posCurrent = idxNext + lenPattern; idxNext = searchString.IndexOf(oldValue, posCurrent, comparisonType); } result.Append(searchString, posCurrent, searchString.Length - posCurrent); return result.ToString(); } #endregion } }