November 2012 - Development Simply Put

A blog simplifies main concepts in IT development and provides tips, hints, advices and some re-usable code. "If you can't explain it simply, you don't understand it well enough" -Albert Einstein

  • Development Simply Put

    If you can't explain it simply, you don't understand it well enough.

    Read More
  • Integrant

    Based in the U.S. with offshore development centers in Jordan and Egypt, Integrant builds quality custom software since 1992. Our staff becomes an extension of your team to eliminate the risks of software development outsourcing and our processes...

    Read More
  • ITWorx

    ITWorx is a global software professional services organization. Headquartered in Egypt, the company offers Portals, Business Intelligence, Enterprise Application Integration and Application Development Outsourcing services to Global 2000 companies.

    Read More
  • Information Technology Institute

    ITI is a leading national institute established in 1993 by the Information and Decision Support Centre.

    Read More

2012-11-07

How To Manage Your Resources


How To Manage Your Resources

As you are going on with your career you stumble on many resources. These resources are very important and they are your assets. So, you should think about how to save and keep track of these resources in order to be able to reuse them when needed.

What resources?
  1. People you know (colleagues, team members, family, friends, neighbors, bloggers, .......)
  2. Internet resources (emails, websites, blogs, communities, forums, ......)
  3. Personal work (trials, proof of concepts, projects, .......)

How to save/track/organize them?
It depends on the type of the resource. Some ways may be somehow common and others may not. Always keep your mind open for new ideas and from time to time try to invest some of your precious time to think of new ideas about organizing your resources. Believe me, do it and you will feel the difference.


What to do with "People I know"?
  1. Keep a good and kind relationship with them
  2. Try to keep in touch
  3. Know each one's strength points
  4. Be sensitive and aware of the context (what to say and when, .........)
  5. Show some -but not too much offending- interest in their life events
  6. Offer help when "needed" not "directly asked"
  7. Say thanks when you can
  8. Invest some time in following their news on Facebook, Twitter, LinkedIn, ......
  9. Integrate your outlook or email client with other services like Facebook, Twitter, LinkedIn, ......
  10. Know who knows/did what
  11. Use a smartphone, it really offers some good magic
  12. Always update your mobile contacts (think of synchronizing them with your Google account, if you don't have one, then for sure have one!!!)
  13. Synchronize your calendar with your contacts' birthdays and occasions
  14. Integrate your internet browser (please try to use one not a bunch) with an email notifier to keep you notified about any incoming mails
  15. It is not a good thing to give someone an email you don't intend to check. It is like allocating a junk box especially for him, then you should probably tell him to know how special he is to you. What a kind gesture of you!!!
  16. Try to find the best in everyone and try to do it better
  17. Don't repeat their mistakes. If someone treated you bad, don't do it with others
  18. Avoid prejudging when you can
  19. Try to find common aspects between you and each one of them
  20. Don't underestimate them
  21. Try to be a model for others to follow because they love to
  22. Be a human with all what the word means not just a being


What to do with my "Internet Resources"?
  1. Try to use only one internet browser to be easy to manage
  2. Bookmark your favorite pages
  3. Add meaningful tags to your bookmarks to be able to search among them later
  4. Synchronize your bookmarks online so that you will not be afraid of losing them and also you can access them anywhere
  5. Synchronize your accounts and subscriptions details (like passwords) online so that you can keep them safe and access them anywhere
  6. If you have any important technical content you wish to keep, try to send it to yourself into a  personal email and specify a folder on your email provider for these mails
  7. Use StumbleUpon service to provide you with random pages on your favorite categories. You can have more than one profile so that each profile has its own categories. It is a very good service and you will be shocked by what sites it gets you


What to do with my "Personal Work"?
  1. Find an online file hosting service to host your important files, documents, source code, ...... so that you can access them anywhere
  2. Find an online source control service to keep your important files, documents, source code, ...... so that you can access them anywhere


That's all what I have in mind right now but please try to put your own system to keep your resources safe and organized.


2012-11-06

How To Restore/Backup SQL Database From/To Remote Server

Did you ever need to restore a SQL database from a backup (.bak) file which is located on another remote server? Or let's be more general, did you ever need to access a file from SQL Server Management Studio File Explorer and this file was located on a remote server?

Some may think that this could be achieved by creating a mapped network drive, on the machine having SQL server installed, which is pointing to the shared path in the other remote server...... then this mapped network drive would be accessible from SQL Server Management Studio File Explorer.

Alas, even after creating the mapped network drive this drive will not be accessible from SQL Server Management Studio File Explorer, actually it will not appear among the available drives.

So, how to do it? If you are interested to know, you can read the rest of the post which will explain in details and screenshots how to do it.


Problem???!!

How To Restore/Backup SQL Database From/To Remote Server
  1. We have a "DB.bak" file which is a database backup file
  2. It is located on a server named "ServerName" (this server may be a web server, file server or any type of servers with file system, it doesn't need to be a SQL server at all so don't get confused)
  3. We have another SQL server on which we want to restore the "DB.bak" file
  4. When we proceed with the regular DB restore operation, we can't browse to the "DB.bak" file from SQL Server Management Studio File Explorer and we can't enforce it by anyway
  5. We need to make the "DB.bak" file accessible from SQL Server Management Studio File Explorer


Configuring Security & Sharing on the Remote Server (ServerName)

On the remote server called "ServerName" which has the "DB.bak" file on its file system, browse to the folder including the file, right-click, properties and then follow the screenshots below.






Creating Mapped Network Drive on the SQL Server

Log on the SQL server machine to create a mapped network drive which is mapped to the shared path you already created in the previous step. To do this, follow the screenshot below.



Registering the Mapped Network Path on SQL Server Management Studio

You, you need to register the mapped network path on the SQL Server Management Studio in order to be able to access the mapped drive from SQL Server Management Studio File Explorer. To do so, open SQL Server Management Studio and execute the query below.
EXEC sp_configure 'show advanced options', 1  
GO  
RECONFIGURE  
GO  
EXEC sp_configure 'xp_cmdshell', 1  
GO  
RECONFIGURE  
GO   

EXEC XP_CMDSHELL 'net use N: /delete'  
EXEC XP_CMDSHELL 'net use N: \\ServerName\DB-Backup-ShareName'  
EXEC XP_CMDSHELL 'Dir N:'


Result???

Now, you can find the mapped network drive (N:\ in our case) among the other drives in the SQL Server Management Studio File Explorer. Now you can restore/backup from/to the shared path as you wish.


Wish this may help you some day, good luck :)



