C#: DateTime to UTC to Milliseconds

If you need to create a universal timestamp which can be sent between servers which may live in different timezones the best way to do this is to make sure you are using the Universal Time standard or UTC. Once you are using the UTC all servers evaluating the timestamp will be able to read in the UTC time and compare it against their UTC and determine if the timestamp has exceeded its limit.

Another issue along the same lines was the service we were calling was not only looking for a UTC time for its timestamps but also wanted that time in the form of milliseconds. Unfortunately there is no built in method on the DateTime Object for converting the current time to milliseconds. In order to get around this you have to do a trick using the total ticks from the DateTime object and then using a property of the TimeSpan object called TicksPerMillisecond. If you divide the ticks by the TicksPerMillisecond property you get the total miliseconds for the current time.

Example:

DateTime.Now.ToUniversalTime().Ticks / TimeSpan.TicksPerMillisecond

C# Dynamically Creating Objects by Class Name

This is an example of how to use the System.Reflection namespace within .Net framework to look inside an assembly in an attempt to locate and instantiate a class of a specific type when you only know its string name and which fits a specific interface.

When would you use this?  Although not very common in everyday coding there really are a few times in my experience where this method has helped me out. For example I used an Enumeration with Attributes to hold various values. One of those Attributes contained the string name of the class which needed to be instantiated by the code using the Enumeration. Because at run-time I only had the string name of the class I was unable to actually instantiate the type or the class from just the string. The method below allowed me to pass in the string name of the class and get back an instantiation of that type in the form of its implemented Interface and then use that class as needed.

Lets see just how creative you can be, add a comment with an example of how you used it.

public static IPerson GetPersonObject(string className, out Type objectType)

        {

            //Get a reference to the assembly containing the target classes

            Assembly assembly = Assembly.Load("DynamicalClassInvokation");

 

            //Get a list of all the classes in that assembly

            List<Type> classes = assembly.GetTypes().ToList();

 

            //Locate the class by its string name

            objectType = classes.Single(x => x.Name.Equals(className, StringComparison.InvariantCultureIgnoreCase));

 

            //Create the object, cast it and return it to the caller

            return (IPerson)Activator.CreateInstance(objectType);

        }

.Net TrippleDES Encryption

Although TrippleDES is no longer considered to be a very secure encryption method you may find there are still uses for it. In my case I ended up needing to encrypt some sensitive query string parameters which were being passed between an application I worked on and a 3rd party. The encryption needed to be easily implemented, use a common key to encrypt and decrypt the data as well as require very little alterations by the 3rd party code. In order to meet all of these demands the application Architect (one awesome mentor) decided we would use the TrippleDESCryptoServiceProvider built into the .Net Cryptography library.

In order to use the provider you first need to add a reference to System.Security.Cryptography (using System.Security.Cryptography).

Now because cryptographic algorithms encrypt data block by block and because contiguous blocks may contain identical data it is always wise to use what is called an ‘Initialization Vector’. This provides TrippleDES with a beginning block of data which it uses to encrypt the first block of actual data. This starts a chain reaction as the algorithm then uses the previous blocks data to process and encrypt each subsequent block. Why is this important you ask? Well had we not used the previous blocks data to encrypt each following block, then all blocks with identical data would have been encrypted using the private key to the exact same result, i.e. they would be identical. With identical blocks throughout the encryption it is much easier for someone to figure out the patterns and begin to identify individual characters and decode what was meant to be secret.

An example would be a text document which is made up of English letters. If every ‘e’ was encrypted to the same result and we were aware that in the English language the letter ‘e’ is the most commonly used letter we could then scan the encrypted results for a pattern which happens the most and conclude they are all the letter ‘e’. Following the same pattern we could run down the alphabet by priority of common use and eventually decode the entire document, of course inserting characters as need like in ‘Wheel of Fortune’. The Initializer Vector allows us to reduce the patterns that begin to show up within the encrypted results thus reducing the ease of decryption by those without the private key (This was of course a simplistic example).

