How to create an Enum value from the string

This is a simple code for converting string representation to Enum
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Blog_CS
{
    public enum State { New, Ready, Stop, Reset };
    class Program
    {
        private static void Main(string[] args)
        {
            const string state = "New";
            State currentState = (State)Enum.Parse(typeof(State), state);

            if (currentState == State.New)
            {
                Console.WriteLine("Run state");

            }
        }
    }
}

How to add custom sorting for a class with IComparable interface

Sometimes it necessary to sort your collection before showing it on UI.You can add custom sorting to you class just by inheriting it with  IComparable interface.IComparable interface contains one single method CompareTo.

For this post I have created a class Employee which has four properties FirstName,LastName,Age and Title.This class implements IComparable interface,which means instance of the class can be compared with other instance of this class.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Blog_CS
{
    public class Employee : IComparable<Employee>
    {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string Title { get; set; }
    public static List<Employee> Employees
        {
            get
            {
    return new List<Employee>()
                           {
    new Employee(){FirstName = "F004",LastName = "L001",Age = 21,Title = "SE"},
    new Employee(){FirstName = "F002",LastName = "L002",Age = 41,Title = "SSE"},
    new Employee(){FirstName = "F001",LastName = "L003",Age = 21,Title = "JE"},
    new Employee(){FirstName = "F003",LastName = "L003",Age = 31,Title = "APM"},
                           };
            }
        }
    #region IComparable<Employee> Members
    public int CompareTo(Employee other)
        {
    return this.FirstName.CompareTo(other.FirstName);
        }
    #endregion
    }
    class Program
    {
    static void Main(string[] args)
        {
            List<Employee> employees = Employee.Employees;
            employees.Sort();
            Console.WriteLine("FirstName    LastName   Age    Title ");
    foreach (var employee in employees)
            {
    string combineddata = String.Format("{0}\t{1}\t{2}\t", employee.FirstName,
                                employee.LastName, Convert.ToInt32(employee.Age), employee.Title);
                Console.WriteLine(combineddata);
            }
        }
    }
}

How to compute hash of a file in c#

This is a very simple code for calculating the hash of file in c# Namespace Required: using System.IO; using System.Security.Cryptography; Complete C# code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Blog_CS
{
    class Program
    {
        private const string FileName = @"D:\output.txt";
        static void Main(string[] args)
        {
            string fileHash = GetHashOfFile(FileName);
            Console.WriteLine(fileHash);
        }

        private static string GetHashOfFile(string fileName)
        {
            using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                //Create HashAlgorithm (MD5,SHA1...)
                HashAlgorithm hash = HashAlgorithm.Create("MD5");
                byte[] hashByte = hash.ComputeHash(fileStream);
                return String.Join(",", hashByte);
            }
        }
    }
}

How to convert byte array to string in c#

This is a very simple code showing how to convert byte array to string in c# Note:Make sure that you have imported the namespace 'System.Text'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Blog_CS
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] bytes = GetBytes("the quick brown fox jump over the lazy dog");
            //Convert byte array to string.
            string message = Encoding.Default.GetString(bytes);
            Console.WriteLine(message);
        }

        private static byte[] GetBytes(string message)
        {
            //Make sure that you have imported 'System.Text' namespace
            return Encoding.Default.GetBytes(message);
        }

    }
}

How to convert string to Byte array in c#

This is very simple code showing how to convert string to byte array in c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Blog_CS
{
    class Program
    {
        static void Main(string[] args)
        {
            const string message = "the quick brown fox jump over the lazy dog";
            byte[] bytes = Encoding.Default.GetBytes(message);
            Print(bytes);
        }

        private static void Print(byte[] bytes)
        {
            Console.WriteLine(String.Join(",", bytes));
        }
    }
}

How to embed exe or resource file in c# assembly