2012-11-04

[ExtensionMethods] Generics (T)

These are extension methods for "Generics (T)". Some are written by me and the rest are collected from other sources. Hope you find them useful :)


using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Reflection;
 
namespace DevelopmentSimplyPut.ExtensionMethods.GenericsExtensionMethods
{
 public static class GenericsExtensionMethods
 {
  /// <summary>
  /// Returns a bool indicating whether the object is nullable or not
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="source"></param>
  /// <returns></returns>
  public static bool ext_IsNullable<T>(this T source)
  {
   bool result = false;
 
   if (source == null)
   {
    result = true;
   }
   else
   {
    Type type = typeof(T);
 
    if (!type.IsValueType)
    {
     result = true;
    }
    else if (Nullable.GetUnderlyingType(type) != null)
    {
     result = true;
    }
   }
 
   return result;
  }
  /// <summary>
  /// Returns a bool indicating whether the object is value type or not
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="source"></param>
  /// <returns></returns>
  public static bool ext_IsItValueType<T>(this T source)
  {
   Type type = typeof(T);
   return (type.IsValueType);
  }
  /// <summary>
  /// Converts from T1 to T2 if doable or just return a default value
  /// </summary>
  /// <typeparam name="T1">Type of Object to convert</typeparam>
  /// <typeparam name="T2">Type of Object to convert to</typeparam>
  /// <param name="source">Object to convert</param>
  /// <param name="CustomConvertOrDefault">Predicate to be used for conversion</param>
  /// <returns>Converted object of type T2 or a default value</returns>
  public static T2 ext_ConvertOrDefault<T1, T2>(this T1 source, Func<T1, T2> CustomConvertOrDefault)
  {
   return CustomConvertOrDefault(source);
  }
  /// <summary>
  /// Converts from T1 to T2 if doable or just return a default value
  /// </summary>
  /// <typeparam name="T1">Type of Object to convert</typeparam>
  /// <typeparam name="T2">Type of Object to convert to</typeparam>
  /// <param name="source">Object to convert</param>
  /// <param name="CustomConvertOrDefault">Predicate to be used for conversion</param>
  /// <param name="defaultValue">Default value to be returned if conversion fails</param>
  /// <returns>Converted object of type T2 or a default value</returns>
  public static T2 ext_ConvertOrDefault<T1, T2>(this T1 source, Func<T1, T2, T2> CustomConvertOrDefault, T2 defaultValue)
  {
   return CustomConvertOrDefault(source, defaultValue);
  }
  /// <summary>
  /// Serialises an object of type T in to an xml string
  /// </summary>
  /// <typeparam name="T">Any class type</typeparam>
  /// <param name="objectToSerialise">Object to serialise</param>
  /// <returns>A string that represents Xml, empty oterwise</returns>
  public static string ext_XmlSerialize<T>(this T objectToSerialise) where T : class
  {
   var serialiser = new XmlSerializer(typeof(T));
   string xml;
   using (var memStream = new MemoryStream())
   {
    using (var xmlWriter = new XmlTextWriter(memStream, Encoding.UTF8))
    {
     serialiser.Serialize(xmlWriter, objectToSerialise);
     xml = Encoding.UTF8.GetString(memStream.GetBuffer());
    }
   }
 
   // ascii 60 = '<' and ascii 62 = '>'
   xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)));
   xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1));
   return xml;
  }
  /// <summary>
  /// Checks if a value falls in between two given values
  /// </summary>
  /// <typeparam name="T">Type</typeparam>
  /// <param name="value"></param>
  /// <param name="low">Lower bound value</param>
  /// <param name="high">Higher bound value</param>
  /// <returns></returns>
  public static bool ext_IsBetween<T>(this T value, T low, T high) where T : IComparable<T>
  {
   return value.CompareTo(low) >= 0 && value.CompareTo(high) <= 0;
  }
 }
}

[ExtensionMethods] System.IConvertible

These are extension methods for "System.IConvertible" class. Some are written by me and the rest are collected from other sources. Hope you find them useful :)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace DevelopmentSimplyPut.ExtensionMethods.IConvertibleEM
{
 public static class IConvertibleExtensionMethods
 {
  public static T ext_ConvertTo<T>(this IConvertible value)
  {
   object holder = Convert.ChangeType(value, typeof(T));
   T result = default(T);
 
   if (null != holder)
   {
    result = (T)holder;
   }
 
   return result;
  }
 }
}


