Monday, January 30, 2012

Best Extension Methods: Cookie Extension Methods

Best Cookies Extension Methods
public static class CookieExtensions
{

    /// 
    /// Sets a persistent cookie which expires after the given number of days
    /// 
    /// The HtmDocument to extend
    /// the cookie key
    /// the cookie value
    /// The number of days before the cookie expires
    public static void SetCookie(this HtmlDocument doc, string key, string value, int days)
    {
        DateTime expiration = DateTime.UtcNow + TimeSpan.FromDays(days);
        SetCookie(doc, key, value, expiration);
    }

    /// 
    /// Sets a persistent cookie with an expiration date
    /// 
    /// The HtmDocument to extend
    /// the cookie key
    /// the cookie value
    public static void SetCookie(this HtmlDocument doc, string key, string value, DateTime expiration)
    {
        string oldCookie = doc.GetProperty("cookie") as String;
        string cookie = String.Format("{0}={1};expires={2}", key, value, expiration.ToString("R"));
        doc.SetProperty("cookie", cookie);
    }

    /// 
    /// Retrieves an existing cookie
    /// 
    /// The HtmDocument to extend
    /// cookie key
    /// null if the cookie does not exist, otherwise the cookie value
    public static string GetCookie(this HtmlDocument doc, string key)
    {
        string[] cookies = doc.Cookies.Split(';');
        key += '=';
        foreach (string cookie in cookies)
        {
            string cookieStr = cookie.Trim();
            if (cookieStr.StartsWith(key, StringComparison.OrdinalIgnoreCase))
            {
                string[] vals = cookieStr.Split('=');

                if (vals.Length >= 2)
                {
                    return vals[1];
                }

                return string.Empty;
            }
        }

        return null;
    }

    /// 
    /// Deletes a specified cookie by setting its value to empty and expiration to -1 days
    /// 
    /// The HtmDocument to extend
    /// the cookie key to delete
    public static void DeleteCookie(this HtmlDocument doc, string key)
    {
        string oldCookie = doc.GetProperty("cookie") as String;
        DateTime expiration = DateTime.UtcNow - TimeSpan.FromDays(1);
        string cookie = String.Format("{0}=;expires={1}", key, expiration.ToString("R"));
        doc.SetProperty("cookie", cookie);
    }
}

Compiled By: Rajesh Rolen

Best Extension Methods: HTTP Extension Methods

Best Http Extension Methods
public static class HttpExtension
{
    public static string HtmlEncode(this string data)
    {
        return HttpUtility.HtmlEncode(data);
    }

    public static string HtmlDecode(this string data)
    {
        return HttpUtility.HtmlDecode(data);
    }

    public static NameValueCollection ParseQueryString(this string query)
    {
        return HttpUtility.ParseQueryString(query);
    }

    public static string UrlEncode(this string url)
    {
        return HttpUtility.UrlEncode(url);
    }

    public static string UrlDecode(this string url)
    {
        return HttpUtility.UrlDecode(url);
    }

    public static string UrlPathEncode(this string url)
    {
        return HttpUtility.UrlPathEncode(url);
    }
}


Compiled By: Rajesh Rolen

Best Extension Methods: String Extension Methods

Best String Extension Methods

public static class StringExtensions
{
    /// 
    /// if the string is NULL, converts it to string.empty. Helpful when trying to avoid null conditions.
    /// 
    /// 
    /// 
    public static string IsNullThenEmpty(this string inString)
    {
        if (inString == null)
            return string.Empty;
        else
            return inString;
    }			

    public static string[] GetStringInBetween(this string strSource, string strBegin, string strEnd, bool includeBegin, bool includeEnd)
    {

        string[] result = { "", "" };

        int iIndexOfBegin = strSource.IndexOf(strBegin);

        if (iIndexOfBegin != -1)
        {

            // include the Begin string if desired

            if (includeBegin)

                iIndexOfBegin -= strBegin.Length;

            strSource = strSource.Substring(iIndexOfBegin

                + strBegin.Length);

            int iEnd = strSource.IndexOf(strEnd);

            if (iEnd != -1)
            {

                // include the End string if desired

                if (includeEnd)

                    iEnd += strEnd.Length;

                result[0] = strSource.Substring(0, iEnd);

                // advance beyond this segment

                if (iEnd + strEnd.Length < strSource.Length)

                    result[1] = strSource.Substring(iEnd

                        + strEnd.Length);

            }

        }

        else

            // stay where we are

            result[1] = strSource;

        return result;

    }

