Computing Hash code(MD5/SHA1) of the File using c#

Tuesday, January 03, 2012 2 comments
What is hash code ?
in simple language hash code is Unique code computed using Mathematical function which is used to Authenticate the data when transmitting over network.

Where Hash code is used ?
Hash code can be used for data authentication purpose for example if you are sending data on communication channel if some one reading the data in between can modify the data and send that modified data.
to prevent modification of data(ie Authenticate) Hash codes are used.

How receiver will know that intermediate person modified the data ?
when sender sends the data it computes the Hash code of the data/file he is transmitting.At receiver side when data arrive with hash code attached Receiver recomputes the hash code and compare it with attached Hash code.if both matches that means data is Intact no one modified the data.

You will argue here that what if intermediate person Modifies the data Recomputed the hash and attach it with modified data.for that reason Simply Computed hash code is not attached to the File,instead RSA Security algorithm is used to encrypt hash code and attach it with file.
so only Alleged receiver will be able to Retrieve Correct Attached hash code value and can compare to authenticate user.

Most popular hash code algorithms are MD5(Message Digest 5) and SHA1 (Secure hashing algorithm).

Here I will not mention how to Encrypt the hash code using RSA Cryptography algorithm.article just tells how to compute hash code.

If you want to learn how to Encrypt the data using RSA Algorithm you can refer this article
private void button1_Click(object sender, EventArgs e)
{
    if (!String.IsNullOrEmpty(txtFileName.Text))
    {

        FileStream fs = new FileStream(txtFileName.Text, FileMode.Open);

        SHA1 hashFunction = SHA1.Create();
        byte[] computedHashCode = hashFunction.ComputeHash(fs);

        string HashInString = Convert.ToBase64String(computedHashCode);

        lblHashCode.Text = HashInString;
        fs.Close();
    }
}

private void btnBrowse_Click(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        string FileName = ofd.FileName;
        txtFileName.Text = FileName;
    }
}
Computing SHA1/MD5 Hash of the File using c#

Creating custom shaped forms using c#

Monday, January 02, 2012 1 comments
To create custom shaped form there are two ways one is to use transparency key property of the form and another is to use Region Property of the form object.Transparency key is OK to use but it will leave some marks at border area of the form which does not look good.so using Region property of the form solve the problem with clean look form.
 
You can use region property like below
this.Region = new Region(<GraphicPath/Rectangle Object Here>);
To create GraphicPath object you will need name space so add it like below.
using System.Drawing.Drawing2D;
For example lets say we need to create a form with oval shape then we can do it like below.
private void Form1_Load(object sender, EventArgs e)
{
    GraphicsPath p = new GraphicsPath();
    p.AddArc(new Rectangle(10, 10, 200, 200), 0, 360);
    this.Region = new Region(p);
}
You will have clean look oval shaped Windows Form.
Output :
Custom Shap Form in Windows Form using c#

Download / Upload Binary Files on FTP Server using c#

Sunday, January 01, 2012 0 comments
Here I am presenting code that is used to download and Upload files to FTP Servers To uploading and Downloading .
We will use FtpWebRequest and FtpWebResponse classes there is reason behind using these classes instead of using WebClient classes that if we use FtpWebRequest/Response classes to upload download files we can have more control over what operations are going on inside. code I am showing here is easy to understand most of prarameters i have specified is commented out so you can understand it easily. first you will need two name spaces to work with FTP.

using System.Net;
using System.IO;
And here are two functions I have made to download and Upload file
Uploading File
/// <summary>
/// Upload File to Specified FTP Url with username and password and Upload Directory if need to upload in sub folders
/// </summary>
/// <param name="FtpUrl">Base FtpUrl of FTP Server</param>
/// <param name="fileName">Local Filename to Upload</param>
/// <param name="userName">Username of FTP Server</param>
/// <param name="password">Password of FTP Server</param>
/// <param name="UploadDirectory">[Optional]Specify sub Folder if any</param>
/// <returns>Status String from Server</returns>

