Tuesday, July 19, 2011

Convert UTF-8 to Unicode extension

The code:

public static string UTF8ToUnicode(this string input)

{

    return Encoding.Unicode.GetString(

                        Encoding.Convert(Encoding.UTF8,

                                            Encoding.Unicode,  

                                            Encoding.UTF8.GetBytes(

                                                        input)));

}

 

Example:

 

string txt ="Hello, World!";

txt.UTF8ToUnicode();

Monday, July 18, 2011

Encrypt and Decrypt extention

Today we offer Encrypt/Decrypt extension by MD5 algorithm:
/// <summary>
/// Encrypt input by MD5
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string Encrypt(this string input)
{
    using (MD5 md5Hash = MD5.Create())
    {
        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder stringBuilder = new StringBuilder();

        // Loop through each byte of the hashed data
        // and format each one as a hexadecimal string.
        Array.ForEach(data,
             item => stringBuilder.Append(item.ToString("x2"))
            );
        // Return the hexadecimal string.
        return stringBuilder.ToString();
    }
}

/// <summary>
/// Verify a hash against a string.
/// </summary>
/// <param name="input"></param>
/// <param name="hash"></param>
/// <returns></returns>
public static bool Decrypt(this string hash, string input )
{
    // Hash the input.
    string hashOfInput = Encrypt(input);
    // Create a StringComparer an compare the hashes.
    StringComparer comparer = StringComparer.OrdinalIgnoreCase;
    return (comparer.Compare(hashOfInput, hash) == default(int)) ? true : false;
}

Example:
public class Foo
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

//Your code
Foo foo = new Foo
{
    UserName = "admin",
    //Encrypt
    Password = "12345".Encrypt()
};

//Decrypt
bool isValid = foo.Password.Decrypt("12345");


Serializer as extension

From Framework 1.1 I’m use in static class for serialize and deserialize  objects. In Framework 2.0 C# got generics and class make away with word “object” but evolution is go on and time has come to create Serializer as extension:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Text;
using System.Xml.Serialization;

static class Serializer
{

/// <summary>
/// Deserializes from binary.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="bytes">buffer</param>
/// <returns></returns>
public static T DeserializeFromBinary<T>(this byte[] bytes) where T : class
{
    T obj = default(T);
    MemoryStream memoryStream = new MemoryStream(bytes);
    try
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        obj = (T)binaryFormatter.Deserialize(memoryStream);
    }
    catch (SerializationException exception)
    {
        throw;
    }
    return obj;
}

/// <summary>
/// Deserializes from file.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="path">Path.</param>
/// <returns></returns>
public static T DeserializeFromFile<T>(this string path) where T : class
{
    T obj = default(T);
    FileStream fileStream = new FileStream(path, FileMode.Open);
    try
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        obj = (T)binaryFormatter.Deserialize(fileStream);
    }
    catch (SerializationException exception)
    {
        throw;
    }
    finally
    {
        fileStream.Close();
    }
    return obj;
}

/// <summary>
/// Deserializes from string that contains SOAP.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="soap">S.</param>
/// <returns></returns>
public static T DeserializeFromSoap<T>(this string soap) where T : class
{
    T obj = default(T);
    MemoryStream memoryStream = new MemoryStream(new UTF8Encoding().GetBytes(soap));
    try
    {
        SoapFormatter soapFormatter = new SoapFormatter();
        obj = (T)soapFormatter.Deserialize(memoryStream);
    }
    catch (SerializationException exception)
    {
        throw;
    }
    return obj;
}

/// <summary>
/// Deserializes from XML string
/// </summary>
/// <param name="type">Type.</param>
/// <param name="s">S.</param>
/// <returns></returns>
public static T DeserializeFromXml<T>(this string xml) where T : class
{
    T obj = default(T);
    try
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        obj = (T)xmlSerializer.Deserialize(new StringReader(xml));
    }
    catch (SerializationException exception)
    {
        throw;
    }
    return obj;
}

