Sunday, November 23, 2008

 

C# Extension methods library

Extension methods are a quick way to extend the types available in the CLR such as string or object and add your own methods without having to re-compile your application. If you are not familiar with Extension methods then check out ScottGu's post.

A while back I brought back an old C# class that had a collection of static 'helper methods' that we used to use back in .NET 1.1 days and decided to port it to .NET 2.0 as Extension methods.

Fortunately doing that was too simple, in fact it was just a matter of adding a this keyword to a method parameter and I had a strongly typed Extension methods class ready.

While there are dozens of Extension method libraries available at CodePlex.com but I decided to stick to my own library for now that is available for download - Extensions.cs or get the code below.

using System;
using System.Web;
using System.Web.SessionState;
using System.Collections;
using System.Text.RegularExpressions;
namespace Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class Extensions
    {
        /// <summary>
        /// Check for Positive Integers with zero inclusive  
        /// </summary>
        /// <param name="strNumber"></param>
        /// <returns></returns>
        public static bool IsWholeNumber(this string strNumber)
        {
            if (strNumber == "")
                return false;
 
            Regex objNotWholePattern = new Regex("[^0-9]");
            return !objNotWholePattern.IsMatch(strNumber);
        }
 
        /// <summary>
        /// Check if the string is Double  
        /// </summary>
        /// <param name="strNumber"></param>
        /// <returns></returns>
        public static bool IsDouble(this string strNumber)
        {
            if (strNumber == "")
                return false;
 
            try
            {
                Convert.ToDouble(strNumber);
                
            }
            catch (Exception)
            {
 
                return false;
            }
 
            return true;
 
        }
 
        /// <summary>
        ///Function to Check for AlphaNumeric. 
        /// </summary>
        /// <param name="strToCheck"> String to check for alphanumeric</param>
        /// <returns>True if it is Alphanumeric</returns>
        public static bool IsAlphaNumeric(this string strToCheck)
        {
            bool valid = true;
 
            if (strToCheck == "")
                return false;
 
            Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
 
            valid = !objAlphaNumericPattern.IsMatch(strToCheck);
            return valid;
        }
 
        /// <summary>
        ///Function to Check for valid alphanumeric input with space chars also
        /// </summary>
        /// <param name="strToCheck"> String to check for alphanumeric</param>
        /// <returns>True if it is Alphanumeric</returns>
        public static bool IsValidAlphaNumericWithSpace(this string strToCheck)
        {
            bool valid = true;
 
            if (strToCheck == "")
                return false;
 
            Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9\\s]");
 
            valid = !objAlphaNumericPattern.IsMatch(strToCheck);
            return valid;
        }
 
        /// <summary>
        /// Check for valid alphabet input with space chars also
        /// </summary>
        /// <param name="strToCheck"> String to check for alphanumeric</param>
        /// <returns>True if it is Alphanumeric</returns>
        public static bool IsValidAlphabetWithSpace(this string strToCheck)
        {
            bool valid = true;
 
            if (strToCheck == "")
                return false;
 
            Regex objAlphaNumericPattern = new Regex("[^a-zA-Z\\s]");
 
            valid = !objAlphaNumericPattern.IsMatch(strToCheck);
            return valid;
        }
 
        /// <summary>
        /// Check for valid alphabet input with space chars also
        /// </summary>
        /// <param name="strToCheck"> String to check for alphanumeric</param>
        /// <returns>True if it is Alphanumeric</returns>
        public static bool IsValidAlphabetWithHyphen(this string strToCheck)
        {
            bool valid = true;
 
            if (strToCheck == "")
                return false;
 
            Regex objAlphaNumericPattern = new Regex("[^a-zA-Z\\-]");
 
            valid = !objAlphaNumericPattern.IsMatch(strToCheck);
            return valid;
        }
 
        /// <summary>
        ///  Check for Alphabets.
        /// </summary>
        /// <param name="strToCheck">Input string to check for validity</param>
        /// <returns>True if valid alphabetic string, False otherwise</returns>
        public static bool IsAlpha(this string strToCheck)
        {
            bool valid = true;
 
            if (strToCheck == "")
                return false;
 
            Regex objAlphaPattern = new Regex("[^a-zA-Z]");
 
            valid = !objAlphaPattern.IsMatch(strToCheck);
            return valid;
        }
        
        /// <summary>
        /// Check whether the string is valid number or not
        /// </summary>
        /// <param name="strNumber">Number to check for </param>
        /// <returns>True if valid number, False otherwise</returns>
        public static bool IsNumber(this string strNumber)
        {
            try
            {
                Convert.ToDouble(strNumber);
                return true;
            }
            catch
            {
                return false;
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strInteger"></param>
        /// <returns></returns>
        public static bool IsInteger(this string strInteger)
        {
            try
            {
                Convert.ToInt32(strInteger);
                return true;
            }
            catch
            {
                return false;
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strDateTime"></param>
        /// <returns></returns>
        public static bool IsDateTime(this string strDateTime)
        {
            try
            {
                Convert.ToDateTime(strDateTime);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// Function to validate given string for HTML Injection
        /// </summary>
        /// <param name="strBuff">String to be validated</param>
        /// <returns>Boolean value indicating if given input string passes HTML Injection validation</returns>
        public static bool IsValidHTMLInjection(this string strBuff)
        {
            return (!Regex.IsMatch(HttpUtility.HtmlDecode(strBuff), "<(.|\n)+?>"));
        }
 
        /// <summary>
        /// Checks whether a valid Email address was input
        /// </summary>
        /// <param name="inputEmail">Email address to validate</param>
        /// <returns>True if valid, False otherwise</returns>
        public static bool isEmail(this string inputEmail)
        {
 
            if (inputEmail != null && inputEmail != "")
            {
                string strRegex = @"^([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})(\]?)$";
                Regex re = new Regex(strRegex);
                if (re.IsMatch(inputEmail))
                    return (true);
                else
                    return (false);
            }
            else
                return (false);
        }
 
        /// <summary>
        /// Converts a valid string to integer
        /// </summary>
        /// <param name="StringToConvert"></param>
        /// <returns></returns>
        public static int ToInteger(this string StringToConvert)
        {
            return Convert.ToInt32(StringToConvert);
        }
 
        /// <summary>
        /// Converts an Object to it's integer value
        /// </summary>
        /// <param name="ObjectToConvert"></param>
        /// <returns></returns>
        public static int ToInteger(this object ObjectToConvert)
        {
            try
            {
                return Convert.ToInt32(ObjectToConvert.ToString());
            }
            catch
            {
                throw new Exception("Object cannot be converted to Integer");
            }
        }
 
        /// <summary>
        /// Converts a valid string to double
        /// </summary>
        /// <param name="StringToConvert"></param>
        /// <returns></returns>
        public static double ToDouble(this string StringToConvert)
        {
            return Convert.ToDouble(StringToConvert);
        }
 
        /// <summary>
        /// Converts an Object to it's double value
        /// </summary>
        /// <param name="ObjectToConvert"></param>
        /// <returns></returns>
        public static double ToDouble(this object ObjectToConvert)
        {
            try
            {
                return Convert.ToDouble(ObjectToConvert.ToString());
            }
            catch
            {
                throw new Exception("Object cannot be converted to double");
            }
        }
 
        /// <summary>
        /// Converts a string to a Sentence case
        /// </summary>
        /// <param name="String"></param>
        /// <returns></returns>
        public static string ToSentence(this string String)
        {
            if (String.Length > 0)
                return String.Substring(0, 1).ToUpper();
 
            return "";
        }
 
        public static bool ToBool(this object Object)
        {
            try
            {
                return Convert.ToBoolean(Object.ToString());
            }
            catch {
                throw new Exception("Object cannot be converted to Boolean");
            }
 
        }
 
        public static DateTime ToDateTime(this string String)
        {
            try
            {
                return Convert.ToDateTime(String);
            }
            catch (Exception ex)
            {
                throw new Exception("Object cannot be converted to DateTime. Object: " + String);
            }
 
        }
    }
}


ScreenHunter_01 Nov. 23 14.13

Labels: , , , ,


Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?