Monday 1 December 2014

Basic Git Operations With GIT GUI for Windows User



Recently I started working on a project which is using GIT as its repository for version controlling. Previously I worked with SVN, CVS but not yet got a chance to work with GIT and was really excited to work with it. But later on I came to know that most of the operations done in GIT are done using commands which most of the window users not found very convenient and so I am.

Anyways, I found a window based utility called GIT GUI for basic operation with GIT repository like download contents from GIT repository, Get latest version, commit your changes to repository etc. I faced some problem in using it with available help for basic operation and concluded something to make its use simple. 

So Today, I am sharing steps in very simple way for basic operation with GIT GUI These steps might be really helpful to you guys if you are just starting working with GIT.

To access GIT repository we needs following mandatory things.
1. GIT GUI tool - Click Here to get it now
2. GIT based repository root location
3. Credentials to access GIT repository

Assuming you have already downloaded and installed GIT - GUI on your windows machine. Now we are going to discuss following basic operations.

1. Clone Repository - This operation creates a clone of actual repository (Actual repository resides on remote server) on your local machine. This clone on your local machine will be your working copy. Below are the steps to create clone of a repository.
For Ex - Assume we have GIT repository as below to work with

Step 1 - Right click in a directory where you want to download contents from GIT repository and select Git GUI here from context menu.





Step 2 - Click on Clone Existing Repository link



Step 3 - Enter remote repository location in source 
Enter path of directory in target to create local copy of repository on your machine and click on Clone” button. 



It will download content of repository in specified path on your local machine. Now you are ready to work with content code or anything.  

2. Pull latest changes - Pull operation is used to get latest changes from remote repository to your local repository or you can say that pull command is used to sync your local repository with remote repository. Steps are given below.

Step 1 - Right click directory where you created your local repository using Clone operation and select Git GUI here from context menu. GIT GUI will be open and pointing to your local repository as below. This window has various option to perform various operation with GIT repository but we are just going to cover most basic operations that are needed at beginner level. 



Step 2 - Select Remote --> Fetch from --> origin
This will fetch (pull) all latest changes from remote repository to your local repository from head/root level, that means all latest changes committed in repository will be in your local repository as well now.



Note:- There is also option to pull specif changes as well if you don’t want to refresh complete copy for any reason.

3. Commit Changes to local repository : - Once we have created our local repository and taken latest changes than we are ready to add or modify files in repository. Assuming you have made some changes in main.txt file as available in your local repository. Below are the steps to scan your modified files and commit them in your local repository.

Step 1 - Select your local repository folder and right click and select Git GUI here. This will open GIT GUI utility.



Step 2 - All modified files will appear in left upper box (titled with Unstaged changes”). You can Rescan for modified files if GUI was not already open and not showing your modified files. Tool will show you contents of selected filed in right upper box and displays your modification in content with green (for addition) and red (for deletion).

Step 3 - Select specific file which you want to commit in repository and click on file icon in left of file name from “Unstaged changes” box. This will move your file to lower left box (titled with  “Staged Changes (Will Commit)” )


Step 4 - Enter commit message in right lower box for this specific commit and click on “Commit” button. This will commit your changes to local repository.



Note:- There is option available to add specific line to commit from specific file through selecting file in unstaged box and content will appear in right upper box. Now select specific line and right click, context menu option will appear to stage changes and unstage changes. All staged changes will commit to your local repository.


4. Push changes to remote repository:- Now after commit what else? Here comes the twist in case of GIT repository. As we have created a clone of repository and that is on our local machine only. So this local repository is maintaining version only for our changes to not to lost your changes. But these changes are still not uploaded to remote repository. 
There is Push operation which is used to push your committed changes to remote.   repository. Below are the steps to push changes to remote location. 

Step 1:- Click on “Push” button which will open “Push” window and titled with “Push Branches”


Step 2:- Select master in source branches and enter your remote GIT repository location (As used earlier during cloning of repository) in Arbitrary Location text box. Various options available but not select any check box for now and click on “Push” button. Screen shown above.

Step 3:- Provide the credentials (Username/Password) for repository and click on OK button.



Success screen will appear if your changes successfully pushed to remote repository.



Important points

1. Keep backup of your changes initially for few days until you got confident with the tool.
2. Always get latest changes from remote repository before pushing your changes to it
3. Avoid committing complete branch until you are sure to commit
4. If there is any conflict in file while you taking latest changes resolve them first and commit changes to you local repository and then push your repository changes to remote repository.

Now you are good to go with very basic operations to play with GIT repository. There is lots of other options available in GIT GUI utility that you can explore further.

A good article for further detailed operations with GIT GUI  is here to explore more. Till than keep exploring.

Wednesday 11 June 2014