[ExtensionMethods] System.Linq.IOrderedQueryable

These are extension methods for "System.Linq.IOrderedQueryable" class. Some are written by me and the rest are collected from other sources. Hope you find them useful :)


using System.Text;
 
namespace DevelopmentSimplyPut.ExtensionMethods.IOrderedQueryableEM
{
 /// <summary>
 /// LinQ  Extentensions
 /// </summary>
 public static class LinqExtensionMethods
 {
  /// <summary>
  /// Converts the Linq data to a commaseperated string including header.
  /// </summary>
  /// <param name="data">The data.</param>
  /// <returns></returns>
  public static string ext_ToCSVString(this System.Linq.IOrderedQueryable data)
  {
   return ext_ToCSVString(data, "; ");
  }
  /// <summary>
  /// Converts the Linq data to a commaseperated string including header.
  /// </summary>
  /// <param name="data">The data.</param>
  /// <param name="delimiter">The delimiter.</param>
  /// <returns></returns>
  public static string ext_ToCSVString(this System.Linq.IOrderedQueryable data, string delimiter)
  {
   return ext_ToCSVString(data, "; ", null);
  }
  /// <summary>
  /// Converts the Linq data to a commaseperated string including header.
  /// </summary>
  /// <param name="data">The data.</param>
  /// <param name="delimiter">The delimiter.</param>
  /// <param name="nullvalue">The nullvalue.</param>
  /// <returns></returns>
  public static string ext_ToCSVString(this System.Linq.IOrderedQueryable data, string delimiter, string nullvalue)
  {
   StringBuilder csvdata = new StringBuilder();
   string replaceFrom = delimiter.Trim();
   string replaceDelimiter = "?";
   System.Reflection.PropertyInfo[] headers = data.ElementType.GetProperties();
   switch (replaceFrom)
   {
    case ";":
     replaceDelimiter = ":";
     break;
    case ",":
     replaceDelimiter = "¸";
     break;
    case "\t":
     replaceDelimiter = "    ";
     break;
    default:
     break;
   }
   if (headers.Length > 0)
   {
    foreach (var head in headers)
    {
     csvdata.Append(head.Name.Replace("_", " ") + delimiter);
    }
    csvdata.Append("\n");
   }
   foreach (var row in data)
   {
    var fields = row.GetType().GetProperties();
    for (int i = 0; i < fields.Length; i++)
    {
     object value = null;
     try
     {
      value = fields[i].GetValue(row, null);
     }
     catch { }
     if (value != null)
     {
      csvdata.Append(value.ToString().Replace("\r", "\f").Replace("\n", " \f").Replace("_", " ").Replace(replaceFrom, replaceDelimiter) + delimiter);
     }
     else
     {
      csvdata.Append(nullvalue);
      csvdata.Append(delimiter);
     }
    }
    csvdata.Append("\n");
   }
   return csvdata.ToString();
  }   
 }
}


[ExtensionMethods] System.DateTime

These are extension methods for "System.DateTime" class. Some are written by me and the rest are collected from other sources. Hope you find them useful :)


using System;
 