Sometimes it is necessary to embed an executable (or any other file) into your application and later recreate it during runtime.In this post I will show you how to embed resource in assembly (application)

  • Open visual studio and create a new console application 
  • Right click on the project and add existing file (resource)




Each individual file must be added into your solution as an “Embedded Resource”. To do this right 
click in the Solution Explorer then select:  Add-> Existing Item. Now locate the executable (or any other)
file of your choice and then select it. You will now see this file in the Solution Explorer. Now right
click on it and choose “Properties” Make sure "Build Action" has "Embedded Resource" selected.





C# Source Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;

namespace Embed_Resource
{
    class Program
    {
        /// <summary>
        /// This function read the name of all resouce file names from the assembly,and print those name on consolse
        /// </summary>
        private static void ReadResourceNameFromAssembly()
        {
            foreach (var resouceName in Assembly.GetExecutingAssembly().GetManifestResourceNames())
            {
                Console.WriteLine(resouceName);
            }
        }
        private static void RetriveResourceFromAssembly()
        {
            string resouceName = "Embed_Resource.data.txt";
            //Get current executing assembly
            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            //Get All resources from assembly
            //Create stream for output file
            FileStream outputFileStream=new FileStream(@"D:\output.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite);
            //Get stream to the resouce
            Stream resouceStream = currentAssembly.GetManifestResourceStream(resouceName);
            //copy resoucestream to outputstram
            if (resouceStream != null)
            {
                resouceStream.CopyTo(outputFileStream);
                resouceStream.Close();
            }
            outputFileStream.Close();
        }
        static void Main(string[] args)
        {
            RetriveResourceFromAssembly();
        }
    }
}

Invalid postback or callback argument. Event validation is enabled using

To fix, modify the web.config file located in the /admin/ folder. Change this line:
<pages validateRequest="false" />
To:
<pages validateRequest="false" enableEventValidation="false" />

How to encrypt/decrypt data in asp.net using Symmetric algorithm

In this post I am going to show you how to encrypt and decrypt data in asp.net using Symmetric algorithm.Before going to implementation details let discuss some security related terms before.

What is Hashing


Hashing is one-way algorithm, means once the data is hashed you can’t recovered it latter.
Hashing is a cryptographic function that is used to provide a secure fingerprint of data. A common usage you may have encountered is to check a file you have downloaded.

What is Encryption

If you want to secure your data, and latter you want to retrieve the original data. We used encryption because encryption is two-way processes. For encryption we requires following things


Key:Key is a piece of information that is used as an input parameter in encryption. The output of encryption is determined by the key.
Types of Encryption

are two main types of encryption and decryption algorithms, symmetric and asymmetric.

Symmetric:

In symmetric encryption we used same key for encryption and decryption( As the diagram shows the same key is used for encrypting and decrypting the message).DES, Triple DES, RC2 and AES or Rijndael are examples of symmetric algorithms




Asymmetric Encryption:

Asymmetric algorithms use a related key-pair to encrypt and decrypt data. One of the keys in the pair is typically called a public key while the other is called a private key. Data encrypted with a public key can only be decrypted with the private key, and vice-versa. PKI (public key infrastructure) is built based on asymmetric algorithm. RSA is a popular asymmetric algorithm.


What are the steps required for Encryption ?

Follow these steps to encrypt data symmetrically:

  1. Choose an algorithm.
  2. Create or retrieve a key.
  3. Generate the IV.
  4. Convert the clear text data to an array of bytes.
  5. Encrypt the clear text byte array.
  6. Store the encrypted data and the IV.

What are the steps required for Decryption?

Following are the steps required for decrypting the data.