/// <summary>
/// Deserializes from XML file.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="xmlFilePath">file path.</param>
/// <returns></returns>
public static T DeserializeFromXmlFile<T>(this string xmlFilePath) where T : class
{
    T obj = default(T);
    FileStream fileStream = default(FileStream);
    try
    {
        fileStream = new FileStream(xmlFilePath, FileMode.Open);
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        obj = (T)xmlSerializer.Deserialize(fileStream);
    }
    catch (Exception exception)
    {
        throw;
    }
    finally
    {
        fileStream.Close();
    }
    return obj;
}

/// <summary>
/// Gets the size of the object.
/// </summary>
/// <param name="obj">O.</param>
/// <returns></returns>
public static long GetByteSize<T>(this T obj) where T : class
{
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    MemoryStream memoryStream = new MemoryStream();
    binaryFormatter.Serialize(memoryStream, obj);
    return memoryStream.Length;
}

/// <summary>
/// Serializes to binary stream.
/// </summary>
/// <param name="obj">Obj.</param>
/// <returns></returns>
public static byte[] SerializeToBinary<T>(this T obj) where T : class
{
    byte[] buffer = new byte[0x9c4];
    MemoryStream memoryStream = new MemoryStream();
    try
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(memoryStream, obj);
        memoryStream.Seek(0, SeekOrigin.Begin);
        if (memoryStream.Length > buffer.Length)
        {
            buffer = new byte[memoryStream.Length];
        }
        buffer = memoryStream.ToArray();
    }
    catch (Exception exception)
    {
        throw;
    }
    finally
    {
        memoryStream.Close();
    }
    return buffer;
}


public static void SerializeToBinary<T>(this T obj, string filePath) where T : class
{
    SerializeToBinary(obj, filePath, FileMode.Create);
}

public static void SerializeToBinary<T>(this T obj, string filePath, FileMode mode) where T : class
{
    FileStream fileStream = default(FileStream);
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    try
    {
        fileStream = new FileStream(filePath, mode);
        binaryFormatter.Serialize(fileStream, obj);
    }
    catch (Exception exception)
    {
        throw;
    }
    finally
    {
        fileStream.Close();
    }
}

public static string SerializeToSoap<T>(this T obj) where T : class
{
    string returnValue = string.Empty;
    MemoryStream memoryStream = new MemoryStream();
    try
    {
        SoapFormatter soapFormatter = new SoapFormatter();
        soapFormatter.Serialize(memoryStream, obj);
        memoryStream.Seek(0, SeekOrigin.Begin);
        returnValue = Encoding.ASCII.GetString(memoryStream.ToArray());
    }
    catch (Exception exception)
    {
        throw;
    }
    finally
    {
        memoryStream.Close();
    }
    return returnValue;
}

public static void SerializeToSoap<T>(this T obj, string filePath, FileMode mode) where T : class
{
    FileStream fileStream = default(FileStream);
    SoapFormatter soapFormatter = new SoapFormatter();
    try
    {
        fileStream = new FileStream(filePath, mode);
        soapFormatter.Serialize(fileStream, obj);
    }
    catch (SerializationException exception)
    {
        throw;
    }
    finally
    {
        fileStream.Close();
    }
}

public static string SerializeToXml<T>(this T obj) where T : class
{
    string returnValue = string.Empty;
    MemoryStream memoryStream = new MemoryStream();
    try
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        serializer.Serialize(memoryStream, obj);
        memoryStream.Seek(0, SeekOrigin.Begin);
        returnValue = Encoding.ASCII.GetString(memoryStream.ToArray());
    }
    catch (SerializationException exception)
    {
        throw;
    }
    finally
    {
        memoryStream.Close();
    }
    return returnValue;
}

public static void SerializeToXmlFile<T>(this T obj, string filePath, FileMode mode) where T : class
{
    FileStream fileStream = default(FileStream);
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    try
    {
        fileStream = new FileStream(filePath, mode);
        serializer.Serialize(fileStream, obj);
    }
    catch (Exception exception)
    {
        throw;
    }
    finally
    {
        fileStream.Close();
    }
}
}