    public static T ToEnum(this string value)
       where T : struct
    {
       
        //Debug.Assert(!string.IsNullOrEmpty(value));
        return (T)Enum.Parse(typeof(T), value, true);
    }
    public static string Nl2Br(this string s)
    {
        return s.Replace("\r\n", "
").Replace("\n", "
"); } public static string Format(this string format, object arg, params object[] additionalArgs) { if (additionalArgs == null || additionalArgs.Length == 0) { return string.Format(format, arg); } else { return string.Format(format, new object[] { arg }.Concat(additionalArgs).ToArray()); } } public static bool ContainsAny(this string theString, char[] characters) { foreach (char character in characters) { if (theString.Contains(character.ToString())) { return true; } } return false; } /// /// Strip a string of the specified substring. /// /// the string to process /// substring to remove /// /// string s = "abcde"; /// /// s = s.Strip("bcd"); //s becomes 'ae; /// /// public static string Strip(this string s, string subString) { s = s.Replace(subString, ""); return s; } /// /// Strip a string of the specified character. /// /// the string to process /// character to remove from the string /// /// string s = "abcde"; /// /// s = s.Strip('b'); //s becomes 'acde; /// /// public static string Strip(this string s, char character) { s = s.Replace(character.ToString(), ""); return s; } /// /// Strip a string of the specified characters. /// /// the string to process /// list of characters to remove from the string /// /// string s = "abcde"; /// /// s = s.Strip('a', 'd'); //s becomes 'bce; /// /// public static string Strip(this string s, params char[] chars) { foreach (char c in chars) { s = s.Replace(c.ToString(), ""); } return s; } /// /// Splits a string into a NameValueCollection, where each "namevalue" is separated by /// the "OuterSeparator". The parameter "NameValueSeparator" sets the split between Name and Value. /// Example: /// String str = "param1=value1;param2=value2"; /// NameValueCollection nvOut = str.ToNameValueCollection(';', '='); /// /// The result is a NameValueCollection where: /// key[0] is "param1" and value[0] is "value1" /// key[1] is "param2" and value[1] is "value2" /// /// String to process /// Separator for each "NameValue" /// Separator for Name/Value splitting /// public static NameValueCollection ToNameValueCollection(this String str, Char OuterSeparator, Char NameValueSeparator) { NameValueCollection nvText = null; str = str.TrimEnd(OuterSeparator); if (!String.IsNullOrEmpty(str)) { String[] arrStrings = str.TrimEnd(OuterSeparator).Split(OuterSeparator); foreach (String s in arrStrings) { Int32 posSep = s.IndexOf(NameValueSeparator); String name = s.Substring(0, posSep); String value = s.Substring(posSep + 1); if (nvText == null) nvText = new NameValueCollection(); nvText.Add(name, value); } } return nvText; } /// /// Truncates the string to a specified length and replace the truncated to a ... /// /// string that will be truncated /// total length of characters to maintain before the truncate happens /// truncated string public static string Truncate(this string text, int maxLength) { // replaces the truncated string to a ... const string suffix = "..."; string truncatedString = text; if (maxLength <= 0) return truncatedString; int strLength = maxLength - suffix.Length; if (strLength <= 0) return truncatedString; if (text == null || text.Length <= maxLength) return truncatedString; truncatedString = text.Substring(0, strLength); truncatedString = truncatedString.TrimEnd(); truncatedString += suffix; return truncatedString; } /// /// Returns the last few characters of the string with a length /// specified by the given parameter. If the string's length is less than the /// given length the complete string is returned. If length is zero or /// less an empty string is returned /// /// the string to process /// Number of characters to return /// public static string Right(this string s, int length) { length = Math.Max(length, 0); if (s.Length > length) { return s.Substring(s.Length - length, length); } else { return s; } } public static String left(this String s, int len) { return s.Substring(0, Math.Min(len, s.Length)); } public static DateTime ToDateFromDDMMYYYY(this string date) { return DateTime.ParseExact(date, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); } //Format string to Title case public static string ToTitleCase(this string mText) { if (mText == null) return mText; System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; System.Globalization.TextInfo textInfo = cultureInfo.TextInfo; // TextInfo.ToTitleCase only operates on the string if is all lower case, otherwise it returns the string unchanged. return textInfo.ToTitleCase(mText.ToLower()); } /// /// Parses a string into an Enum /// /// The type of the Enum /// String value to parse /// The Enum corresponding to the stringExtensions public static T EnumParse(this string value) { return EnumParse(value, false); } public static T EnumParse(this string value, bool ignorecase) { if (value == null) { throw new ArgumentNullException("value"); } value = value.Trim(); if (value.Length == 0) { throw new ArgumentException("Must specify valid information for parsing in the string.", "value"); } Type t = typeof(T); if (!t.IsEnum) { throw new ArgumentException("Type provided must be an Enum.", "T"); } return (T)Enum.Parse(t, value, ignorecase); } // Enable quick and more natural string.Format calls public static string F(this string s, params object[] args) { return string.Format(s, args); } public static DateTime? ToDateTime(this string source) { if (!string.IsNullOrEmpty(source)) { return Convert.ToDateTime(source); } return null; } public static int? ToNullableInt(this string source) { var i = 0; return int.TryParse(source, out i) ? (int?)i : null; } public static string ToPlural(this string singular) { // Multiple words in the form A of B : Apply the plural to the first word only (A) int index = singular.LastIndexOf(" of "); if (index > 0) return (singular.Substring(0, index)) + singular.Remove(0, index).ToPlural(); // single Word rules //sibilant ending rule if (singular.EndsWith("sh")) return singular + "es"; if (singular.EndsWith("ch")) return singular + "es"; if (singular.EndsWith("us")) return singular + "es"; if (singular.EndsWith("ss")) return singular + "es"; //-ies rule if (singular.EndsWith("y")) return singular.Remove(singular.Length - 1, 1) + "ies"; // -oes rule if (singular.EndsWith("o")) return singular.Remove(singular.Length - 1, 1) + "oes"; // -s suffix rule return singular + "s"; } public static bool IsValidEmailAddress(this string s) { Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"); return regex.IsMatch(s); } /// /// Converts a string into a "SecureString" /// /// Input String /// public static System.Security.SecureString ToSecureString(this String str) { System.Security.SecureString secureString = new System.Security.SecureString(); foreach (Char c in str) secureString.AppendChar(c); return secureString; } public static string ToProperCase(this string text) { System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; System.Globalization.TextInfo textInfo = cultureInfo.TextInfo; return textInfo.ToTitleCase(text); } public static bool IsNumeric(this string theValue) { long retNum; return long.TryParse(theValue, System.Globalization.NumberStyles.Integer, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum); } public static bool IsNotNullOrEmpty(this string input) { return !String.IsNullOrEmpty(input); } public static bool IsNullOrEmpty(this string input) { return String.IsNullOrEmpty(input); } public static bool IsNotNullOrEmptyOrSpace(this string input) { if (!String.IsNullOrEmpty(input)) { return !String.IsNullOrEmpty(input.Trim()); } else { return true; } } public static bool IsNullOrEmptyOrSpace(this string input) { if (!String.IsNullOrEmpty(input)) { return String.IsNullOrEmpty(input.Trim()); } else { return true; } } /// /// Count all words in a given string /// /// string to begin with /// int public static int WordCount(this string input) { var count = 0; try { // Exclude whitespaces, Tabs and line breaks var re = new Regex(@"[^\s]+"); var matches = re.Matches(input); count = matches.Count; } catch { } return count; } }

Compiled By: Rajesh Rolen

Best Extension Methods: Date and Time

Best Extension Methods for Date and time

public static class DateExtensions
{