  1. Choose the same algorithm that was used to encrypt the data.
  2. Retrieve the key that was used.
  3. Retrieve the IV that was used.
  4. Retrieve the encrypted data.
  5. Decrypt the data.
  6. Convert the decrypted data back to its original format.
Implementation 

I am going to choose Triple DES algorithm for this demo.(Step#1)


 Let's first generate IV (initialization vector) and Key (Step #2).For this,create a separate console application and paste following code inside Main method



static void Main(string[] args)
 {
  DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  des.GenerateIV();
  des.GenerateKey();
  Console.WriteLine("Key={0}",String.Join(",",des.Key));
  Console.WriteLine("IV={0}", String.Join(",", des.IV));


 }


Run the application and note down the value of IV and Key.



Create a new class named EncryptionManager and add following code



public class EncryptionManager
{
private byte[] Key = {89,83,45,236,140,228,180,79,209,164,231,131,28,7,110,73,140,235,118,52,225,46,202,118
    };
private byte[] IV = { 161, 200, 187, 207, 22, 92, 119, 227 };
public string Encrypt(string inputString)
    {
//Step #4
byte[] buffer = Encoding.ASCII.GetBytes(inputString);
        TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider()
        {
            Key = Key,
            IV = IV
        };
//Step #4,5,6
        ICryptoTransform ITransform = tripleDes.CreateEncryptor();
return Convert.ToBase64String(ITransform.TransformFinalBlock(buffer, 0, buffer.Length));
    }
public string Decrypt(string inputString)
    {
byte[] buffer = Convert.FromBase64String(inputString);
        TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider()
        {
            Key = Key,
            IV = IV
        };
        ICryptoTransform ITransform = tripleDes.CreateDecryptor();
return Encoding.ASCII.GetString(ITransform.TransformFinalBlock(buffer, 0, buffer.Length));
    }
}
How to use
Create a new webpage and add following code inside it


 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EncryptDecrypt.aspx.cs" Inherits="EncryptDecrypt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:TextBox ID="txtData" runat="server" TextMode="MultiLine"></asp:TextBox>
</td>
<td>
<asp:TextBox runat="server" ID="txtEncrypt" TextMode="MultiLine"></asp:TextBox>
</td>
<td>
<asp:TextBox runat="server" ID="txtDecrypt" TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnEncrypt" runat="server" OnClick="btnEncrypt_Click" Text="Encrypt" />
<asp:Button ID="btnDecrypt" runat="server" Text="Decrypt" OnClick="btnDecrypt_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;
using System.IO;
public partial class EncryptDecrypt : System.Web.UI.Page
{
    EncryptionManager manager = new EncryptionManager();
protected void Page_Load(object sender, EventArgs e)
    {
    }
protected void btnEncrypt_Click(object sender, EventArgs e)
    {
        txtEncrypt.Text = manager.Encrypt(txtData.Text);
    }
protected void btnDecrypt_Click(object sender, EventArgs e)
    {
        txtDecrypt.Text = manager.Decrypt(txtEncrypt.Text);
    }
}

How to compress response in asp.net

In this post I will show you how to compress http response in asp.net for improving performance. Before going into details let's create a simple website with single page Default.aspx and add following code into it Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grdPerson" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            grdPerson.DataSource = Person.Persons;
            grdPerson.DataBind();
        }
    }
}


[Serializable]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Phone { get; set; }
    public string Email { get; set; }
    public static List<Person> Persons
    {
        get
        {
            return new List<Person>()
                {
                    new Person(){FirstName="Santosh",LastName="Singh",Phone=1213123,Email="santosh@gmail.com"},
                    new Person(){FirstName="Ashok",LastName="Singh",Phone=1213123,Email="ashok@gmail.com"},
                    new Person(){FirstName="Bill",LastName="Gates",Phone=1213123,Email="bill@gmail.com"},
                };
        }

    }
    public override string ToString()
    {
        return string.Format(@"FirstName {0} & LastName {1} Phone {2} Email {3}", this.FirstName, this.LastName, this.Phone, this.Email);
    }
}
Now,press F5 and see the response result in FireBug.You will see the response result something like below
Note down the Content-Length size(in my case is 1720) Let's compress the response.For this right click on website ,and add Global.asax file.Inside this file add a method named
void Application_BeginRequest(object sender, EventArgs e)
{

}
Inside it paste the following code and see the result in FireBug
 void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext incoming = HttpContext.Current;
        string oldpath = incoming.Request.Path.ToLower();
        incoming.Response.Filter = new System.IO.Compression.GZipStream(incoming.Response.Filter, System.IO.Compression.CompressionMode.Compress);
        HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
        HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

    }