public static string UploadFile(string FtpUrl, string fileName, string userName, string password,string UploadDirectory="")
{
    string PureFileName = new FileInfo(fileName).Name;
    String uploadUrl = String.Format("{0}{1}/{2}", FtpUrl,UploadDirectory,PureFileName);
    FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(uploadUrl);
    req.Proxy = null;
    req.Method = WebRequestMethods.Ftp.UploadFile;
    req.Credentials = new NetworkCredential(userName,password);
    req.UseBinary = true;
    req.UsePassive = true;
            
    byte[] data = File.ReadAllBytes(fileName);
    req.ContentLength = data.Length;
    Stream stream = req.GetRequestStream();
    stream.Write(data, 0, data.Length);
    stream.Close();
    FtpWebResponse res = (FtpWebResponse)req.GetResponse();
           
    return res.StatusDescription;
}
Downloading File
/// <summary>
/// Download File From FTP Server
/// </summary>
/// <param name="FtpUrl">Base url of FTP Server</param>
/// <param name="FileNameToDownload">if file is in root then write FileName Only if is in use like "subdir1/subdir2/filename.ext"</param>
/// <param name="userName">Username of FTP Server</param>
/// <param name="password">Password of FTP Server</param>
/// <param name="tempDirPath">Folderpath where you want to Download the File</param>
/// <returns>Status String from Server</returns>

public static string DownloadFile(string FtpUrl,string FileNameToDownload,string userName, string password,string tempDirPath)
{
    string ResponseDescription = "";
    string PureFileName = new FileInfo(FileNameToDownload).Name;
    string DownloadedFilePath  =  tempDirPath+"/"+PureFileName;
    String downloadUrl = String.Format("{0}/{1}", FtpUrl, FileNameToDownload);

    FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(downloadUrl);
    req.Method = WebRequestMethods.Ftp.DownloadFile;
    req.Credentials = new NetworkCredential(userName, password);
    req.UseBinary = true;
    req.Proxy = null;

    try
    {
        FtpWebResponse response = (FtpWebResponse)req.GetResponse();
        Stream stream = response.GetResponseStream();

        byte[] buffer = new byte[2048];

        FileStream fs = new FileStream(DownloadedFilePath, FileMode.Create);
        int ReadCount = stream.Read(buffer, 0, buffer.Length);
        while (ReadCount > 0)
        {
            fs.Write(buffer, 0, ReadCount);
            ReadCount = stream.Read(buffer, 0, buffer.Length);
        }
        ResponseDescription = response.StatusDescription;
        fs.Close();
        stream.Close();
    }
    catch(Exception e)
    {
        Console.WriteLine(e.Message);
    }
    return ResponseDescription;
}

Retain values of Dynamically Created controls between postbacks in asp.net

Tuesday, December 27, 2011 0 comments
Many programmers having difficulty when creating dynamic controls on the page they are created by simple code but when you press some button / Postback occurs all values and properties are lost.

To solve the problem you need to understand the life cycle of the Page. below is normal steps performed in Page Life Cycle all steps are not included but these are few of them in order of execution.
  1. Creating Control Hierarchy
  2. Init() event
  3. Loading View State
  4. Load
  5. Save View State Data
Here in control hierarchy creation step control hierarchy is created i.e<form> <input> etc tags are converted into class file  that contain code to generate all those controls dynamically.Then after init() event is fired which calls init() event of all the servers controls too .Then after the ViewStates are loaded because we may have changed controls properties programatically after page is loaded so that must be remembered by asp.net they are restored on Load View State stage after each postback.Then after the Load Event is fired.

when we perform post back state data of controls are stored in ViewState are loaded back to control in LoadView Stat step of life cycle of the page.

so you can see that if we create control on Load Event(this is what normally all programmer do) then view state data can not be restore because LoadViewState stage is above the Load stage of page hence when ViewState data are loaded our control does not exist so we cant load data without controls. so point is  controls should be exist in page before LoadViewState stage.

so we can use Init() event where we can create dynamic control which will retrain the Control values across postbacks and will work like normal controls as we added them statically.And you can use Load Event to initialize properties of controls you created in Init() stage.That was the main logic here to retain the Values of Dynamically created control between postbacks. So , create controls at correct event of the page ;-)
protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    CreateControls();
}