    /// 
    /// DateDiff in SQL style. 
    /// Datepart implemented: 
    ///     "year" (abbr. "yy", "yyyy"), 
    ///     "quarter" (abbr. "qq", "q"), 
    ///     "month" (abbr. "mm", "m"), 
    ///     "day" (abbr. "dd", "d"), 
    ///     "week" (abbr. "wk", "ww"), 
    ///     "hour" (abbr. "hh"), 
    ///     "minute" (abbr. "mi", "n"), 
    ///     "second" (abbr. "ss", "s"), 
    ///     "millisecond" (abbr. "ms").
    /// 
    /// 
    /// 
    /// 
    public static Int64 DateDiff(this DateTime StartDate, String DatePart, DateTime EndDate)
    {
        Int64 DateDiffVal = 0;
        System.Globalization.Calendar cal = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;
        TimeSpan ts = new TimeSpan(EndDate.Ticks - StartDate.Ticks);
        switch (DatePart.ToLower().Trim())
        {
            #region year
            case "year":
            case "yy":
            case "yyyy":
                DateDiffVal = (Int64)(cal.GetYear(EndDate) - cal.GetYear(StartDate));
                break;
            #endregion

            #region quarter
            case "quarter":
            case "qq":
            case "q":
                DateDiffVal = (Int64)((((cal.GetYear(EndDate)
                                    - cal.GetYear(StartDate)) * 4)
                                    + ((cal.GetMonth(EndDate) - 1) / 3))
                                    - ((cal.GetMonth(StartDate) - 1) / 3));
                break;
            #endregion

            #region month
            case "month":
            case "mm":
            case "m":
                DateDiffVal = (Int64)(((cal.GetYear(EndDate)
                                    - cal.GetYear(StartDate)) * 12
                                    + cal.GetMonth(EndDate))
                                    - cal.GetMonth(StartDate));
                break;
            #endregion

            #region day
            case "day":
            case "d":
            case "dd":
                DateDiffVal = (Int64)ts.TotalDays;
                break;
            #endregion

            #region week
            case "week":
            case "wk":
            case "ww":
                DateDiffVal = (Int64)(ts.TotalDays / 7);
                break;
            #endregion

            #region hour
            case "hour":
            case "hh":
                DateDiffVal = (Int64)ts.TotalHours;
                break;
            #endregion

            #region minute
            case "minute":
            case "mi":
            case "n":
                DateDiffVal = (Int64)ts.TotalMinutes;
                break;
            #endregion

            #region second
            case "second":
            case "ss":
            case "s":
                DateDiffVal = (Int64)ts.TotalSeconds;
                break;
            #endregion

            #region millisecond
            case "millisecond":
            case "ms":
                DateDiffVal = (Int64)ts.TotalMilliseconds;
                break;
            #endregion

            default:
                throw new Exception(String.Format("DatePart \"{0}\" is unknown", DatePart));
        }
        return DateDiffVal;
    }
    public static string ToStringDDMMYYYYFromDate(this DateTime date)
    {
        if (date == null)
        {
            return "";
        }
        else
        {
            return date.ToString("dd/MM/yyyy");

        }
    }
    public static string ToStringDDMMYYYYFromDate(this DateTime? date)
    {
        if (date == null)
        {
            return "";
        }
        else
        {
            return ((DateTime)date).ToString("dd-MM-yyyy");

        }
    }
    static public int Age(this DateTime dateOfBirth)
    {
        if (DateTime.Today.Month < dateOfBirth.Month ||
        DateTime.Today.Month == dateOfBirth.Month &&
         DateTime.Today.Day < dateOfBirth.Day)
        {
            return DateTime.Today.Year - dateOfBirth.Year - 1;
        }
        else
            return DateTime.Today.Year - dateOfBirth.Year;
    }
    public static string ToFriendlyDateString(this DateTime Date)
    {
        string FormattedDate = "";
        if (Date.Date == DateTime.Today)
        {
            FormattedDate = "Today";
        }
        else if (Date.Date == DateTime.Today.AddDays(-1))
        {
            FormattedDate = "Yesterday";
        }
        else if (Date.Date > DateTime.Today.AddDays(-6))
        {
            // *** Show the Day of the week
            FormattedDate = Date.ToString("dddd").ToString();
        }
        else
        {
            FormattedDate = Date.ToString("MMMM dd, yyyy");
        }

        //append the time portion to the output
        FormattedDate += " @ " + Date.ToString("t").ToLower();
        return FormattedDate;
    }
    public static bool IsWeekend(this DayOfWeek d)
    {
        return !d.IsWeekday();
    }