SFTP upload with .Net Application


Today I was working on a utility which need to upload data on FTP. I have implemented code to upload on FTP using FTP web request. But end of the day when I finally deployed the code, I received the details of SFTP account with host, username, password and port. When I configured these details in utility the utility has failed to upload file on FTP.

Then I started researching reason of failure and found that .Net don’t support secured FTP i. e. SFTP. After searching over net I found that we need to use third party library to upload files on SFTP while using with .Net. There are many third party libraries available for SFTP, two of them are given below that could be used for this purpose.

         1.      Rebex SFTP
         2.      SharpSSH

SharpSSH is open source library and published with BSD License. I have decided to use this one for SFTP functionality implementation.

SharpSSH is a pure .NET implementation of the SSH2 client protocol suite. It provides an API for communication with SSH servers and could be integrated into any .NET application.

I am just going to discuss quick integration of this library to implement SFTP functionality in your application. You can download source code or DLLs for SharpSSH here.

Sharp SSH is actually using some java library and commands to support SFTP which is covered in a wrapper to work with .Net.

You will get following three DLLs in download
          1.      Tamir.SharpSSH.dll
          2.      Org.Mentalis.Security.dll
          3.      DiffieHellman.dll

You need to add reference to Tamir.SharpSSH while two other DLLs should also be referenced or added in bin. Org.Mentalis.Security dll is used for encryption. Now let’s come directly to the small piece of code which is doing SFTP here.

//Include namespace for Tamir.SharpSSH and System.IO as below.
using Tamir.SharpSsh;
using System.IO;

//Collect SFTP account details and root directory to upload file in.
string m_FTPServerAddress = "x.x.x.x"; // this is host IP or host domain name
string m_FTPUser = "username"; // this is username as needed to access SFTP
string m_FTPPassword = "Password"; // this is password as needed to access SFTP
string m_FTPPort = "Port"; //this is port number which is configured in SFTP for communucation.

string m_RemoteFTPFolder = "/RootFolderName/"; // this is root folder name as configured in SFTP.

string filePathAndName = "File path"; //This is cmplete file name with physical path.

//Create object for SFTP class as in Tamir.SharpSSH dll.
Sftp scp = new Sftp(m_FTPServerAddress, m_FTPUser, m_FTPPassword);

//Connect to SFTP using port as provided.
scp.Connect(m_FTPPort.ToIntSafe());

//Put/upload file on SFTP from source location to destination location in SFTP root directory.
scp.Put(filePathAndName, m_RemoteFTPFolder + Path.GetFileName(filePathAndName));

//Close connection from SFTP after uploading.
scp.Close();

Now refer above code and notice three magical lines which are doing actual job here as below.
1.      Following line of code creates an object of a SFTP class as in Tamir.SharpSSH using available ftp server address which is host ip/name, SFTP user name and SFTP password.

Sftp scp = new Sftp(m_FTPServerAddress, m_FTPUser, m_FTPPassword);

2.      Following line connects and creates a communication channel between application and SFTP host using specific post as provided in “m_FTPPort” variable.

scp.Connect(m_FTPPort.ToIntSafe());

3.      Following line of code uploads file from source path to destination path on Sftp root.

//scp.Put(source_file, destination_file);
scp.Put(filePathAndName, m_RemoteFTPFolder + Path.GetFileName(filePathAndName));

4.      Following line of code finally closes connection and communication channel from SFTP host.

scp.Close();

The code as explained above is tested and working properly. While I was trying to implement this code I came with an exception with no information in it. But after researching and trying I come to know that I was giving just file name in destination file as specified in point 3. While root folder of SFTP was needed as prefixed with file name to successfully upload file on SFTP server.

I just mentioned above point so that no one other should stuck in such a small problem.
Now enjoy SFTP upload just like normal FTP upload.

Wednesday 26 March 2014

CAPTCHA Integration.

We are doing lots of daily routine work online now a days and therefore lots of vendors providing online membership in their site to maintain our daily or monthly tasks like to recharge your mobile, DTH recharge, Pay your bills etc. 

But some of the intruders tries to hangout their system by creating fraud members and so on using program or scripts. So to avoid these automated traffic/junk data for membership, registration, some specific checks/verifications are popular to be applied on site pages to verify human being submission/activity to conform valid membership/registration. 

One of the most famous approach is CAPTCHA. Which is actually an image containing some alpha/numeric/alphanumeric code which could not be easily understand by program and script. Thus CAPTCHA helps to avoid automated submission/registration etc. 

Today we are going to integrate a very basic level captcha which could be explored more to make it more complex to break for automated scripts or programs. 

1.       Create a class and name it as “GenerateRandomCaptchaImage.cs” and copy below code and paste in it.

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System;
public class GenerateRandomCaptchaImage
{