namespace DevelopmentSimplyPut.ExtensionMethods.DateTimeEM
{
 /// <summary>
 /// DateTime Extensions
 /// </summary>
 public static class DateTimeExtensionMethods
 {
  /// <summary>
  /// Elapseds the time.
  /// </summary>
  /// <param name="datetime">The datetime.</param>
  /// <returns>TimeSpan</returns>
  public static TimeSpan ext_Elapsed(this DateTime datetime)
  {
   return DateTime.Now - datetime;
  }
  /// <summary>
  /// Weeks the of year.
  /// </summary>
  /// <param name="datetime">The datetime.</param>
  /// <param name="weekrule">The weekrule.</param>
  /// <param name="firstDayOfWeek">The first day of week.</param>
  /// <returns></returns>
  public static int ext_WeekOfYear(this DateTime datetime, System.Globalization.CalendarWeekRule weekrule, DayOfWeek firstDayOfWeek)
  {
   System.Globalization.CultureInfo ciCurr = System.Globalization.CultureInfo.CurrentCulture;
   return ciCurr.Calendar.GetWeekOfYear(datetime, weekrule, firstDayOfWeek);
  }
  /// <summary>
  /// Weeks the of year.
  /// </summary>
  /// <param name="datetime">The datetime.</param>
  /// <param name="firstDayOfWeek">The first day of week.</param>
  /// <returns></returns>
  public static int ext_WeekOfYear(this DateTime datetime, DayOfWeek firstDayOfWeek)
  {
   System.Globalization.DateTimeFormatInfo dateinf = new System.Globalization.DateTimeFormatInfo();
   System.Globalization.CalendarWeekRule weekrule = dateinf.CalendarWeekRule;
   return ext_WeekOfYear(datetime, weekrule, firstDayOfWeek);
  }
  /// <summary>
  /// Weeks the of year.
  /// </summary>
  /// <param name="datetime">The datetime.</param>
  /// <param name="weekrule">The weekrule.</param>
  /// <returns></returns>
  public static int ext_WeekOfYear(this DateTime datetime, System.Globalization.CalendarWeekRule weekrule)
  {
   System.Globalization.DateTimeFormatInfo dateinf = new System.Globalization.DateTimeFormatInfo();
   DayOfWeek firstDayOfWeek = dateinf.FirstDayOfWeek;
   return ext_WeekOfYear(datetime, weekrule, firstDayOfWeek);
  }
  /// <summary>
  /// Weeks the of year.
  /// </summary>
  /// <param name="datetime">The datetime.</param>
  /// <param name="weekrule">The weekrule.</param>
  /// <returns></returns>
  public static int ext_WeekOfYear(this DateTime datetime)
  {
   System.Globalization.DateTimeFormatInfo dateinf = new System.Globalization.DateTimeFormatInfo();
   System.Globalization.CalendarWeekRule weekrule = dateinf.CalendarWeekRule;
   DayOfWeek firstDayOfWeek = dateinf.FirstDayOfWeek;
   return ext_WeekOfYear(datetime, weekrule, firstDayOfWeek);
  }
  /// <summary>
  /// Gets the date time for day of week.
  /// </summary>
  /// <param name="datetime">The datetime.</param>
  /// <param name="day">The day.</param>
  /// <param name="firstDayOfWeek">The first day of week.</param>
  /// <returns></returns>
  public static DateTime ext_GetDateTimeForDayOfWeek(this DateTime datetime, DayOfWeek day, DayOfWeek firstDayOfWeek)
  {
   int current = DaysFromFirstDayOfWeek(datetime.DayOfWeek, firstDayOfWeek);
   int resultday = DaysFromFirstDayOfWeek(day, firstDayOfWeek);
   return datetime.AddDays(resultday - current);
  }
  /// <summary>
  /// Gets the date time for day of week.
  /// </summary>
  /// <param name="datetime">The datetime.</param>
  /// <param name="day">The day</param>
  /// <returns></returns>
  public static DateTime ext_GetDateTimeForDayOfWeek(this DateTime datetime, DayOfWeek day)
  {
   System.Globalization.DateTimeFormatInfo dateinf = new System.Globalization.DateTimeFormatInfo();
   DayOfWeek firstDayOfWeek = dateinf.FirstDayOfWeek;
   return ext_GetDateTimeForDayOfWeek(datetime, day, firstDayOfWeek);
  }
  /// <summary>
  /// Firsts the date time of week.
  /// </summary>
  /// <param name="datetime">The datetime.</param>
  /// <returns></returns>
  public static DateTime ext_FirstDateTimeOfWeek(this DateTime datetime)
  {
   System.Globalization.DateTimeFormatInfo dateinf = new System.Globalization.DateTimeFormatInfo();
   DayOfWeek firstDayOfWeek = dateinf.FirstDayOfWeek;
   return ext_FirstDateTimeOfWeek(datetime, firstDayOfWeek);
  }
  /// <summary>
  /// Firsts the date time of week.
  /// </summary>
  /// <param name="datetime">The datetime.</param>
  /// <param name="firstDayOfWeek">The first day of week.</param>
  /// <returns></returns>
  public static DateTime ext_FirstDateTimeOfWeek(this DateTime datetime, DayOfWeek firstDayOfWeek)
  {
   return datetime.AddDays(-DaysFromFirstDayOfWeek(datetime.DayOfWeek, firstDayOfWeek));
  }
  /// <summary>
  /// Days from first day of week.
  /// </summary>
  /// <param name="current">The current.</param>
  /// <param name="firstDayOfWeek">The first day of week.</param>
  /// <returns></returns>
  private static int DaysFromFirstDayOfWeek(DayOfWeek current, DayOfWeek firstDayOfWeek)
  {
   //Sunday = 0,Monday = 1,...,Saturday = 6
   int daysbetween = current - firstDayOfWeek;
   if (daysbetween < 0) daysbetween = 7 + daysbetween;
   return daysbetween;
  }
  /// <summary>
  /// Gets the string representation of a date if available
  /// </summary>
  /// <param name="datetime">The date</param>
  /// <param name="defaultvalue">The default value</param>
  /// <returns></returns>
  public static string ext_GetValueOrDefaultToString(this DateTime? datetime, string defaultvalue)
  {
   if (datetime == null) return defaultvalue;
   return datetime.Value.ToString();
  }
  /// <summary>
  /// Gets the string representation of a date if available
  /// </summary>
  /// <param name="datetime">The date</param>
  /// <param name="format">The format of the string representation of the date</param>
  /// <param name="defaultvalue">The default value</param>
  /// <returns></returns>
  public static string ext_GetValueOrDefaultToString(this DateTime? datetime, string format, string defaultvalue)
  {
   if (datetime == null) return defaultvalue;
   return datetime.Value.ToString(format);
  }
 }
}


2012-11-03

[ExtensionMethods] System.Web.UI.WebControls.WebControl

These are extension methods for "System.Web.UI.WebControls.WebControl" class. Some are written by me and the rest are collected from other sources. Hope you find them useful :)


using System;
using System.Linq;
using System.Web.UI.WebControls;
using System.Collections.Generic;
 