    public static bool IsWeekday(this DayOfWeek d)
    {
        switch (d)
        {
            case DayOfWeek.Sunday:
            case DayOfWeek.Saturday: return false;

            default: return true;
        }
    }

    public static DateTime AddWorkdays(this DateTime d, int days)
    {
        // start from a weekday
        while (d.DayOfWeek.IsWeekday()) d = d.AddDays(1.0);
        for (int i = 0; i < days; ++i)
        {
            d = d.AddDays(1.0);
            while (d.DayOfWeek.IsWeekday()) d = d.AddDays(1.0);
        }
        return d;
    }
    public static string FirstDayOfMonth(this DateTime date)
    {
        return new DateTime(date.Year, date.Month, 1).ToString("MM/dd/yyyy");
    }

    public static string LastDayOfMonth(this DateTime date)
    {
        return new DateTime(DateTime.Now.Year, DateTime.Now.Month + 1, 1).AddDays(-1).ToString("MM/dd/yyyy");
    }
    /// 
    /// Converts a regular DateTime to a RFC822 date string.
    /// 
    /// The specified date formatted as a RFC822 date string.
    public static string ToRFC822DateString(this DateTime date)
    {
        int offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours;
        string timeZone = "+" + offset.ToString().PadLeft(2, '0');
        if (offset < 0)
        {
            int i = offset * -1;
            timeZone = "-" + i.ToString().PadLeft(2, '0');
        }
        return date.ToString("ddd, dd MMM yyyy HH:mm:ss " + timeZone.PadRight(5, '0'), System.Globalization.CultureInfo.GetCultureInfo("en-US"));
    }
}

Compiled By: Rajesh Rolen

Best Extension Methods: JSON

These are best extension methods for JSON
public static class Json
{

