Monday, January 30, 2012

Best Extension Methods

Read More

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

Read More

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

Read More

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

Read More

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

Read More

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

Read More

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

Read More

Best Extension Methods: Slice of Collection

This Extension method is to get a slice of collection from a collection.
  public static IEnumerable Slice(this IEnumerable collection, int start, int end)
        {
            int index = 0;
            int count = 0;

            if (collection == null)
                throw new ArgumentNullException("collection");

            // Optimise item count for ICollection interfaces.
            if (collection is ICollection)
                count = ((ICollection)collection).Count;
            else if (collection is ICollection)
                count = ((ICollection)collection).Count;
            else
                count = collection.Count();

            // Get start/end indexes, negative numbers start at the end of the collection.
            if (start < 0)
                start += count;

            if (end < 0)
                end += count;

            foreach (var item in collection)
            {
                if (index >= end)
                    yield break;

                if (index >= start)
                    yield return item;

                ++index;
            }
        }
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: From IEnumerable To String

This extension method creates a string with specified separator from an IEnumerable List.
/// 
        /// Concatenates a specified separator String between each element of a specified enumeration, yielding a single concatenated string.
        /// 
        /// any object
        /// The enumeration
        /// A String
        /// A String consisting of the elements of value interspersed with the separator string.
        public static string ToString(this IEnumerable list, string separator)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var obj in list)
            {
                if (sb.Length > 0)
                {
                    sb.Append(separator);
                }
                sb.Append(obj);
            }
            return sb.ToString();
        }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Replace Items in Collection

This extension method replaces an item in a collection that implements the IList interface.
   /// 
        /// This extension method replaces an item in a collection that implements the IList interface.
        /// 
        /// The type of the field that we are manipulating
        /// The input list
        /// The position of the old item
        /// The item we are goint to put in it's place
        /// True in case of a replace, false if failed
        public static bool Replace(this IList thisList, int position, T item)
        {
            if (position > thisList.Count - 1)
                return false;
            // only process if inside the range of this list

            thisList.RemoveAt(position);
            // remove the old item
            thisList.Insert(position, item);
            // insert the new item at its position
            return true;
            // return success
        }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Clone

This extension method to get a clone of an object
    /// 
    /// Makes a copy from the object.
    /// Doesn't copy the reference memory, only data.
    /// 
    /// Type of the return object.
    /// Object to be copied.
    /// Returns the copied object.
    public static T Clone(this object item)
    {
        if (item != null)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();

            formatter.Serialize(stream, item);
            stream.Seek(0, SeekOrigin.Begin);

            T result = (T)formatter.Deserialize(stream);

            stream.Close();

            return result;
        }
        else
            return default(T);
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Send Email

If your application need functionality to send email at any time may be send a value of string or may be some exception then this extension method will help you.


    /// 
    /// Send an email using the supplied string.
    /// 
    /// String that will be used i the body of the email.
    /// Subject of the email.
    /// The email address from which the message was sent.
    /// The receiver of the email. 
    /// The server from which the email will be sent.  
    /// A boolean value indicating the success of the email send.
    public static bool Email(this string body, string subject, string sender, string recipient, string server)
    {
        try
        {
            // To
            //MailMessage mailMsg = new MailMessage();
            //mailMsg.To.Add(recipient);

            //// From
            //MailAddress mailAddress = new MailAddress(sender);
            //mailMsg.From = mailAddress;

            //// Subject and Body
            //mailMsg.Subject = subject;
            //mailMsg.Body = body;

            //// Init SmtpClient and send
            //SmtpClient smtpClient = new SmtpClient(server);
            //System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
            //smtpClient.Credentials = credentials;

            //smtpClient.Send(mailMsg);
        }
        catch (Exception ex)
        {
            return false;
        }

        return true;
    }

Read More

Best Extension Methods: Throw exception argument is Null