namespace DevelopmentSimplyPut.ExtensionMethods.WebControlEM
{
 public static class WebControlExtensionMethods
 {
  /// <summary>
  /// Adds a CSS class to a WebControl
  /// </summary>
  /// <param name="control">The WebControl</param>
  /// <param name="cssClass">CSS class name</param>
  public static void ext_AddCssClass(this WebControl control, string cssClass)
  {
   if (null != control && !string.IsNullOrEmpty(cssClass) && !string.IsNullOrWhiteSpace(cssClass))
   {
    if (string.IsNullOrEmpty(control.CssClass) || string.IsNullOrWhiteSpace(control.CssClass))
    {
     control.CssClass = cssClass;
    }
    else
    {
     bool found = false;
     {
      found = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
        .Any<string>(classEntry => classEntry.Trim().ToUpperInvariant().Equals(cssClass.Trim().ToUpperInvariant(), StringComparison.OrdinalIgnoreCase));
     }
 
     if (!found)
     {
      control.CssClass += " " + cssClass;
      control.CssClass.Trim();
     }
    }
   }
  }
  /// <summary>
  /// Removes a CSS class from a WebControl
  /// </summary>
  /// <param name="control">The WebControl</param>
  /// <param name="cssClass">CSS class name</param>
  public static void ext_RemoveCssClass(this WebControl control, string cssClass)
  {
   if (null != control && !string.IsNullOrEmpty(cssClass) && !string.IsNullOrWhiteSpace(cssClass) && !string.IsNullOrEmpty(control.CssClass) && !string.IsNullOrWhiteSpace(control.CssClass))
   {
    if (control.CssClass.Trim().ToUpperInvariant().Equals(cssClass.Trim().ToUpperInvariant()))
    {
     control.CssClass = string.Empty;
    }
    else
    {
     var classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
          .SkipWhile<string>(classEntry => classEntry.Trim().ToUpperInvariant().Equals(cssClass.Trim().ToUpperInvariant(), StringComparison.OrdinalIgnoreCase))
          .ToArray<string>();
 
     if (null != classes && classes.Length > 0)
     {
      control.CssClass = String.Join(" ", classes);
      control.CssClass.Trim();
     }
    }
   }
  }
  /// <summary>
  /// Gets an IEnumerable of all child WebControls
  /// </summary>
  /// <param name="source">WebControl</param>
  /// <returns></returns>
  public static IEnumerable<WebControl> ext_GetChildControlsRecursively(this WebControl source)
  {
   return source.ext_GetChildControlsRecursively(null);
  }
  /// <summary>
  /// Gets an IEnumerable of all child WebControls which satisfy a certain condition
  /// </summary>
  /// <param name="source">WebControl</param>
  /// <param name="selector">Selector method which decides if a certain WebControl should be selected</param>
  /// <returns></returns>
  public static IEnumerable<WebControl> ext_GetChildControlsRecursively(this WebControl source, Func<WebControl,bool> selector)
  {
   if (null != source)
   {
    if ((null == selector) || (null != selector && selector(source)))
    {
     yield return source;
    }
 
    if (!source.HasControls())
    {
     yield break;
    }
 
    foreach (WebControl ctrl in source.Controls)
    {
     foreach (WebControl ctrl1 in ctrl.ext_GetChildControlsRecursively())
     {
      if ((null == selector) || (null != selector && selector(ctrl1)))
      {
       yield return ctrl1;
      }
     }
    }
   }
   else
   {
    yield break;
   }
  }
 }
}


[ExtensionMethods] System.String

These are extension methods for "System.String" class. Some are written by me and the rest are collected from other sources. Hope you find them useful :)


using System;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
 
