robbanp
I'm the co-founder of this website and the tech lead. Follow me on: twitter.com/robertpohl
Blog

The Rob blog

I'm Robert Pohl, the creator and co-founder to ThatsToday. I blog mostly about technology and internet related topics. Follow me on Twitter @robertpohl
Subscribe to RSS

 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;
        }

 

Comments on this article

Add your comment
Sign In

Not a member yet?

Signing up is FREE and will only take 15 seconds!

Facebook Login

Sign In

E-mail address:
Password:
Remember me
Sponsored links
AdUniver.se - ad platform Create wish-list e-böcker ljudböcker till din ipad android läsplatta dator

Close