This extension method is for parameters of function where you wants that if a parameter/argument of a function is null then you want an exception to be thrown.
//Throw exception if parameters of function is null
    // eg: public Test(string input1)
    //{
    //    input1.ThrowIfArgumentIsNull("input1");
    //}
    public static void ThrowIfArgumentIsNull(this T obj, string parameterName) where T : class
    {
        if (obj == null) throw new ArgumentNullException(parameterName + " not allowed to be null");
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Resize Image

If your site has more work on displaying product images then this extension method will best suit for you application. This extension method is able to resize the image.

 public static Image ResizeAndFit(this Image image, Size newSize)
    {
        var sourceIsLandscape = image.Width > image.Height;
        var targetIsLandscape = newSize.Width > newSize.Height;

        var ratioWidth = (double)newSize.Width / (double)image.Width;
        var ratioHeight = (double)newSize.Height / (double)image.Height;

        var ratio = 0.0;

        if (ratioWidth > ratioHeight && sourceIsLandscape == targetIsLandscape)
            ratio = ratioWidth;
        else
            ratio = ratioHeight;

        int targetWidth = (int)(image.Width * ratio);
        int targetHeight = (int)(image.Height * ratio);

        var bitmap = new Bitmap(newSize.Width, newSize.Height);
        var graphics = Graphics.FromImage((Image)bitmap);

        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

        var offsetX = ((double)(newSize.Width - targetWidth)) / 2;
        var offsetY = ((double)(newSize.Height - targetHeight)) / 2;

        graphics.DrawImage(image, (int)offsetX, (int)offsetY, targetWidth, targetHeight);
        graphics.Dispose();

        return (Image)bitmap;
    }


Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Log Exception

One of the best extension method to log / email the exception of the application.
//log exception  like: try
    //{
    //    //Your stuff here
    //}
    //catch(Exception ex)
    //{
    //    ex.Log();
    //}
    public static void Log(this Exception ex, string additionalMessage = "")
    {
        StringBuilder msg = new StringBuilder();

        if (!string.IsNullOrEmpty(additionalMessage))
        {
            msg.Append(additionalMessage);
            msg.Append(Environment.NewLine);
        }

        if (ex != null)
        {
            try
            {
                Exception orgEx = ex;

                msg.Append("Exception:");
                msg.Append(Environment.NewLine);
                while (orgEx != null)
                {
                    msg.Append(orgEx.Message);
                    msg.Append(Environment.NewLine);
                    orgEx = orgEx.InnerException;
                }

                if (ex.Data != null)
                {
                    foreach (object i in ex.Data)
                    {
                        msg.Append("Data :");
                        msg.Append(i.ToString());
                        msg.Append(Environment.NewLine);
                    }
                }

                if (ex.StackTrace != null)
                {
                    msg.Append("StackTrace:");
                    msg.Append(Environment.NewLine);
                    msg.Append(ex.StackTrace.ToString());
                    msg.Append(Environment.NewLine);
                }

                if (ex.Source != null)
                {
                    msg.Append("Source:");
                    msg.Append(Environment.NewLine);
                    msg.Append(ex.Source);
                    msg.Append(Environment.NewLine);
                }

                if (ex.TargetSite != null)
                {
                    msg.Append("TargetSite:");
                    msg.Append(Environment.NewLine);
                    msg.Append(ex.TargetSite.ToString());
                    msg.Append(Environment.NewLine);
                }

                Exception baseException = ex.GetBaseException();
                if (baseException != null)
                {
                    msg.Append("BaseException:");
                    msg.Append(Environment.NewLine);
                    msg.Append(ex.GetBaseException());
                }
            }
            finally
            {
            }
        }
        // log this or email to admin return msg.ToString();
    }

Compiled BY: Rajesh Rolen

Read More

Best Extension Methods: From IEnumerable To HTML Table

This extension method is to convert IEnumerable to HTML Table String. You can use it when you wants to show values of IEnumerable on Screen in form of HTML Table.

 public static string ToHtmlTable(this IEnumerable list, string tableSyle, string headerStyle, string rowStyle, string alternateRowStyle)
    {

        var result = new StringBuilder();
        if (String.IsNullOrEmpty(tableSyle))
        {
            result.Append("<table id=\"" + typeof(T).Name + "Table\" >");
        }
        else
        {
            result.Append("<table id=\"" + typeof(T).Name + "Table\" class=\"" + tableSyle + "\" >");
        }

        var propertyArray = typeof(T).GetProperties();
        foreach (var prop in propertyArray)
        {
            if (String.IsNullOrEmpty(headerStyle))
            {
                result.AppendFormat("<th >{0}</th >", prop.Name);
            }
            else
            {
                result.AppendFormat("<th class=\"{0}\" >{1}</th >", headerStyle, prop.Name);
            }
        }

        for (int i = 0; i < list.Count(); i++)
        {
            if (!String.IsNullOrEmpty(rowStyle) && !String.IsNullOrEmpty(alternateRowStyle))
            {
                result.AppendFormat("<tr class=\"{0}\" >", i % 2 == 0 ? rowStyle : alternateRowStyle);
            }
            else
            {
                result.AppendFormat("<tr >");
            }

            foreach (var prop in propertyArray)
            {
                object value = prop.GetValue(list.ElementAt(i), null);
                result.AppendFormat("<td >{0}</td >", value ?? String.Empty);
            }
            result.AppendLine("</tr >");
        }
        result.Append("</table >");
        return result.ToString();
    }


Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Force Download a File

Below Extension method is for Force Download a file
 // full path to your file
    //var yourFilePath = HttpContext.Current.Request.PhysicalApplicationPath + "Files\yourFile.jpg";
    // save downloaded file as (name)
    //var saveFileAs = "yourFile.jpg";

    // start force download of your file
    //Response.ForceDownload(yourFilePath, saveFileAs);    
    public static void ForceDownload(this HttpResponse Response, string fullPathToFile, string outputFileName)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=" + outputFileName);
        Response.WriteFile(fullPathToFile);
        Response.ContentType = "";
        Response.End();
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: AddRange To Collection

Using below extension method we can add a multiple values to a typed collection in one go.
 //add value to collection in one statement
    public static void AddRange(this ICollection list, params S[] values)
    where S : T
    {
        foreach (S value in values)
            list.Add(value);
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Is Matching with one of any String

Using below extension method we can check that a value is matching with one of any parameter or not...

    //  below function is replacement for such condition   if(reallyLongStringVariableName == "string1" || 
    //    reallyLongStringVariableName == "string2" || 
    //    reallyLongStringVariableName == "string3")
    //{
    //  // do something....
    //}
    public static bool In(this T source, params T[] list)
    {
        if (null == source) throw new ArgumentNullException("source");
        return list.Contains(source);
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Get Core Type

Below extension method check for a type and Return underlying type if type is Nullable otherwise return the type
 /// 
    /// Return underlying type if type is Nullable otherwise return the type
    /// 
    public static Type GetCoreType(Type t)
    {
        if (t != null && IsNullable(t))
        {
            if (!t.IsValueType)
            {
                return t;
            }
            else
            {
                return Nullable.GetUnderlyingType(t);
            }
        }
        else
        {
            return t;
        }
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: IsNullable

Below Extension method provides facility to check whether the type is nullable type or not..

   /// 
    /// Determine of specified type is nullable
    /// 
    public static bool IsNullable(Type t)
    {
        return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Convert Generic List To DataTable

Below extension method converts Generic List to DataTable
/// 
    /// Convert a List{T} to a DataTable.
    /// 
    public static DataTable ToDataTable(this List items)
    {
        var tb = new DataTable(typeof(T).Name);

        PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo prop in props)
        {
            Type t = GetCoreType(prop.PropertyType);
            tb.Columns.Add(prop.Name, t);
        }

        foreach (T item in items)
        {
            var values = new object[props.Length];

            for (int i = 0; i < props.Length; i++)
            {
                values[i] = props[i].GetValue(item, null);
            }

            tb.Rows.Add(values);
        }

        return tb;
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Convert IEnumerable To DataTable

This extension method converts IEnumerable to DataTable

 public static DataTable ToDataTable(this IEnumerable items)
    {
        var tb = new DataTable(typeof(T).Name);
        PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var prop in props)
        {
            //tb.Columns.Add(prop.Name, prop.PropertyType);
            Type t = GetCoreType(prop.PropertyType);
            tb.Columns.Add(prop.Name, t);
        }

        foreach (var item in items)
        {
            var values = new object[props.Length];
            for (var i = 0; i < props.Length; i++)
            {
                values[i] = props[i].GetValue(item, null);
            }

            tb.Rows.Add(values);
        }
        return tb;
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Paging on IEnumerables

Below extension method provides easy way to perform paging on IEnumerables.
public static IEnumerable Page(this IEnumerable source, int page, int pageSize)
    {
        return source.Skip((page - 1) * pageSize).Take(pageSize);
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Paging on IQueryable

Below extension methods allow easy way to perform paging on IQueryables.

public static IQueryable Page(this IQueryable source, int page, int pageSize)
    {
        return source.Skip((page - 1) * pageSize).Take(pageSize);
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Convert To Double

Below extension method converts a value/object to double and if its not convertible then returns 0.0;
//use it like: string s=4.5; double d = s.ToDouble();
public static double ToDouble(this object source)
    {
        double val = 0;
        if (source != null)
        {
            string str = Convert.ToString(source);
            if (! string.IsNullOrEmpty(str))
            {
                double.TryParse(str, out val);

            }
        }
        return val;
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Convert To Integer

below extension methods converts an object/double/string to integer and if its not convertable then returns 0.

 public static int ToInt(this object source)
    {
        int val = 0;
        if (source != null)
        {
            string str = Convert.ToString(source);
            if (!string.IsNullOrEmpty(str))
            {                
                int.TryParse(str, out val);
                if (val <= 0)
                {
                    try
                    {

                        val = (int)Convert.ToDouble(str);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
        return val;
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Type Conversion

Using below extension method you can convert one type to another type.
 public static T To(this object input) where T : IConvertible
    {
        string type = typeof(T).Name;

        TypeCode typecode;
        if (!Enum.TryParse(type, out typecode)) throw new ArgumentException("Could not convert!");

        return (T)Convert.ChangeType(input, typecode);
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: IsNull

This is very simple but very useful to get rid of using == null again and again.. just type obj.isNull() and its done..
public static bool IsNull(this object source)
    {
        return source == null;
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Convert Enum To Dictionary

Using below extension method you can convert a enum to a dictionary type.
/// 
    /// Converts Enumeration type into a dictionary of names and values
    /// 
    /// Enum type
    public static IDictionary EnumToDictionary(this Type t)
    {
        if (t == null) throw new NullReferenceException();
        if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration");

        string[] names = Enum.GetNames(t);
        Array values = Enum.GetValues(t);

        return (from i in Enumerable.Range(0, names.Length)
                select new { Key = names[i], Value = (int)values.GetValue(i) })
                    .ToDictionary(k => k.Key, k => k.Value);
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Value Exists Between

Using below extension method you can check that the value exists in between of a range or not.
//you can use it like: int a=10; if(a.Between(2,20)){...do some work...}
public static bool Between(this T me, T lower, T upper) where T : IComparable
    {
        return me.CompareTo(lower) >= 0 && me.CompareTo(upper) < 0;
    }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Execute If Not Null

This is very useful extension method.In a situation where we wants to execute a function if object is not null and if null then return some default value in that scenario we can use this extension method. Now we need not to write if..else code for checking null again and again.
///Use it like:
    /// var username = HttpContext.Current.IfNotNull( ctx => ctx.User.IfNotNull( user => user.Identity.IfNotNull( iden => iden.Name ) ) );

    public static TResult IfNotNull(this T target, Func getValue)
    {
        if (target != null)
            return getValue(target);
        else
            return default(TResult);
    }

Compiled By: Rajesh Rolen

Read More

Wednesday, January 25, 2012

Setup ASP.NET MVC3 on IIS 5

These are steps to setup MVC3 project on IIS 5 1. Right click on Default Web Site and click Properties
2. Make sure the website or virtual directory is an Application.
3. Set permissions to Scripts Only
4. Click Configuration. Under the Mappings tab, click the Add button
5. You need to insert the path to the file aspnet_isapi.dll. This is most likely C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll.
6. In the Extension field, enter “.*” (excluding quotes).
7. Select All Verbs. Select “Script Engine”. Make sure ”Check that file exists” is not selected.
8. Here’s the bug. “.*” This isn’t a valid extension in IIS 5.1 so the OK button is disabled. Click in the
Extension field, then in the Executable field, and the OK button should be enabled! Click OK at this point.

Compiled By: Rajesh Rolen

Read More
Powered By Blogger · Designed By Seo Blogger Templates