namespace DevelopmentSimplyPut.ExtensionMethods.StringEM
{
 public static class StringExtensionMethods
 {
  /// <summary>
  /// Repeats a string for a given number of times
  /// </summary>
  /// <param name="source">String</param>
  /// <param name="numberOfTimes">Number of times</param>
  /// <returns></returns>
  public static string ext_RepeatNoOfTimes(this string source, int numberOfTimes)
  {
   string result = string.Empty;
   for (int i = 0; i < numberOfTimes; i++)
   {
    result += source;
   }
   return result;
  }
  /// <summary>
  /// Formats numbers inside a string into a given number of digits with extra preceeding zeros
  /// </summary>
  /// <param name="source">String</param>
  /// <param name="numOfDigits">Number of digits</param>
  /// <returns></returns>
  public static string ext_PutNumbersIntoNoOfDigits(this string source, int numOfDigits)
  {
   string result = source;
   result = Regex.Replace(result, @"\d+", new MatchEvaluator(delegate(Match match)
   {
    if (match.Length < numOfDigits)
    {
     string zero = "0";
     result = zero.ext_RepeatNoOfTimes(numOfDigits - match.Length) + match.Value;
     return result;
    }
    else
    {
     result = match.Value;
     return result;
    }
   }));
 
   return result;
  }
  /// <summary>
  /// Gets the {n} first characters of a string
  /// </summary>
  /// <param name="source">String</param>
  /// <param name="NumOfChars">Number of characters</param>
  /// <returns></returns>
  public static string ext_First(this string source, int NumOfChars)
  {
   if (string.IsNullOrEmpty(source) || source.Length <= NumOfChars)
   {
    return source;
   }
 
   return source.Substring(0, NumOfChars);
  }
  /// <summary>
  /// Gets the {n} last characters of a string
  /// </summary>
  /// <param name="source">String</param>
  /// <param name="NumOfChars">Number of characters</param>
  /// <returns></returns>
  public static string ext_Last(this string source, int NumOfChars)
  {
   if (string.IsNullOrEmpty(source) || source.Length <= NumOfChars)
   {
    return source;
   }
 
   return source.Substring(source.Length - NumOfChars, NumOfChars);
  }
  /// <summary>
  /// Splits a string into two parts, the first one is the string part before the last existance of a certain character,
  /// the second one is the string part after the last existance of the same character
  /// </summary>
  /// <param name="source"></param>
  /// <param name="splitAtChar"></param>
  /// <returns></returns>
  public static string[] ext_SplitAtLastCharExistance(this string source, char splitAtChar)
  {
   string[] result = { string.Empty, string.Empty };
   if (string.IsNullOrEmpty(source))
   {
    //string is empty
    return result;
   }
 
   if (!(source.Contains(splitAtChar)))
   {
    //character doesn't exist in the string
    result[0] = source;
    return result;
   }
 
   if (source.Length == 1)
   {
    //the string is only the character itself
    return result;
   }
 
   int temp = source.LastIndexOf(splitAtChar);
 
   if (temp == 0)
   {
    //the character is at the start
    result[0] = string.Empty;
    result[1] = source.Substring(temp + 1, source.Length - temp - 1);
   }
   else if (temp == source.Length - 1)
   {
    //the character is at the end
    result[0] = source.Substring(0, temp);
    result[1] = string.Empty;
   }
   else
   {
    //the character is in the middle
    result[0] = source.Substring(0, temp);
    result[1] = source.Substring(temp + 1, source.Length - temp - 1);
   }
 
   return result;
  }
  /// <summary>
  /// Gets the preceding part of a string except the last given number of characters
  /// </summary>
  /// <param name="source">String</param>
  /// <param name="NumOfChars">Number of characters</param>
  /// <returns></returns>
  public static string ext_ExceptLastNoOfChars(this string source, int NumOfChars)
  {
   if (string.IsNullOrEmpty(source) || source.Length <= NumOfChars)
   {
    return string.Empty;
   }
 
   return source.Substring(0, source.Length - NumOfChars);
  }
  /// <summary>
  /// Gets the succeeding part of a string except the first given number of characters
  /// </summary>
  /// <param name="source"></param>
  /// <param name="NumOfChars"></param>
  /// <returns></returns>
  public static string ext_ExceptFirstNoOfChars(this string source, int NumOfChars)
  {
   if (string.IsNullOrEmpty(source) || source.Length <= NumOfChars)
   {
    return string.Empty;
   }
 
   return source.Substring(NumOfChars, source.Length - NumOfChars);
  }
  /// <summary>
  /// Formats a string with one literal placeholder.
  /// </summary>
  /// <param name="text">The extension text</param>
  /// <param name="arg0">Argument 0</param>
  /// <returns>The formatted string</returns>
  public static string ext_FormatWith(this string text, object arg0)
  {
   return string.Format(text, arg0);
  }
  /// <summary>
  /// Formats a string with two literal placeholders.
  /// </summary>
  /// <param name="text">The extension text</param>
  /// <param name="arg0">Argument 0</param>
  /// <param name="arg1">Argument 1</param>
  /// <returns>The formatted string</returns>
  public static string ext_FormatWith(this string text, object arg0, object arg1)
  {
   return string.Format(text, arg0, arg1);
  }
  /// <summary>
  /// Formats a string with tree literal placeholders.
  /// </summary>
  /// <param name="text">The extension text</param>
  /// <param name="arg0">Argument 0</param>
  /// <param name="arg1">Argument 1</param>
  /// <param name="arg2">Argument 2</param>
  /// <returns>The formatted string</returns>
  public static string ext_FormatWith(this string text, object arg0, object arg1, object arg2)
  {
   return string.Format(text, arg0, arg1, arg2);
  }
  /// <summary>
  /// Formats a string with a list of literal placeholders.
  /// </summary>
  /// <param name="text">The extension text</param>
  /// <param name="args">The argument list</param>
  /// <returns>The formatted string</returns>
  public static string ext_FormatWith(this string text, params object[] args)
  {
   return string.Format(text, args);
  }
  /// <summary>
  /// Formats a string with a list of literal placeholders.
  /// </summary>
  /// <param name="text">The extension text</param>
  /// <param name="provider">The format provider</param>
  /// <param name="args">The argument list</param>
  /// <returns>The formatted string</returns>
  public static string ext_FormatWith(this string text, IFormatProvider provider, params object[] args)
  {
   return string.Format(provider, text, args);
  }
  /// <summary>
  /// Deserialises an xml string in to an object of Type T
  /// </summary>
  /// <typeparam name="T">Any class type</typeparam>
  /// <param name="xml">Xml as string to deserialise from</param>
  /// <returns>A new object of type T is successful, null if failed</returns>
  public static T ext_XmlDeserialize<T>(this string xml) where T : class
  {
   var serialiser = new XmlSerializer(typeof(T));
   T newObject;
 
   using (var stringReader = new StringReader(xml))
   {
    using (var xmlReader = new XmlTextReader(stringReader))
    {
     try
     {
      newObject = serialiser.Deserialize(xmlReader) as T;
     }
     catch (InvalidOperationException) // String passed is not Xml, return null
     {
      return null;
     }
 
    }
   }
 
   return newObject;
  }
  /// <summary>
  /// Parses a string into an Enum
  /// </summary>
  /// <typeparam name="T">The type of the Enum</typeparam>
  /// <param name="value">String value to parse</param>
  /// <returns>The Enum corresponding to the stringExtensions</returns>
  public static T ext_ToEnum<T>(this string value)
  {
   return ext_ToEnum<T>(value, false);
  }
  /// <summary>
  /// Parses a string into an Enum
  /// </summary>
  /// <typeparam name="T">The type of the Enum</typeparam>
  /// <param name="value">String value to parse</param>
  /// <param name="ignorecase">Ignore the case of the string being parsed</param>
  /// <returns>The Enum corresponding to the stringExtensions</returns>
  public static T ext_ToEnum<T>(this string value, bool ignorecase)
  {
   if (value == null)
    throw new ArgumentNullException("Value");
 
   value = value.Trim();
 
   if (value.Length == 0)
    throw new ArgumentNullException("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);
  }
  /// <summary>
  /// Toes the integer.
  /// </summary>
  /// <param name="value">The value.</param>
  /// <param name="defaultvalue">The defaultvalue.</param>
  /// <returns></returns>
  public static int ext_ToInteger(this string value, int defaultvalue)
  {
   return (int)ext_ToDouble(value, defaultvalue);
  }
  /// <summary>
  /// Toes the integer.
  /// </summary>
  /// <param name="value">The value.</param>
  /// <returns></returns>
  public static int ext_ToInteger(this string value)
  {
   return ext_ToInteger(value, 0);
  }
  /// <summary>
  /// Toes the double.
  /// </summary>
  /// <param name="value">The value.</param>
  /// <param name="defaultvalue">The defaultvalue.</param>
  /// <returns></returns>
  public static double ext_ToDouble(this string value, double defaultvalue)
  {
   double result;
   if (double.TryParse(value, out result))
   {
    return result;
   }
   else return defaultvalue;
  }
  /// <summary>
  /// Toes the double.
  /// </summary>
  /// <param name="value">The value.</param>
  /// <returns></returns>
  public static double ext_ToDouble(this string value)
  {
   return ext_ToDouble(value, 0);
  }
  /// <summary>
  /// Toes the date time.
  /// </summary>
  /// <param name="value">The value.</param>
  /// <param name="defaultvalue">The defaultvalue.</param>
  /// <returns></returns>
  public static DateTime? ext_ToDateTime(this string value, DateTime? defaultvalue)
  {
   DateTime result;
   if (DateTime.TryParse(value, out result))
   {
    return result;
   }
   else return defaultvalue;
  }
  /// <summary>
  /// Toes the date time.
  /// </summary>
  /// <param name="value">The value.</param>
  /// <returns></returns>
  public static DateTime? ext_ToDateTime(this string value)
  {
   return ext_ToDateTime(value, null);
  }
  /// <summary>
  /// Converts a string value to bool value, supports "T" and "F" conversions.
  /// </summary>
  /// <param name="value">The string value.</param>
  /// <returns>A bool based on the string value</returns>
  public static bool? ext_ToBoolean(this string value)
  {
   if (string.Compare("T", value, true) == 0)
   {
    return true;
   }
   if (string.Compare("F", value, true) == 0)
   {
    return false;
   }
   bool result;
   if (bool.TryParse(value, out result))
   {
    return result;
   }
   else return null;
  }
  /// <summary>
  /// Gets the string value or a default value
  /// </summary>
  /// <param name="value">String</param>
  /// <returns></returns>
  public static string ext_GetValueOrEmpty(this string value)
  {
   return ext_GetValueOrDefault(value, string.Empty);
  }
  /// <summary>
  /// Gets the string value or a default value
  /// </summary>
  /// <param name="value">String</param>
  /// <param name="defaultvalue">Default value</param>
  /// <returns></returns>
  public static string ext_GetValueOrDefault(this string value, string defaultvalue)
  {
   if (value != null) return value;
   return defaultvalue;
  }
  /// <summary>
  /// Converts string to a Name-Format where each first letter is Uppercase.
  /// </summary>
  /// <param name="value">The string value.</param>
  /// <returns></returns>
  public static string ext_ToUpperLowerNameVariant(this string value)
  {
   if (string.IsNullOrEmpty(value)) return "";
   char[] valuearray = value.ToLower().ToCharArray();
   bool nextupper = true;
   for (int i = 0; i < (valuearray.Count() - 1); i++)
   {
    if (nextupper)
    {
     valuearray[i] = char.Parse(valuearray[i].ToString().ToUpper());
     nextupper = false;
    }
    else
    {
     switch (valuearray[i])
     {
      case ' ':
      case '-':
      case '.':
      case ':':
      case '\n':
       nextupper = true;
       break;
      default:
       nextupper = false;
       break;
     }
    }
   }
   return new string(valuearray);
  }
  /// <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 ext_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.");
   }
 
