Even after using .Net for years, we tend to write the same utility methods over and over again. Some people put them in external class libraries (my usually is called Parse.MySmartFunction()), but lately I began to move my utilities to into extension methods which was introduced in C# 3.0.
1. Shorten strings:
Used in almost all my web projects
public static string Shorten(this string str,int len)
{
if (str.Length > len)
{
return StripHtml(str.Substring(0, len) + "...");
}
return str;
}
2. Strip HTML from a string:
Very common in different content listings
public static string StripHtml(this string str)
{
return Regex.Replace(str, "</?[a-z][a-z0-9]*[^<>]*>|<!--.*?-->", "", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
3. Convert a string to a MD5Hashed string:
Many API calls require MD5 Hashing
public static string ToMd5HashString(this string str)
{
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] data = System.Text.Encoding.ASCII.GetBytes(str);
data = x.ComputeHash(data);
string ret = "";
for (int i = 0; i < data.Length; i++)
ret += data[i].ToString("x2").ToLower();
return ret;
}
4. Convert a XML String to a XmlNode
When you load XML from the database
public static XmlNode ToXmlNode(this string str)
{
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
nsmgr.AddNamespace("", "");
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
XmlTextReader reader = new XmlTextReader(str, XmlNodeType.Element, context);
XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);
return node;
}
5. Bytes to Megabytes:
Easy but tiresome number conversions.
public static double BytesToMegabytes(this long bytes)
{
return (bytes / 1024f) / 1024f;
}