    #region [Constructor]
   
    public GenerateRandomCaptchaImage() { }
   
    #endregion

    #region [Properties]

    private string captchaText;
    public string CaptchaText
    {
        get { return this.captchaText; }
    }

    private Bitmap captchaImage;
    public Bitmap CaptchaImage
    {
        get { return this.captchaImage; }
    }

    private int captchaWidth;
    public int CaptchaWidth
    {
        get { return this.captchaWidth; }
    }

    private int captchaHeight;
    public int CaptchaHeight
    {
        get { return this.captchaHeight; }
    }

   
    #endregion

    #region [Private Variables]

    private Random random = new Random();

    #endregion

    #region [Methods]

    public GenerateRandomCaptchaImage(string s, int width, int height)
    {
        this.captchaText = s;
        this.SetDimensions(width, height);
        this.GenerateCaptchaImage();
    }
    public void Dispose()
    {
        GC.SuppressFinalize(this);
        this.Dispose(true);
    }
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
            this.captchaImage.Dispose();
    }
    private void SetDimensions(int width, int height)
    {
        if (width <= 0)
            throw new ArgumentOutOfRangeException("width", width,
                "width must be greater than zero.");
        if (height <= 0)
            throw new ArgumentOutOfRangeException("height", height,
                "Height must be greater than zero.");
        this.captchaWidth = width;
        this.captchaHeight = height;
    }

    private void GenerateCaptchaImage()
    {
        //Declare bitmap variable.
        Bitmap captchaBitmap = new Bitmap
          (this.captchaWidth, this.captchaHeight, PixelFormat.Format32bppArgb);
        Graphics captchaGraphics = Graphics.FromImage(captchaBitmap);
        captchaGraphics.SmoothingMode = SmoothingMode.AntiAlias;
        Rectangle imageRect = new Rectangle(0, 0, this.captchaWidth, this.captchaHeight);
        HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti,
            Color.LightGray, Color.White);
        captchaGraphics.FillRectangle(hatchBrush, imageRect);
        SizeF size;
        float fontSize = imageRect.Height + 1;
        Font font;

        do
        {
            fontSize--;
            font = new Font(FontFamily.GenericSansSerif, fontSize, FontStyle.Bold);
            size = captchaGraphics.MeasureString(this.captchaText, font);
        } while (size.Width > imageRect.Width);
        StringFormat format = new StringFormat();
        format.Alignment = StringAlignment.Center;
        format.LineAlignment = StringAlignment.Center;
        GraphicsPath graphicPath = new GraphicsPath();
       
        graphicPath.AddString(this.captchaText, font.FontFamily, (int)font.Style, 75, imageRect, format);
        float v = 4F;
        PointF[] points =
          {
                new PointF(this.random.Next(imageRect.Width) / v, this.random.Next(
                   imageRect.Height) / v),
                new PointF(imageRect.Width - this.random.Next(imageRect.Width) / v,
                    this.random.Next(imageRect.Height) / v),
                new PointF(this.random.Next(imageRect.Width) / v,
                    imageRect.Height - this.random.Next(imageRect.Height) / v),
                new PointF(imageRect.Width - this.random.Next(imageRect.Width) / v,
                    imageRect.Height - this.random.Next(imageRect.Height) / v)
          };
        Matrix matrix = new Matrix();
        matrix.Translate(0F, 0F);
        graphicPath.Warp(points, imageRect, matrix, WarpMode.Perspective, 0F);
        hatchBrush = new HatchBrush(HatchStyle.Percent10, Color.Black, Color.SkyBlue);
        captchaGraphics.FillPath(hatchBrush, graphicPath);
        int m = Math.Max(imageRect.Width, imageRect.Height);
        for (int i = 0; i < (int)(imageRect.Width * imageRect.Height / 30F); i++)
        {
            int x = this.random.Next(imageRect.Width);
            int y = this.random.Next(imageRect.Height);
            int w = this.random.Next(m / 50);
            int h = this.random.Next(m / 50);
            captchaGraphics.FillEllipse(hatchBrush, x, y, w, h);
        }
        font.Dispose();
        hatchBrush.Dispose();
        captchaGraphics.Dispose();
        this.captchaImage = captchaBitmap;
    }

    #endregion
}



2.       Add a page and name it as “CaptchaImageGenerator.aspx” and copy below code and paste in “CaptchaImageGenerator.aspx.cs” file.
 using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Imaging;
public partial class CaptchaImageGenerator : System.Web.UI.Page
{
    #region [Events]
   
