Sunday, October 28, 2012

Validation is a boxing value is default

public static bool IsDefault(this object o)
{
    if (o == null)
    {
        return true;
    }
    return (o.GetType().IsValueType)  
        ?  Activator.CreateInstance(o.GetType()).Equals(o)
        : false;
}

Friday, August 5, 2011

Extension of paging in LINQ

Implementation:

public static IEnumerable<T> Paging<T>(this  IQueryable<T> query,int rowCount, int pageIndex)

{

    return  query       

        .Skip((pageIndex - 1) * rowCount)

        .Take(rowCount);

}

Using:

private void TestMethod()

{

    Random rnd = new Random();

    List<Foo> fooList = new List<Foo>();

    for (int i = 0; i < 20; i++)

    {

        fooList.Add(

                new Foo

                {

                    ID = rnd.Next(100),

                    Name = Membership.GeneratePassword(5, 0)

                }

            );

    }

 

    var query = fooList.OrderBy(item => item.ID).AsQueryable();

 

   Console.WriteLine("Attempt 1");

    query.Paging(10, 1)

       .ToList()

       .ForEach(

        item => Console.WriteLine(item.ID + ": " + item.Name)

        );

    Console.WriteLine("Attempt 2");

    query.Paging(5, 2)

        .ToList()

        .ForEach(

        item => Console.WriteLine(item.ID + ": " + item.Name)

        );

}

Class:

public class Foo

{

    public int ID { get; set; }

    public string Name { get; set; }

}

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.