Check the Content-Length property after compression. Note:For compress/decompression I am using .net framework class GZipStream

How to Hash User Passwords in asp.net

In this post I will show you how to hash user password in asp.net Before going into implementation details,let first design the table structure.For the shake of simplicity I have taken only some fields.
Right click on the website,add asp.net special folder App_Code. Right click on App_Code folder and add new item Linq to Sql classes and drag the table from Server Explorer to Linq to sql classes surface.
Again right click App_Code and add new class named UserManager.cs inside App_Code folder.Now paste the following code in it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Web.Security;
public class UserManager
{
   
    private static string CreateSalt(int size)
    {
        //Generate a cryptographic random number.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        byte[] buff = new byte[size];
        rng.GetBytes(buff);
        // Return a Base64 string representation of the random number.
        return Convert.ToBase64String(buff);
    }
    public static string CreatePasswordHash(string pwd, string salt)
    {
        string saltAndPwd = String.Concat(pwd, salt);
        string hashedPwd =FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");
        return hashedPwd;
    }
    public void CreaetUser(string userName, string password, string email)
    {
        SecureLoginDataContext dc = new SecureLoginDataContext();
        string salt = CreateSalt(8);
        User user = new User();
        user.Email = email;
        user.Salt = salt;
        user.Password = CreatePasswordHash(password, salt);
        user.UserName = userName;
        dc.Users.InsertOnSubmit(user);
        dc.SubmitChanges();
    }

    public static User GetUserDetails(string username)
    {
        SecureLoginDataContext dc = new SecureLoginDataContext();
        User result = (from c in dc.Users
                         where c.UserName.Equals(username)
                         select c).FirstOrDefault();

        return result;
    }
   
}
Add three new pages to your website named Login.aspx,Welcome.aspx and Registration.aspx Open Login.aspx and add following code in it Login.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <table class="style1">
            <tr>
                <td>
                    UserName</td>
                <td>
                    <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Password</td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Width="128px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:Button ID="btnLogin" runat="server" Text="Login" 
                        onclick="btnLogin_Click" />
                </td>
            </tr>
        </table>
    
    </div>
    </form>
    <p>
        <a href="Registration.aspx">Not a registred member</a></p>
</body>
</html>
Login.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        User user = UserManager.GetUserDetails(txtUserName.Text);
        string tempHashPassword = UserManager.CreatePasswordHash(txtPassword.Text, user.Salt);
        //Compare tempHashPassword with haspassword stored in database.
        if (tempHashPassword == user.Password)
        {
            Response.Redirect("Welcome.aspx");
        }
        else
        {
            Response.Write("Invalid username/password");
        }
    }
}
open Registration.aspx and add following code in it
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Registration.aspx.cs" Inherits="Registration" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
 
</head>
<body>
    <form id="form1" runat="server">

    <table class="style1">
        <tr>
            <td>
                UserName</td>
            <td>
                <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Password</td>
            <td>
                <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Email</td>
            <td>
                <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;</td>
            <td>
                <asp:Button ID="btnCreate" runat="server" onclick="btnCreate_Click" 
                    Text="Create" />
            </td>
        </tr>
    </table>

    </form>
  
</body>
</html>
Registration.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnCreate_Click(object sender, EventArgs e)
    {
        UserManager user = new UserManager();
        user.CreaetUser(txtUserName.Text, txtPassword.Text, txtEmail.Text);
        Response.Redirect("Login.aspx");
    }
}