    protected void Page_Load(object sender, EventArgs e)
    {
        // Create a captcha code and keep it in session.
        this.Session["CaptchaImageText"] = GenerateRandomCaptchaCode();
        // generate Captcha image using the string code stored in the session.
        GenerateRandomCaptchaImage ci = new GenerateRandomCaptchaImage(this.Session
            ["CaptchaImageText"].ToString(), 300, 75);
        // Change the response headers/content type to output a jpg image.
        this.Response.Clear();
        this.Response.ContentType = "image/jpeg";
       
        // send image to the response stream in jpeg format.
        ci.CaptchaImage.Save(this.Response.OutputStream, ImageFormat.Jpeg);
        // Dispose the Captcha image object.
        ci.Dispose();
    }

    #endregion

    /// <summary>
    /// Generate random captcha code string.
    /// </summary>
    /// <returns></returns>

    #region [Methods]
   
    private string GenerateRandomCaptchaCode()
    {
        Random random = new Random();
        string s = "";
        for (int j = 0; j < 5;j++)
        {
            int i = random.Next(3);
            int ch;
            switch (i)
            {
                case 1:
                    ch = random.Next(0, 9);
                    s = s + ch.ToString();
                    break;
                case 2:
                    ch = random.Next(65, 90);
                    s = s + Convert.ToChar(ch).ToString();
                    break;
                case 3:
                    ch = random.Next(97, 122);
                    s = s + Convert.ToChar(ch).ToString();
                    break;
                default:
                    ch = random.Next(97, 122);
                    s = s + Convert.ToChar(ch).ToString();
                    break;
            }
            random.NextDouble();
            random.Next(100, 1999);
        }
        return s;
    }

    #endregion
}

Purpose of each file as created above is explained below.
1.       GenerateRandomCaptchaImage.cs :- This file contains code for captcha image generation. This code creates an image for provided randomly generated code with specified dimensions. “GenerateCaptchaImage” is the method which is responsible to generate desired image. You can modify code to give some variations to generated CAPTCHA image.

2.       CaptchaImageGenerator.aspx : - This file contains code for generation of random code to be appeared in CAPTCHA image. “GenerateRandomCaptchaCode” is the method used to generate random code. You can modify this code to give variation in code generation as per your choice. This page also returns generated CAPTCHA code in the form of image as response stream. So when we need to render CAPTCHA on page, we hust need to call this page to get CAPTCHA code.

Now create another page and name it as “Default.aspx” to render CAPTCHA code on page.
Default.aspx will be used to demo, how to display generated random code in the form of image in simple word how to display CAPTCHA on page and verify valid human submission.

Below is the code snippet which is used to render captcha code on page in image control. Add it in Default.aspx.
HTML Code -
<asp:ScriptManager ID="sm1" runat="server" />
    <div>
        <asp:Label ID="lblmsg" runat="server" Font-Bold="True" ForeColor="Red" Text=""></asp:Label>
        <br />
    </div>
    <asp:TextBox ID="txtimgcode" runat="server"></asp:TextBox>
    <br />
    <asp:UpdatePanel ID="upCaptchaCode" runat="server" UpdateMode="Always">
        <ContentTemplate>
        <asp:Panel ID="pnlCaptcha" runat="server" >
           
        </asp:Panel>
            <asp:Button ID="btnRegenerate" runat="server" Text="Reset" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <br />
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button"/>

C# Code - Add below code in Default.aspx.cs file as created above.

protected void Page_Load(object sender, EventArgs e)
{
        //Clear already added image with captcha code.
        pnlCaptcha.Controls.Clear();

        //Create new image object to add in panel to display Captcha code.
        Image img1 = new Image();

//Create  new GUID string to unique request to generate different captcha code every time.
        string s = Guid.NewGuid().ToString();

//Set image url to content returned from CaptchaImageGenerator page on the  basis of unique request based on unique GUID query string.
        img1.ImageUrl = "~/CaptchaImageGenerator.aspx?p=" + s;

        //Now add created image object in panel on page controls to appear.
        pnlCaptcha.Controls.Add(img1);
}

protected void Button1_Click(object sender, EventArgs e)
{
//Compare entered captcha code with generated captcha code as stored in session when generated.
        if (this.txtimgcode.Text == this.Session["CaptchaImageText"].ToString())
        {
            lblmsg.Text = "Code matched.";
        }
        else
        {
            lblmsg.Text = "code does not match.";
        }
        this.txtimgcode.Text = "";
}

Now, using this simple code as per instructions as above you can create and integrate CAPTCHA code in your application with simplest CAPTCHA code. Now you can explore more and can play with the code to make it more complex to break.

So, enjoy CAPTCHA integration in your sites to verify human being submission to your application pages and avoid any traffic/junk data in your system which can be generated using automated scripts/programs.

See you in the next blog till then enjoy integration.