   System.Security.Cryptography.CspParameters cspp = new System.Security.Cryptography.CspParameters();
   cspp.KeyContainerName = key;
 
   System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.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="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 ext_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
   {
    System.Security.Cryptography.CspParameters cspp = new System.Security.Cryptography.CspParameters();
    cspp.KeyContainerName = key;
 
    System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.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>
  /// Determines whether it is a valid URL.
  /// </summary>
  /// <returns>
  ///     <c>true</c> if [is valid URL] [the specified text]; otherwise, <c>false</c>.
  /// </returns>
  public static bool ext_IsValidUrl(this string text)
  {
   System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
   return rx.IsMatch(text);
  }
  /// <summary>
  /// Determines whether it is a valid email address
  /// </summary>
  /// <returns>
  ///     <c>true</c> if [is valid email address] [the specified s]; otherwise, <c>false</c>.
  /// </returns>
  public static bool ext_IsValidEmailAddress(this string email)
  {
   System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
   return regex.IsMatch(email);
  }
  /// <summary>
  /// Send an email using the supplied string.
  /// </summary>
  /// <param name="body">String that will be used i the body of the email.</param>
  /// <param name="subject">Subject of the email.</param>
  /// <param name="sender">The email address from which the message was sent.</param>
  /// <param name="recipient">The receiver of the email.</param>
  /// <param name="server">The server from which the email will be sent.</param>  
  /// <returns>A boolean value indicating the success of the email send.</returns>
  public static bool ext_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)
   {
    throw new Exception("Could not send mail from: " + sender + " to: " + recipient + " thru smtp server: " + server + "\n\n" + ex.Message, ex);
   }
 