    public static string ToJson(this object obj)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Serialize(obj);
    }

    public static string ToJson(this object obj, int recursionDepth)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        serializer.RecursionLimit = recursionDepth;
        return serializer.Serialize(obj);
    }

    public static T FromJson(this object obj)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Deserialize(obj as string);
    }
}

Compiled By: Rajesh Rolen

Best Extension Methods: Extensions for Datatable and Datareader

Best Extension Methods for DataTable and DataReader
public static class DataTableReaderExtension
{
    #region Select Distinct
    /// 
    /// "SELECT DISTINCT" over a DataTable
    /// 
    /// Input DataTable
    /// Fields to select (distinct)
    /// 
    public static DataTable SelectDistinct(this DataTable SourceTable, String FieldName)
    {
        return SelectDistinct(SourceTable, FieldName, String.Empty);
    }

    /// 
    ///"SELECT DISTINCT" over a DataTable
    /// 
    /// Input DataTable
    /// Fields to select (distinct)
    /// Optional filter to be applied to the selection
    /// 
    public static DataTable SelectDistinct(this DataTable SourceTable, String FieldNames, String Filter)
    {
        DataTable dt = new DataTable();
        String[] arrFieldNames = FieldNames.Replace(" ", "").Split(',');
        foreach (String s in arrFieldNames)
        {
            if (SourceTable.Columns.Contains(s))
                dt.Columns.Add(s, SourceTable.Columns[s].DataType);
            else
                throw new Exception(String.Format("The column {0} does not exist.", s));
        }

        Object[] LastValues = null;
        foreach (DataRow dr in SourceTable.Select(Filter, FieldNames))
        {
            Object[] NewValues = GetRowFields(dr, arrFieldNames);
            if (LastValues == null || !(ObjectComparison(LastValues, NewValues)))
            {
                LastValues = NewValues;
                dt.Rows.Add(LastValues);
            }
        }

        return dt;
    }
    #endregion

    #region Private Methods
    private static Object[] GetRowFields(DataRow dr, String[] arrFieldNames)
    {
        if (arrFieldNames.Length == 1)
            return new Object[] { dr[arrFieldNames[0]] };
        else
        {
            ArrayList itemArray = new ArrayList();
            foreach (String field in arrFieldNames)
                itemArray.Add(dr[field]);

            return itemArray.ToArray();
        }
    }

    /// 
    /// Compares two values to see if they are equal. Also compares DBNULL.Value.
    /// 
    /// Object A
    /// Object B
    /// 
    private static Boolean ObjectComparison(Object a, Object b)
    {
        if (a == DBNull.Value && b == DBNull.Value) //  both are DBNull.Value
            return true;
        if (a == DBNull.Value || b == DBNull.Value) //  only one is DBNull.Value
            return false;
        return (a.Equals(b));  // value type standard comparison
    }

    /// 
    /// Compares two value arrays to see if they are equal. Also compares DBNULL.Value.
    /// 
    /// Object Array A
    /// Object Array B
    /// 
    private static Boolean ObjectComparison(Object[] a, Object[] b)
    {
        Boolean retValue = true;
        Boolean singleCheck = false;

        if (a.Length == b.Length)
            for (Int32 i = 0; i < a.Length; i++)
            {
                if (!(singleCheck = ObjectComparison(a[i], b[i])))
                {
                    retValue = false;
                    break;
                }
                retValue = retValue && singleCheck;
            }

        return retValue;
    }
    #endregion
    /// 
    /// Checks if a column exists in the DataReader
    /// 
    /// DataReader
    /// Name of the column to find
    /// Returns true if the column exists in the DataReader, else returns false
    public static Boolean ColumnExists(this IDataReader dr, String ColumnName)
    {
        for (Int32 i = 0; i < dr.FieldCount; i++)
            if (dr.GetName(i).Equals(ColumnName, StringComparison.OrdinalIgnoreCase))
                return true;

        return false;
    }




}

Compiled By: Rajesh Rolen

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Web Hosting Bluehost