Thursday, 21 June 2012

Extension method

 /// <summary>
    /// Extension methods allow you to easily extend a type,
    /// such as an integer or string, without re-compiling or modifying the type.
    /// In essence, they are a type of static (shared in VB) method,
    /// but they are called as if the method is native to the type.
    /// </summary>
    public static class Extensions
    {

        /// <summary>
        /// Check for Positive Integers with zero inclusive 
        /// </summary>
        /// <param name="strNumber"></param>
        /// <returns></returns>
        public static string HtmlEncode(this string String)
        {

            if (String == "")
                return "";


            return HttpUtility.HtmlEncode(String);

        }

        /// <summary>
        /// Check for Positive Integers with zero inclusive 
        /// </summary>
        /// <param name="strNumber"></param>
        /// <returns></returns>
        public static string HtmlDecode(this string String)
        {

            if (String == "")
                return "";


            return HttpUtility.HtmlDecode(String);

        }

        /// <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
            {
                if (string.IsNullOrEmpty(strInteger))
                    return false;


                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>
        /// Does the string contains text? Same as (IsNullOrEmpty() == false).
        /// </summary>
        /// <param name="txt">Text to look at.</param>
        /// <returns>True if valid and string text.</returns>
        public static bool IsStringNullOrEmpty(this string txt)
        {
            return string.IsNullOrEmpty(txt) == 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)
        {

            try
            {
                return Convert.ToInt32(StringToConvert.ToString());
            }
            catch
            {
                throw new Exception("String could not be converted to Integer");
            }
        }

        /// <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 an Object to it's integer value
        /// </summary>
        /// <param name="ObjectToConvert"></param>
        /// <returns></returns>
        public static long ToLong(this object ObjectToConvert)
        {
            try
            {
                return Convert.ToInt64(ObjectToConvert.ToString());
            }
            catch
            {
                throw new Exception("Object cannot be converted to Long");
            }
        }

        /// <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 an Object to it's decimal value
        /// </summary>
        /// <param name="ObjectToConvert"></param>
        /// <returns></returns>
        public static decimal ToDecimal(this object ObjectToConvert)
        {
            try
            {
                return Convert.ToDecimal(ObjectToConvert.ToString());
            }
            catch
            {
                throw new Exception("Object cannot be converted to decimal");
            }
        }

        /// <summary>
        /// Converts an String to it's decimal value
        /// </summary>
        /// <param name="ObjectToConvert"></param>
        /// <returns></returns>
        public static decimal ToDecimal(this string StringToConvert)
        {

            try
            {
                return Convert.ToDecimal(StringToConvert.ToString());
            }
            catch
            {
                throw new Exception("String cannot be converted to decimal");
            }
        }

        /// <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() + String.Substring(1, String.Length - 1);

            return "";

        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="format"></param>
        /// <param name="arg"></param>
        /// <param name="additionalArgs"></param>
        /// <returns></returns>
        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());
            }
        }    


        /// <summary>
        /// This extension method replaces an item in a collection that implements the IList interface.
        /// </summary>
        /// <typeparam name="T">The type of the field that we are manipulating</typeparam>
        /// <param name="thisList">The input list</param>
        /// <param name="position">The position of the old item</param>
        /// <param name="item">The item we are goint to put in it's place</param>
        /// <returns>True in case of a replace, false if failed</returns>
        public static bool Replace<T>(this IList<T> 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
        }

        /// <summary>
        /// Returns an enumerable collection of the specified type containing the substrings in this instance that are delimited by elements of a specified Char array
        /// </summary>
        /// <param name="str">The string.</param>
        /// <param name="separator">
        /// An array of Unicode characters that delimit the substrings in this instance, an empty array containing no delimiters, or null.
        /// </param>
        /// <typeparam name="T">
        /// The type of the elemnt to return in the collection, this type must implement IConvertible.
        /// </typeparam>
        /// <returns>
        /// An enumerable collection whose elements contain the substrings in this instance that are delimited by one or more characters in separator.
        /// </returns>
        public static IEnumerable<T> SplitTo<T>(this string str, params char[] separator) where T : IConvertible
        {
            foreach (var s in str.Split(separator, StringSplitOptions.None))
                yield return (T)Convert.ChangeType(s, typeof(T));
        }

        /// <summary>
        /// Returns true when a string is a valid url
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static bool IsValidUrl(this string text)
        {
            Regex rx = new Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
            return rx.IsMatch(text);
        }

        /// <summary>
        /// Adds an element to an IEnumerable (System.Linq.Concat only adds multiple elements)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target"></param>
        /// <param name="element"></param>
        /// <returns></returns>
        static IEnumerable<T> Concat<T>(IEnumerable<T> target, T element)
        {
            foreach (T e in target) yield return e;
            yield return element;
        }

        /// <summary>
        /// Converts an Array of arbitrary type to an array of type T. If a suitable converter
        /// cannot be found to do the conversion, a NotSupportedException is thrown.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ar"></param>
        /// <returns></returns>
        public static T[] ConvertTo<T>(this Array ar)
        {
            T[] ret = new T[ar.Length];
            System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
            if (tc.CanConvertFrom(ar.GetValue(0).GetType()))
            {
                for (int i = 0; i < ar.Length; i++)
                {
                    ret[i] = (T)tc.ConvertFrom(ar.GetValue(i));
                }
            }
            else
            {
                tc = System.ComponentModel.TypeDescriptor.GetConverter(ar.GetValue(0).GetType());
                if (tc.CanConvertTo(typeof(T)))
                {
                    for (int i = 0; i < ar.Length; i++)
                    {
                        ret[i] = (T)tc.ConvertTo(ar.GetValue(i), typeof(T));
                    }
                }
                else
                {
                    throw new NotSupportedException();
                }
            }
            return ret;
        }

        /// <summary>
        /// Object can be converted to Boolean
        /// </summary>
        /// <param name="Object"></param>
        /// <returns></returns>
        public static bool ToBool(this object Object)
        {
            try
            {
                return Convert.ToBoolean(Object.ToString());
            }
            catch
            {
                throw new Exception("Object cannot be converted to Boolean");
            }

        }

        /// <summary>
        /// String can be converted to DateTime
        /// </summary>
        /// <param name="String"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(this string String)
        {
            try
            {
                return Convert.ToDateTime(String);
            }
            catch
            {
                throw new Exception("Object cannot be converted to DateTime. Object: " + String);
            }
        }

        /// <summary>
        /// Object can be converted to DateTime
        /// </summary>
        /// <param name="Object"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(this object Object)
        {
            try
            {
                return Convert.ToDateTime(Convert.ToString(Object));
            }
            catch
            {
                throw new Exception("Object cannot be converted to DateTime. Object: " + Object);
            }
        }

        /// <summary>
        /// Get String First 3 Characters
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetFirstThreeCharacters(this String str)
        {
            if (str.Length < 3)
            {
                return str;
            }
            else
            {
                return str.Substring(0, 3);
            }
        }

        /// <summary>
        /// Returns the index of the first occurrence in a sequence by using the default equality comparer.
        /// </summary>
        /// <typeparam name="TSource">The type of the elements of source.</typeparam>
        /// <param name="list">A sequence in which to locate a value.</param>
        /// <param name="value">The object to locate in the sequence</param>
        /// <returns>The zero-based index of the first occurrence of value within the entire sequence, if found; otherwise, –1.</returns>
        public static int IndexOf<TSource>(this IEnumerable<TSource> list, TSource value) where TSource : IEquatable<TSource> {

            return list.IndexOf<TSource>(value, EqualityComparer<TSource>.Default);

        }

        /// <summary>
        /// Returns the index of the first occurrence in a sequence by using a specified IEqualityComparer.
        /// </summary>
        /// <typeparam name="TSource">The type of the elements of source.</typeparam>
        /// <param name="list">A sequence in which to locate a value.</param>
        /// <param name="value">The object to locate in the sequence</param>
        /// <param name="comparer">An equality comparer to compare values.</param>
        /// <returns>The zero-based index of the first occurrence of value within the entire sequence, if found; otherwise, –1.</returns>
        public static int IndexOf<TSource>(this IEnumerable<TSource> list, TSource value, IEqualityComparer<TSource> comparer) {
            int index = 0;
            foreach (var item in list) {
                if (comparer.Equals(item, value)) {
                    return index;
                }
                index++;
            }
            return -1;
        }
      
        /// <summary>
        /// Selects specific number of rows from a datatable
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        public static DataTable SelectRows(this DataTable dataTable, int rowCount)
        {
            try
            {
                DataTable myTable = dataTable.Clone();
                DataRow[] myRows = dataTable.Select();
                for (int i = 0; i < rowCount; i++)
                {

                    if (i < myRows.Length)
                    {
                        myTable.ImportRow(myRows[i]);

                        myTable.AcceptChanges();
                    }
                }

                return myTable;
            }
            catch (Exception)
            {
                return new DataTable();
            }
        }

        /// <summary>
        /// Accepts a date time value, calculates number of days, minutes or seconds and shows 'pretty dates'
        /// like '2 days ago', '1 week ago' or '10 minutes ago'
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public static string GetPrettyDate(this DateTime d)
        {
            // 1.
            // Get time span elapsed since the date.
            TimeSpan s = DateTime.Now.Subtract(d);

            // 2.
            // Get total number of days elapsed.
            int dayDiff = (int)s.TotalDays;

            // 3.
            // Get total number of seconds elapsed.
            int secDiff = (int)s.TotalSeconds;

            // 4.
            // Don't allow out of range values.
            if (dayDiff < 0 || dayDiff >= 31)
            {
                return d.ToString();
            }

            // 5.
            // Handle same-day times.
            if (dayDiff == 0)
            {

                // A.
                // Less than one minute ago.
                if (secDiff < 60)
                {
                    return "just now";
                }

                // B.
                // Less than 2 minutes ago.
                if (secDiff < 120)
                {
                    return "1 minute ago";
                }

                // C.
                // Less than one hour ago.
                if (secDiff < 3600)
                {
                    return string.Format("{0} minutes ago",

                        Math.Floor((double)secDiff / 60));
                }

                // D.
                // Less than 2 hours ago.
                if (secDiff < 7200)
                {
                    return "1 hour ago";
                }

                // E.
                // Less than one day ago.
                if (secDiff < 86400)
                {

                    return string.Format("{0} hours ago",

                        Math.Floor((double)secDiff / 3600));
                }

            }

            // 6.
            // Handle previous days.
            if (dayDiff == 1)
            {
                return "yesterday";
            }

            if (dayDiff < 7)
            {
                return string.Format("{0} days ago",

                    dayDiff);
            }

            if (dayDiff < 31)
            {

                return string.Format("{0} weeks ago",

                    Math.Ceiling((double)dayDiff / 7));

            }

            return null;

        }

        /// <summary>
        /// This mehtod will extend the response mehtod and open the page in a new window
        /// </summary>
        /// <param name="response"></param>
        /// <param name="url"></param>
        /// <param name="target"></param>
        /// <param name="windowFeatures"></param>
        public static void Redirect(this HttpResponse response, string url, string target, string windowFeatures)
        {

            if ((String.IsNullOrEmpty(target) ||

                target.Equals("_self", StringComparison.OrdinalIgnoreCase)) &&

                String.IsNullOrEmpty(windowFeatures))
            {

                response.Redirect(url);

            }
            else
            {
                Page page = (Page)HttpContext.Current.Handler;

                if (page == null)
                {
                    throw new InvalidOperationException(

                        "Cannot redirect to new window outside Page context.");
                }

                url = page.ResolveClientUrl(url);
                string script;
                if (!String.IsNullOrEmpty(windowFeatures))
                {
                    script = @"window.open(""{0}"", ""{1}"", ""{2}"");";
                }
                else
                {
                    script = @"window.open(""{0}"", ""{1}"");";
                }

                script = String.Format(script, url, target, windowFeatures);

                ScriptManager.RegisterStartupScript(page,

                    typeof(Page),

                    "Redirect",

                    script,

                    true);

            }

        }

        /// <summary>
        /// Determines whether the specified collection has any elements in the sequence.
        /// This method also checks for a null collection.
        /// </summary>
        /// <param name="items">The ICollection of items to check.</param>
        public static bool HasElements(this ICollection items)
        {
            return items != null && items.Count > 0;
        }

        /// <summary>
        /// The IsBetween method returns a boolean and determines whether or not a value is between an inclusive upper and lower boundary.
        /// This will only work on types that implement the IComparable interface.
        /// Determines whether a value is between a minimum and maximum value.
        /// </summary>
        /// <typeparam name="T">The type of the value parameter.</typeparam>
        /// <param name="value">The value that needs to be checked.</param>
        /// <param name="low">The inclusive lower boundary.</param>
        /// <param name="high">The inclusive upper boundary.</param>
        public static bool IsBetween<T>(this T value, T low, T high) where T : IComparable<T>
        {
            return value.CompareTo(low) >= 0 && value.CompareTo(high) <= 0;
        }

        /// <summary>
        /// Executes the given action against the given ICollection instance.
        /// </summary>
        /// <typeparam name="T">The type of the ICollection parameter.</typeparam>
        /// <param name="items">The collection the action is performed against.</param>
        /// <param name="action">The action that is performed on each item.</param>
        public static void Each<T>(this ICollection<T> items, Action<T> action)
        {
            foreach (T item in items)
            {
                action(item);
            }
        }

        /// <summary>
        /// Determines whether a parameter is in a given list of parameters.
        /// E.g.. 11.In(1,2,3) will return false.
        /// </summary>
        /// <typeparam name="T">The type of the source parameter.</typeparam>
        /// <param name="source">The item that needs to be checked.</param>
        /// <param name="list">The list that will be checked for the given source.</param>
        //public static bool In<T>(this T source, params T[] list)
        //{
        //    if (null == source) throw new ArgumentNullException("source");
        //    return list.Contains(source);
        //}

        /// <summary>
        /// Fast version of the RemoveAt function. Overwrites the element at the specified index
        /// with the last element in the list, then removes the last element, thus lowering the
        /// inherent O(n) cost to O(1). Intended to be used on *unordered* lists only.
        /// </summary>
        /// <param name="_list">List.</param>
        /// <param name="_index">Index of the element to be removed.</param>
        public static void RemoveAtFast<T>(this IList<T> _list, int _index)
        {
            _list[_index] = _list[_list.Count - 1];
            _list.RemoveAt(_list.Count - 1);
        }

        /// <summary>
        /// Orders a list based on a sortexpression.
        /// Useful in object databinding scenarios where the objectdatasource generates a dynamic sortexpression
        /// (example: "Name desc") that specifies the property of the object sort on.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="sortExpression"></param>
        /// <returns></returns>
        //public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, string sortExpression)
        //{
        //    sortExpression += "";
        //    string[] parts = sortExpression.Split(' ');
        //    bool descending = false;
        //    string property = "";

        //    if (parts.Length > 0 && parts[0] != "")
        //    {
        //        property = parts[0];

        //        if (parts.Length > 1)
        //        {
        //            descending = parts[1].ToLower().Contains("esc");
        //        }

        //        PropertyInfo prop = typeof(T).GetProperty(property);

        //        if (prop == null)
        //        {
        //            throw new Exception("No property '" + property + "' in + " + typeof(T).Name + "'");
        //        }

        //        if (descending)
        //            return list.OrderByDescending(x => prop.GetValue(x, null));
        //        else
        //            return list.OrderBy(x => prop.GetValue(x, null));
        //    }

        //    return list;
        //}

        /// <summary>
        /// Encryptes a string using the supplied key. Encoding is done using RSA encryption.
        /// </summary>
        /// <param name="stringToEncrypt">String that must be encrypted.</param>
        /// <param name="key">Encryptionkey.</param>
        /// <returns>A string representing a byte array separated by a minus sign.</returns>
        /// <exception cref="ArgumentException">Occurs when stringToEncrypt or key is null or empty.</exception>
        public static string Encrypt(this string stringToEncrypt, string key)
        {
            if (string.IsNullOrEmpty(stringToEncrypt))
            {
                throw new ArgumentException("An empty string value cannot be encrypted.");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Cannot encrypt using an empty key. Please supply an encryption key.");
            }

            CspParameters cspp = new CspParameters();
            cspp.KeyContainerName = key;

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
            rsa.PersistKeyInCsp = true;

            byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(stringToEncrypt), true);

            return BitConverter.ToString(bytes);
        }

        /// <summary>
        /// Decryptes a string using the supplied key. Decoding is done using RSA encryption.
        /// </summary>
        /// <param name="stringToDecrypt">String that must be decrypted.</param>
        /// <param name="key">Decryptionkey.</param>
        /// <returns>The decrypted string or null if decryption failed.</returns>
        /// <exception cref="ArgumentException">Occurs when stringToDecrypt or key is null or empty.</exception>
        public static string Decrypt(this string stringToDecrypt, string key)
        {
            string result = null;

            if (string.IsNullOrEmpty(stringToDecrypt))
            {
                throw new ArgumentException("An empty string value cannot be encrypted.");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
            }

            try
            {
                CspParameters cspp = new CspParameters();
                cspp.KeyContainerName = key;

                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
                rsa.PersistKeyInCsp = true;

                string[] decryptArray = stringToDecrypt.Split(new string[] { "-" }, StringSplitOptions.None);
                byte[] decryptByteArray = Array.ConvertAll<string, byte>(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));


                byte[] bytes = rsa.Decrypt(decryptByteArray, true);

                result = System.Text.UTF8Encoding.UTF8.GetString(bytes);

            }
            finally
            {
                // no need for further processing
            }

            return result;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="control"></param>
        /// <param name="datasource"></param>
        /// <param name="textField"></param>
        /// <param name="valueField"></param>
        /// <returns></returns>
        public static bool DataBind(this ListControl control, object datasource, string textField, string valueField)
        {
            return DataBind(control, datasource, textField, null, valueField);
        }

        /// <summary>
        ///Bind to a ListControl (Dropdownlist, listbox, checkboxlist, radiobutton)
        ///in minimal amounts of code. Also returns true false if items
        ///are in the control after binding and sets the selected index to first value.
        /// </summary>
        /// <param name="control"></param>
        /// <param name="datasource"></param>
        /// <param name="textField"></param>
        /// <param name="textFieldFormat"></param>
        /// <param name="valueField"></param>
        /// <returns></returns>
        public static bool DataBind(this ListControl control, object datasource, string textField, string textFieldFormat, string valueField)
        {
            control.DataTextField = textField;
            control.DataValueField = valueField;

            if (!string.IsNullOrEmpty(textFieldFormat))
                control.DataTextFormatString = textFieldFormat;

            control.DataSource = datasource;
            control.DataBind();

            if (control.Items.Count > 0)
            {
                control.SelectedIndex = 0;
                return true;
            }
            else return false;
        }

        /// <summary>
        /// Adds a css class to the webcontrol.
        /// Instead of having to pass one string to the CssClass property,
        /// you can add them one by one with the AddCssClass extension method.
        /// This can come in handy when a webcontrol has a default class (from the ASP.NET markup)
        /// and then needs additional classes based on a condition (like whether or not a user is logged in).
        /// </summary>
        /// <param name="control"></param>
        /// <param name="cssClass"></param>
        public static void AddCssClass(this WebControl control, string cssClass)
        {
            control.CssClass += " " + cssClass;
        }

        /// <summary>
        /// Generic recursive FindControl.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="startingControl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static T FindControl<T>(this Control startingControl, string id) where T : Control
        {
            T foundControl = default(T);

            int controlCount = startingControl.Controls.Count;

            foreach (Control c in startingControl.Controls)
            {
                if (c is T && string.Equals(id, c.ID,
                    StringComparison.InvariantCultureIgnoreCase))
                {
                    foundControl = c as T;
                    break;
                }
                else
                {
                    foundControl = FindControl<T>(c, id);
                    if (foundControl != null)
                    {
                        break;
                    }
                }
            }
            return foundControl;
        }

        /// <summary>
        /// A simple date range
        /// </summary>
        /// <param name="self"></param>
        /// <param name="toDate"></param>
        /// <returns></returns>
        public static IEnumerable<DateTime> GetDateRangeTo(this DateTime self, DateTime toDate)
        {
            var range = Enumerable.Range(0, new TimeSpan(toDate.Ticks - self.Ticks).Days);

            return from p in range
                   select self.Date.AddDays(p);
        }

        /// <summary>
        /// Removes all selected rows from datagridview and returns the response on success
        /// </summary>
        /// <param name="dgv"></param>
        /// <returns></returns>
        //public static bool RemoveSelectedRows(this GridView dgv)
        //{
        //    try
        //    {
        //        if (dgv.Rows.Count > 0)
        //        {
        //            if (dgv.SelectedRow.ToInteger() == dgv.Rows.Count)
        //            {
        //                dgv.DataSource = null;
        //            }

        //            foreach (GridView row in dgv.SelectedRow)
        //            {
        //                dgv.RemoveSelectedRows(row);
        //            }
        //        }

        //        return true;
        //    }
        //    catch (Exception exc)
        //    {
        //        return false;
        //    }
        //}

        /// <summary>
        /// Converts an array of any type to List<T>
        /// passing a mapping delegate Func<object, T>
        /// that returns type T. If T is null, it will not be added to the collection.
        /// If the array is null, then a new instance of List<T>() is returned.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="mapFunction"></param>
        /// <returns></returns>
        public static List<T> ToList<T>(this Array items, Func<object, T> mapFunction)
        {
            if (items == null || mapFunction == null)
                return new List<T>();

            List<T> coll = new List<T>();
            for (int i = 0; i < items.Length; i++)
            {
                T val = mapFunction(items.GetValue(i));
                if (val != null)
                    coll.Add(val);
            }
            return coll;
        }
      
        /// delegate with lambda expression
        /// datatble object, column name , return value as string       
        /// x=DataTable, y=string typr column name
        public static Func<DataTable, string, string> DataTableColumnValue = (x, y) =>
        {
            string result = string.Empty;

            if (x.Columns.Contains(y))
            {
                result = Convert.ToString(x.Rows[0][y]);
            }
            return result;
        };
    }
---------------------------------------------------------------------------------------------------------
 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDropDownList();               
            }
        }

        private void BindDropDownList()
        {
            Dictionary<int, string> data = new Dictionary<int, string>();
            data.Add(0, "Apple");
            data.Add(1, "Orange");
            data.Add(2, "Pair");
            ddlFruits.DataBind(data, "value", "key");
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (txtName.Text.IsStringNullOrEmpty())
            {
                Int32 myInt = Convert.ToInt16(txtQuantity.Text);
                if (myInt.IsBetween(0, 5))
                {
                    string Greeting = "Hello {0}, my name is {1}, and I own you.";
                    string Value = string.Format(Greeting, txtName.Text, "Sourabh");
                }
            }
        }

No comments:

Post a Comment