A method limited to using by class only but not prevent from errors. Examples:
public class Foo
{
    public int ID { get; set; }
    public string Name { get; set; }
}
//……………………
//Your code
Foo foo = new Foo
{
    ID = 5,
    Name = "John Smith"
};
//Serialize
string xml = foo.SerializeToXml();
//Deserialize
Foo newFoo = xml.DeserializeFromXml<Foo>();
//Serialize
foo.SerializeToXmlFile(@"C:\file.xml", System.IO.FileMode.CreateNew);
//Deserialize
byte[] bytes = //...;
bytes.DeserializeFromBinary<Foo>();
// And more extension is working by same  calling

Enjoy!

IsDefault extension

Known reserved word of C#  default(TYPE)  can be used as very usability feature as IsDefault():

public static bool IsDefault<T>(this T value)
{
    return value == null || value.Equals(default(T));
}
A can be available in every place in the project by next using:

int number = 5;
if (number.IsDefault())
{
    //...
}

It's  short and simple alternative to usual:
if (number == default(int)) 

The extension work nice with objects:
class Foo
{
    public int Id { get; set; }
    public int Name { get; set; }
}
//...
Foo foo = new Foo();
if (!foo.IsDefault())
{
    //....
    foo.Name = "John Smith";
}
 Enjoy!

Sunday, July 17, 2011

ForEach for ICollection<T>

I like inline function list.ForEach() for IList but always disappointed regarding to ICollection. In order to run loop requered to create Enumerator and etc. Therefore I offering short solutions:
public static void ForEach<T>(this IEnumerable<T> collection,Action<T> action)
{
    IEnumerator<T> enumerator = collection.GetEnumerator();
    while (enumerator.MoveNext())
    {
        action.Invoke(enumerator.Current);
    }
}

A using:

Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("a", 123);
dic.Add("b",456);
//Example 1
dic.ForEach(item => Console.WriteLine(item.Key));


Action<string, int> print = (key, value) =>
{
    Console.WriteLine(
        string.Format("Key: {0}, value: {1}", key, value)
    );
};
//Example 2
dic.ForEach(item => print(item.Key, item.Value));

Enjoy.

Extension for expression (List == null || List.Count > 0)

How many times in the time of coding you had to write an expression as:
List<T> list = new List<T>();
//...
if (list == null || list.Count  == 0)
{
// ...
}
I offering elegant and short solution with the assistance of extension with same name like string.You can use it not only in List but in everyone that inherits from IEnumarable<>:Add next extension(or class) to your project:
public static class Extensions
{
    public static bool IsNullOrDefault<T>(this IEnumerable<T> value)
    {
        return (value == null || value.Count() == default(int));
    }
}

Using:
List<string> list =  new List<string>();
bool isTrue = list.IsNullOrDefault();
list.Add("abc");
bool isFalse = list.IsNullOrDefault();

int[] numbers = null;
isTrue = numbers.IsNullOrDefault();
numbers = new int[] {1};
isFalse = numbers.IsNullOrDefault();

Enjoy!

Object ToString() extension

In the past we used by static methods in order to print properties of the object to console or log file but in the epoch of LINQ and extension possible to convert  old method to small expression only:
public static string Print<T>(this T obj)
{
    StringBuilder sb = new StringBuilder();
    Array.ForEach<PropertyInfo>(typeof(T).GetProperties(),
        property => sb.AppendFormat("{0}: {1}, \n", property.Name, property.GetValue(obj, null)));
    return sb.ToString();
}

And of course example for using:
public class Foo
{
    public int ID { get; set; }
    public string Name { get; set; }
}
 //Your code
Foo foo = new Foo
{
ID = 5,
Name = "John Smith"
};
Console.Write(foo.Print());
Enjoy!

Convert type extension

Current extension allow to convert type to type with/without throwing exception:
public static T ConvertTo(this object value,  
                 bool isThrowException = false
              T defaultValue = default(T))
       {
           try
           {
               return (T)Convert.ChangeType(value, typeof(T));
           }
           catch (Exception ex)
           {
               if (isThrowException)
               {
                   throw ex;
               }
           }
           return defaultValue;
       }

Using:
string numberString = "5";
//Return correct or default value and not throwing exception
int numInt = numberString.ConvertTo<int>();
//Return correct or default value and throwing exception
numInt = numberString.ConvertTo<int>(true);
//Return correct or value(-1) and not throwing exception
numInt = numberString.ConvertTo<int>(false,-1);