public void CreateControls()
{
     /* you can get data about how many number of textbox to create using Some Other class */
     int Number = 10;

     for (int i = 0; i < Number; i++)
     {
        TextBox tb = new TextBox();
        tb.ID = "txt" + i.ToString();
        Page.Form.Controls.Add(tb);
     }
}
protected void Page_Load(object sender, EventArgs e)
{
    /* you can Initialize  Properties of Control Here that you created */
}

Check if email address really exist or not using c#

Thursday, December 22, 2011 9 comments
Summary : article demonstrate basic technique for checking if particular email is exist or not. using SMTP protocol specifications in RFC 821.
Check if Email Address Exist or not using c# code
Note : Code written here by me is for checking if particular Gmail address exist or not.To make this code work with other Mail Providers you need to find Mail Server of the particular email provider by Querying MX Record Entry of particular mail provider.

Here is how you can determine MX Record of particular mail server using cmd
Finding MX Record of Mail Service Provider
Here i used basic technique of SMTP commands to check if mail address exist or not.
Here is how typical mail server communication is done.
Receiver: 220 server.com Simple Mail Transfer Service Ready
Sender  : HELO server.com
Receiver: 250 server.com
Sender  : MAIL FROM: <abc@gmail.com>
Receiver: 250 OK
Sender  : RCPT TO: <somemailaddress@gmail.com>
Receiver: 250 OK
here when we perform RCPT TO command server checks existence of particular mail address by querying the server and if it find that Mail Address is correct it respond with 550 code and error message.

so we will fire RCPT TO command against gmail server and gmail server will respond with error message if email address in recipient field is not correct.if we get error that means email address is not correct one and we can display error to
user.

now lets do the actual code work in which we will perform communication to SMTP server exactly as shown
  • Connect to server
  • Pefrom HELO
  • Fire MAIL FROM command
  • Fire RCPT TO command and check Response
now to perform all this we need to communicate with server using Sockets i selected TcpClient to perform code. code like below to perform communication with server
using System.Net.Sockets;
using System.IO;
using System.Text;

protected void btnCheck_Click(object sender, EventArgs e)
{
    TcpClient tClient = new TcpClient("gmail-smtp-in.l.google.com", 25);
    string CRLF = "\r\n";
    byte[] dataBuffer;
    string ResponseString;

    NetworkStream netStream = tClient.GetStream();
    StreamReader reader = new StreamReader(netStream);
      
    ResponseString = reader.ReadLine();

    /* Perform HELO to SMTP Server and get Response */
    dataBuffer = BytesFromString("HELO KirtanHere" + CRLF);
    netStream.Write(dataBuffer, 0, dataBuffer.Length);
    ResponseString = reader.ReadLine();

    dataBuffer = BytesFromString("MAIL FROM:<YourGmailID@gmail.com>" + CRLF);
    netStream.Write(dataBuffer, 0, dataBuffer.Length);
    ResponseString = reader.ReadLine();

    /* Read Response of the RCPT TO Message to know from google if it exist or not */
    dataBuffer = BytesFromString("RCPT TO:<"+TextBox1.Text.Trim()+">"+CRLF);
    netStream.Write(dataBuffer, 0, dataBuffer.Length);
       
    ResponseString = reader.ReadLine();
    if (GetResponseCode(ResponseString) == 550)
    {
        Response.Write("Mai Address Does not Exist !<br/><br/>");
        Response.Write("<B><font color='red'>Original Error from Smtp Server :</font></b>"+ResponseString);
    }

    /* QUITE CONNECTION */
    dataBuffer = BytesFromString("QUITE" + CRLF);
    netStream.Write(dataBuffer, 0, dataBuffer.Length);
    tClient.Close();
}

private byte[] BytesFromString(string str)
{
    return Encoding.ASCII.GetBytes(str);
}

private int GetResponseCode(string ResponseString)
{
    return int.Parse(ResponseString.Substring(0, 3));
}

Download Sample code for Checking Mail Address Exist or Not