   return true;
  }
  /// <summary>
  /// Truncates the string to a specified length and replace the truncated to a ...
  /// </summary>
  /// <param name="maxLength">total length of characters to maintain before the truncate happens</param>
  /// <returns>truncated string</returns>
  public static string ext_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;
  }
  /// <summary>
  /// Converts to a HTML-encoded string
  /// </summary>
  /// <param name="data">The data.</param>
  /// <returns></returns>
  public static string ext_HtmlEncode(this string data)
  {
   return System.Web.HttpUtility.HtmlEncode(data);
  }
  /// <summary>
  /// Converts the HTML-encoded string into a decoded string
  /// </summary>
  public static string ext_HtmlDecode(this string data)
  {
   return System.Web.HttpUtility.HtmlDecode(data);
  }
  /// <summary>
  /// Parses a query string into a System.Collections.Specialized.NameValueCollection
  /// using System.Text.Encoding.UTF8 encoding.
  /// </summary>
  public static System.Collections.Specialized.NameValueCollection ext_ParseQueryString(this string query)
  {
   return System.Web.HttpUtility.ParseQueryString(query);
  }
  /// <summary>
  /// Encode an Url string
  /// </summary>
  public static string ext_UrlEncode(this string url)
  {
   return System.Web.HttpUtility.UrlEncode(url);
  }
  /// <summary>
  /// Converts a string that has been encoded for transmission in a URL into a
  /// decoded string.
  /// </summary>
  public static string ext_UrlDecode(this string url)
  {
   return System.Web.HttpUtility.UrlDecode(url);
  }
  /// <summary>
  /// Encodes the path portion of a URL string for reliable HTTP transmission from
  /// the Web server to a client.
  /// </summary>
  public static string ext_UrlPathEncode(this string url)
  {
   return System.Web.HttpUtility.UrlPathEncode(url);
  }
  /// <summary>
  /// Replaces the format item in a specified System.String with the text equivalent
  /// of the value of a specified System.Object instance.
  /// </summary>
  /// <param name="arg">The arg.</param>
  /// <param name="additionalArgs">The additional args.</param>
  public static string ext_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>
  /// Determines whether [is not null or empty] [the specified input].
  /// </summary>
  /// <returns>
  ///     <c>true</c> if [is not null or empty] [the specified input]; otherwise, <c>false</c>.
  /// </returns>
  public static bool ext_IsNotNullOrEmpty(this string input)
  {
   return !String.IsNullOrEmpty(input);
  }
 }
}


Extension Methods!!!

"Extension methods" was first introduced in .NET 3.5 (C#3/VB9). It is a feature which lets you extend existing classes with new methods without the need to inherit from these classes. These classes are probably to be closed ones without access to their source code, otherwise, why extend the class when I can edit its code freely?!!!

Writing an extension method is so similar to writing a static class which wraps or uses the class which I want to extend. Actually there is always a debate on whether to use static classes or use extension methods. Me myself, I prefer to use extension methods because I think it makes the code more readable as you don't need to break the context to make use of a static method.

To get what I am saying here, suppose that we want to write a method which takes an "int", increment it by 3, multiply it by 5 and finally return the value.

To achieve this, we have 3 approaches:
  1. Writing a static class (IntHelper) with a static method inside (DoCalculations) which takes an int as input parameter (inputNum) and returns the resulting int ((inputNum + 3)*5)
  2. Writing an extension method (DoCalculations) which extends int to do the same job as above
  3. Writing a new class which inherits from int and then adds a new method (DoCalculations) which carries out the too complex calculation we are talking about :)

Now, let's check every approach and come out with a decision on which one we prefer to use.


Writing new class inheriting from int:
I think we all agree that this will be too much and inappropriate :)


Writing static class:
The code will be
  1. public static class IntHelper
  2. {
  3.     public static int DoCalculations(int inputNum)
  4.     {
  5.         return (inputNum + 3) * 5;
  6.     }
  7. }

And to use, the code will be
  1. int currentWidth = this.Width;
  2. MessageBox.Show(IntHelper.DoCalculations(currentWidth).ToString());


Writing an extension method:
The code will be
  1. public static int DoCalculations(this int source)
  2. {
  3.     return (source + 3) * 5;
  4. }

And to use, the code will be
  1. int currentWidth = this.Width;
  2. MessageBox.Show(currentWidth.DoCalculations().ToString());


So, now after we have seen all approaches, I still think that the extension method is more appropriate cause when using the call we didn't break the natural flow.

Finally, this was a brief introduction of extension methods and if you wish to know more you can read Scott Hanselman's post of title "How do Extension Methods work and why was a new CLR not required?"


Update:
Some extension methods are added in separate posts where each post includes extension methods for certain class. Please find these posts below.


Posts:
  1. Catalog
  2. System.String
  3. System.Web.UI.WebControls.WebControl
  4. System.DateTime
  5. System.Linq.IOrderedQueryable
  6. System.IConvertible
  7. Generics (T)