Here are examle Encryption/Decryption methods you can use to accomplish TrippleDES encryption:

using System;

using System.Text;

using System.Security.Cryptography;

public static class StringExtensions

{

    public static string EncryptString3Des(this string value, string key, byte[] iVector)

    {

        //(Example) Initialization Vector: byte[] IVector = new byte[8] { 27, 9, 45, 27, 0, 72, 171, 54 };

        byte[] buffer = Encoding.ASCII.GetBytes(value);

        TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();

        MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();

        tripleDes.Key = MD5.ComputeHash(Encoding.ASCII.GetBytes(key));

        tripleDes.IV = iVector;

        ICryptoTransform ITransform = tripleDes.CreateEncryptor();

        return Convert.ToBase64String(ITransform.TransformFinalBlock(buffer, 0, buffer.Length));

    }

    public static string DecryptString3Des(this string value, string key, byte[] iVector)

    {

        //(Example) Initialization Vector: byte[] IVector = new byte[8] { 27, 9, 45, 27, 0, 72, 171, 54 };

        byte[] buffer = Convert.FromBase64String(value);

        TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();

        MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();

        tripleDes.Key = MD5.ComputeHash(Encoding.ASCII.GetBytes(key));

        tripleDes.IV = iVector;

        ICryptoTransform ITransform = tripleDes.CreateDecryptor();

        return Encoding.ASCII.GetString(ITransform.TransformFinalBlock(buffer, 0, buffer.Length));

    }

}

C# Dynamically Creating XDocuments from Collections

        private XDocument GenerateExtendedAttributes(Dictionary<string, List<string>> attributes)

        {

            XDocument xDoc = new XDocument();

            XElement xRoot = new XElement("ExtendedAttributes");

            xDoc.Add(xRoot);

            foreach (KeyValuePair<string, List<string>> attribute in attributes)

            {

                XElement xExtendedAttribute = new XElement("Attribute",

                                                   new XAttribute("Key", attribute.Key));

                foreach (string value in attribute.Value)

                {

                    xExtendedAttribute.Add(

                        new XElement("Value", value));

                }

                xRoot.Add(xExtendedAttribute);

            }

            return xDoc;

        }

C# Inheritance Components

Class: Represent objects in code. Contain Fields (data storage), Methods (actions), Properties (attributes)

Interface: When an Interface is defined it lists out the public methods which must be created by any class which implements the Interface. It is a contract between objects stating that they will always provide their own implementations of a set of specific method signatures. This allows for other classes to accept an Interface type without knowing the details of its implementation, it only needs to know that the public contract methods are there for it to use.

Abstract Base Classes: When a class is declared as Abstract is prevents direct instantiation of the class in code. Instead a new class has to be created which derives from the Abstract class. This allows you to create a base class with base implementations but forces users of that class to derive their own classes from it in order to use the functionality.

Abstract Methods: When a base class declares a method as being Abstract it does not provide a default implementation and demands that all derived classes must override the method with its own implementation.

Virtual Methods: When a base class declares a method as being Virtual it provides a default implementation for that method but allows any derived classes to override the method with its own implementation.

C# Custom Exceptions

[Serializable]

class AttributeNullException : Exception

{

///

/// Initializes a new instance of the class.

///

/// The message.

public AttributeNullException(string message): base(message)

{

}

///

/// Initializes a new instance of the class.

///

/// The message.

/// The inner exception.

public AttributeNullException(string message, Exception innerException): base(message, innerException)

{

}

///

/// Initializes a new instance of the class.

///

/// The that holds the serialized object data about the exception being thrown.

/// The that contains contextual information about the source or destination.

///

/// The parameter is null.

///

///

/// The class name is null or is zero (0).

///

public AttributeNullException(SerializationInfo info, StreamingContext context): base(info, context)

{

}

}