C#: String to Enumeration Extension Method

Here is another useful one I came across a while ago, don’t remember what site but thanks to whoever wrote it. This Extension Method takes the String and converts it to the Enumeration Type that is specified.

        /// 
        /// Converts the string to the Enumeration Type supplied.
        /// 
        /// 
        /// The String.
        /// Enumeration of Type Supplied
        /// Thrown if the string cannot be converted to the Enum type.
        /// Thrown if the string is null.
        public static T ToEnum(this string value)
        where T : struct
        {
            return (T)Enum.Parse(typeof(T), value, true);
        }

C#: SHA1 String Hash Extension Method

In a recent project I needed the ability to take an incoming string value and calculate its SHA1 Hash in order to tell if the value had been altered in some way. Instead of creating a special utility class to accomplish this I figured a clean solution would be to just add an extension method to the String class. Here is what I came up with.

        /// 
        /// Calculates the SHA1 hash and returns it as a base64 string.
        /// 
        /// Source string to hash
        /// Base64 Hash or null.
        /// Occurs when value or key is null or empty.
        public static string GetSha1Hash(this string value)
        {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentException("String is empty and not hashable.");
            Byte[] bytes = Encoding.UTF8.GetBytes(value);
            Byte[] computedHash = new SHA1CryptoServiceProvider().ComputeHash(bytes);
            return Convert.ToBase64String(computedHash);
        }

C#: ArrayList.ToList() Extension Method

I notices while working with a 3rd party component that the built-in ArrayList object in .Net does not have a built-in ToList() method to convert it to a generic List like various other list objects.
I actually prefer using generic lists much more than the standard collections since they provide tons more functionality. Because of the all this I decided it was about time I add an extension method to my library for converting ArrayLists to a typed generic list.

    public static class ArrayListExtensions
    {
        /// 
        /// Adds the ability to convert a standard
        /// ArrayList into a Generic List.
        /// 
        /// 
        /// The list.
        /// 
        public static List ToList(this ArrayList list)
        {
            List resultList = new List();
            foreach (T item in list)
            {
                resultList.Add(item);
            }
 
            return resultList;
        }
    }

C#: Windows to Unix/Linux Time Conversions

From what I have learned on a recent project is that Windows machines calculate the current date starting on 1/1/0001 where as Linux machines are calculating their time off of what is called the “Start of Epoch” which turns our to be 1/1/1970. I guess we could call it an Epoch year with all the disco and bellbottom pants!
When using Time Stamps across operating system boundaries it is always a good idea to use UTC time (Universal Time) so that you don’t have to mess with time zones. But as I came to find out, that is not enough, you also have to calculate that time stamp from the same origin date.
Below is how you accomplish this in C#:

DateTime startOfEpoch = new DateTime(1970, 1, 1);
long milliseconds = (long)(DateTime.UtcNow - startOfEpoch).TotalMilliseconds;

C#: Type Safe ICloneable Implementation

By default the ICloneable interface defines a Clone() method which returns an object of type Object and therefore is not a type safe action. To make your implementation of the ICloneable interface type safe for the following. By adding a typed Clone() method to your class and then adding an Explicit implementation of the ICloneable.Clone() interface method which returns the results of your Clone() method the returned object will be typed correctly.

        #region Public Methods

        /// 

        /// Clones this instance.

        /// 

        /// 

        public Program Clone()

        {

            Program cloneProgram = new Program();

            cloneProgram.Id = Id;

            cloneProgram.Name = Name;

            cloneProgram.EnrollDate = EnrollDate;

            cloneProgram.SubmitDate = SubmitDate;

            cloneProgram.EvalDate1 = EvalDate1;

            cloneProgram.EvalDate2 = EvalDate2;

            cloneProgram.EvalDate3 = EvalDate3;

            cloneProgram.Link = Link;

            cloneProgram.Style = Style;

            cloneProgram.Behaviors = Behaviors;

            cloneProgram.Interests = Interests;

            return cloneProgram;

        }

        #endregion

        #region Interface Methods

        /// 

        /// Creates a new object that is a copy of the current instance.

        /// 

        /// 

        /// A new object that is a copy of this instance.

        /// 

        /// 2

        object ICloneable.Clone()

        {

            return Clone();

        }

        #endregion

C#: Cloneable Generic List Extension Method

Unfortunately the built in C# generic list does not have a Clone() method. If you need to clone a list for manipulation purposes you can always use an extension method and add a Clone() method yourself. Below is an Extension Method for Cloning a generic list in C#:

public static class ListExtension

    {

        public static IList Clone(this IList listToClone) where T : ICloneable

        {

            return listToClone.Select(item => (T)item.Clone()).ToList();

        }

    }

C#: Sending Email

To send email from your application or website do the following:

1. Add this config entry to your (App)(Web).config altering the host to the URL or IP address of your email server with the associated credentials.

    <system.net>

        <mailSettings>

            <smtp from="noreply@medimedia.com">

                <network host="localhost" password="" userName="" />

            </smtp>

        </mailSettings>

    </system.net>

2. Use the following code to create and send a MailMessage

Version:0.9 StartHTML:0000000105 EndHTML:0000007499 StartFragment:0000000105 EndFragment:0000007499

        private void SendEmail()

        {

            MailMessage message = new MailMessage();

            message.From = new MailAddress(_fromEmail);

            foreach (string email in _emailList)

            {

                message.To.Add(new MailAddress(email));

            }

            message.Subject =  _subject;

            message.IsBodyHtml = false;

            message.Priority = MailPriority.High;             

            message.Body = _body;


            try

            {

                SmtpClient client = new SmtpClient();

                client.Send(message);

            }

            catch (Exception ex)

            {

               //TODO: Handle exception

            }

        }