Monday, July 30, 2012

How to write a professional FTP Web client application?



Here is sample code for a complete web based FTP client application written in C# and Asp.Net:

FtpController class that should be placed in App_Code folder:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Ds17.Ftp
{
    public class FtpController
    {
        /// <summary>
        /// Name of FTP Server
        /// </summary>
        public string ServerName { get; set; }

        /// <summary>
        /// User id of FTP server
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// Authorized FTP server password
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// File path with file name.
        /// </summary>
        public string LocatFilePath { get; set; }

        /// <summary>
        /// Current FTP directory.
        /// </summary>
        public string CurrentFtpPath { get; set; }

        /// <summary>
        /// Name of the files to upload
        /// </summary>
        public string FileName { get; set; }


        /// <summary>
        /// Uploads file to FTP Server
        /// </summary>
        /// <param name="FilePath">Local path with file name</param>
        /// <param name="FtpPath">FTP Path with file name</param>
        /// <returns>Boolean</returns>
        public bool UploadFileByFTP(string LocalFilePath)
        {
            bool success = true;
            try
            {
                //Create FTP request
                if (!ServerName.Contains("ftp://")) ServerName = "ftp://" + ServerName;
                string fileFtpPath = string.Empty;
                if (string.IsNullOrEmpty(CurrentFtpPath))
                {
                    fileFtpPath = ServerName;
                }
                else
                {
                    fileFtpPath = ServerName + "" + CurrentFtpPath + "/" + FileName;
                }
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(fileFtpPath);

                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential(UserName, Password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;

                //Load the file
                FileStream stream = File.OpenRead(LocalFilePath);
                byte[] buffer = new byte[stream.Length];

                stream.Read(buffer, 0, buffer.Length);
                stream.Close();
                stream.Dispose();

                //Upload file
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();
            }
            catch { success = false; }
            return success;
        }

        /// <summary>
        /// Download from FTP server
        /// </summary>
        /// <returns></returns>
        public byte[] DownloadFileFromFTP()
        {
            byte[] retBytes = null;
            try
            {
                //Create FTP request
                if (!ServerName.Contains("ftp://")) ServerName = "ftp://" + ServerName;
                string ftpFilePath = string.Empty;
                if (string.IsNullOrEmpty(CurrentFtpPath))
                {
                    ftpFilePath = ServerName + "/" + FileName;
                }
                else
                {
                    ftpFilePath = ServerName + CurrentFtpPath + "/" + FileName;
                }
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftpFilePath);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(UserName, Password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;

                //FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                //Stream responseStream = response.GetResponseStream();
                //StreamReader reader = new StreamReader(responseStream);
                //retString= (reader..ReadToEnd());

                //Streams
                FtpWebResponse response = request.GetResponse() as FtpWebResponse;
                Stream reader = response.GetResponseStream();

                //Download to memory
                //Note: adjust the streams here to download directly to the hard drive
                MemoryStream memStream = new MemoryStream();
                byte[] buffer = new byte[1024]; //downloads in chuncks

                while (true)
                {
                    //Try to read the data
                    int bytesRead = reader.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        break;
                    }
                    else
                    {
                        //Write the downloaded data
                        memStream.Write(buffer, 0, bytesRead);

                    }
                }

                //Convert the downloaded stream to a byte array
                retBytes = memStream.ToArray();

                //Clean up
                reader.Close();
                memStream.Close();
                response.Close();
            }

            catch { }
            return retBytes;
        }

        /// <summary>
        /// Delete directory from FTP server
        /// </summary>
        /// <param name="DirecotryName"></param>
        /// <returns></returns>
        public bool DeleteDirectoryFromFTP(string DirecotryName)
        {
            bool success = true;
            FtpWebRequest request = null;
            FtpWebResponse response = null;
            try
            {
                //Create FTP request
                if (!ServerName.Contains("ftp://")) ServerName = "ftp://" + ServerName;
                string fileFtpPath = ServerName + "" + CurrentFtpPath + "/" + DirecotryName;

                request = (FtpWebRequest)FtpWebRequest.Create(fileFtpPath);
                request.Method = WebRequestMethods.Ftp.RemoveDirectory;
                request.Credentials = new NetworkCredential(UserName, Password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;

                response = (FtpWebResponse)request.GetResponse();
                response.Close();
            }
            catch { success = false; }
            return success;
        }

        /// <summary>
        /// Delete file from FTP Server
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool DeleteFileFromFTP(string fileName)
        {
            bool success = true;
            FtpWebRequest request = null;
            FtpWebResponse response = null;
            try
            {
                //Create FTP request
                if (!ServerName.Contains("ftp://")) ServerName = "ftp://" + ServerName;
                string fileFtpPath = ServerName + "" + CurrentFtpPath + "/" + fileName;

                request = (FtpWebRequest)FtpWebRequest.Create(fileFtpPath);
                request.Method = WebRequestMethods.Ftp.DeleteFile;
                request.Credentials = new NetworkCredential(UserName, Password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;

                response = (FtpWebResponse)request.GetResponse();
                response.Close();
            }
            catch { success = false; }
            return success;
        }

        /// <summary>
        /// Get Directories and Files under parent filePath
        /// </summary>
        /// <param name="filePath">Parent Directory</param>
        /// <returns>Array of directories</returns>
        public string[] GetFtpDirectories()
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();

            FtpWebRequest request = null;
            FtpWebResponse response = null;
            StreamReader reader = null;
            try
            {
                // Get the object used to communicate with the server.
                if (!ServerName.Contains("ftp://")) ServerName = "ftp://" + ServerName;
                string filePath = string.Empty;
                if (string.IsNullOrEmpty(CurrentFtpPath))
                {
                    filePath = ServerName;
                }
                else
                {
                    filePath = ServerName + "/" + CurrentFtpPath;
                }
                request = (FtpWebRequest)WebRequest.Create(filePath);
                request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;

                request.Credentials = new NetworkCredential(UserName, Password);
                response = (FtpWebResponse)request.GetResponse();

                Stream responseStream = response.GetResponseStream();
                reader = new StreamReader(responseStream);
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                // to remove the trailing '\n'
                result.Remove(result.ToString().LastIndexOf('\n'), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                downloadFiles = null;
                return downloadFiles;
            }
        }

        /// <summary>
        /// Create a directory in FTP Server
        /// </summary>
        /// <param name="filePath">Full path of new directory</param>
        /// <returns>Boolean</returns>
        public bool CreateFtpDirectories(string filePath)
        {
            bool success = false;
            FtpWebRequest request = null;
            FtpWebResponse response = null;
            try
            {
                if (!ServerName.Contains("ftp://")) ServerName = "ftp://" + ServerName;
                string fileFtpPath = string.Empty;
                if (string.IsNullOrEmpty(CurrentFtpPath))
                {
                    fileFtpPath = ServerName;
                }
                else
                {
                    fileFtpPath = ServerName + filePath;
                }

                // Get the object used to communicate with the server.
                request = (FtpWebRequest)WebRequest.Create(fileFtpPath);
                request.Method = WebRequestMethods.Ftp.MakeDirectory;
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;

                request.Credentials = new NetworkCredential(UserName, Password);
                response = (FtpWebResponse)request.GetResponse();
                response.Close();
                success = true;
            }
            catch
            {
                if (response != null)
                {
                    response.Close();
                }
            }
            return success;
        }

        /// <summary>
        /// Finds a string in an array of strings
        /// </summary>
        /// <param name="strArray">Array of string</param>
        /// <param name="strToFind">String to search</param>
        /// <returns>Boolean</returns>
        public bool IsExistsIn(string[] strArray, string strToFind)
        {
            bool exist = false;
            int strIndex = Array.IndexOf(strArray, strToFind);
            if (strIndex >= 0)
            {
                exist = true;
            }
            return exist;
        }

        /// <summary>
        /// Checks whether connected to FTP server
        /// </summary>
        /// <returns>Boolean</returns>
        public bool IsConnected()
        {
            bool success = false;
            FtpWebRequest request = null;
            FtpWebResponse response = null;
            StreamReader reader = null;
            try
            {
                // Get the object used to communicate with the server.
                if (!ServerName.Contains("ftp://")) ServerName = "ftp://" + ServerName;
                request = (FtpWebRequest)WebRequest.Create(ServerName);
                request.Method = WebRequestMethods.Ftp.ListDirectory;
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;

                request.Credentials = new NetworkCredential(UserName, Password);
                response = (FtpWebResponse)request.GetResponse();

                Stream responseStream = response.GetResponseStream();
                reader = new StreamReader(responseStream);
                success = true;
                reader.Close();
                response.Close();
            }
            catch
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                success = false;
            }
            return success;
        }

        public List<Files> GetFiles(string[] directoryDetails)
        {
            string[] files = directoryDetails.Where(s => s.StartsWith("-")).ToArray();
            return (from file in files let fileName = file.Substring(52) let fileSize = Convert.ToInt64(file.Substring(23, 15)) let midifyDate = file.Substring(39, 13) select new Files { FileName = fileName, LastModifiedDate = midifyDate, ImageUrl = string.Empty, ModifiedDate = DateTime.Now, Size = fileSize }).ToList();
        }

        public List<string> GetFolders(string[] directoryDetails)
        {
            return directoryDetails.Where(s => s.StartsWith("d")).ToArray().Select(f => f.Substring(52)).ToList();
        }
    }

    public class Files
    {
        public string FileName { get; set; }
        public Int64 Size { get; set; }
        public DateTime ModifiedDate { get; set; }
        public string LastModifiedDate { get; set; }
        public string ImageUrl { get; set; }
    }
}




Ftp.aspx HTML Code:


<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/FTP.master" AutoEventWireup="true"
    CodeFile="ftp.aspx.cs" Inherits="ftp" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <style type="text/css">
        .setBoarder
        {
            border: 1px solid #CCCCCC;
            border-spacing: 5px;
        }
        .FormLeftSpace
        {
            width: 19%;
            float: left;
            clear: none;
            min-width: 19%;
        }
        .FormLeftColumn
        {
            width: 49%;
            float: left;
            clear: none;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div id="wrapper">
        <div id="main" class='wide'>
            <div id="content">
                <div style="text-align: center; margin: 40px auto 5px auto;">
                </div>
                <div class="page_form">
                    <asp:MultiView runat="server" ID="mvFtp" ActiveViewIndex="0">
                        <asp:View runat="server" ID="vLogin">
                            <div style="margin: 0; padding: 0">
                            </div>
                            <div class="login-box" id="account_signin" style="width: 496px; margin: 0 auto 40px auto;">
                                <div id="sign_in_username_password" style="padding-top: 20px;">
                                    <table style="width: 100%;" align="center" border="0" cellpadding="3" cellspacing="0">
                                        <tr>
                                            <td colspan="2" style="width: 110px; text-align: center;">
                                                <h1>
                                                    Web-Based FTP Client</h1>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="width: 110px; text-align: right;">
                                                Server Name:
                                            </td>
                                            <td style="width: 262px">
                                                <asp:TextBox ID="txtServerName" runat="server" Height="25px" Width="263px"></asp:TextBox><br />
                                                <asp:RequiredFieldValidator ID="rfvServerName" runat="server" ErrorMessage="Server Name is required!"
                                                    ControlToValidate="txtServerName" Display="dynamic" />
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="width: 110px; text-align: right;">
                                                User Name:
                                            </td>
                                            <td style="width: 262px">
                                                <asp:TextBox ID="txtUserName" runat="server" Height="25px" Width="263px"></asp:TextBox><br />
                                                <asp:RequiredFieldValidator ID="rfvUserName" runat="server" ErrorMessage="User Name is required!"
                                                    ControlToValidate="txtUserName" Display="dynamic" />
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="width: 110px; text-align: right; padding-top: 10px;">
                                                Password:
                                            </td>
                                            <td style="width: 262px; text-align: left; padding-top: 10px;">
                                                <asp:TextBox ID="txtPassWord" runat="server" Font-Size="Smaller" Height="25px" TextMode="Password"
                                                    Width="263px"></asp:TextBox><br />
                                                <asp:RequiredFieldValidator ID="rfvPassword" runat="server" ErrorMessage="Password is required!"
                                                    ControlToValidate="txtPassWord" Display="dynamic" />
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="text-align: left; height: 20px;" colspan="2" align="center">
                                                <div class="buttonHolder" style="text-align: center;">
                                                    <asp:Button ID="btnLogIn" runat="server" OnClick="btnLogIn_Click" CausesValidation="true"
                                                        Text="Login" CssClass="primaryAction" Width="110" />
                                                </div>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </asp:View>
                        <asp:View runat="server" ID="vFtpMain">
                            <div id="dvFtp" style="margin: 0; padding: 0">
                                <div style="padding: 10px;" class="setBoarder">
                                    <div class="setBoarder" style="background-color: #F0FFFF">
                                        <b>Current Directory: </b>
                                        <asp:Label runat="server" ID="lblDirectory"></asp:Label>
                                    </div>
                                    <br />
                                    <div>
                                        <table width="100%">
                                            <tr>
                                                <td style="width: 30%; vertical-align: top;">
                                                    <table width="100%">
                                                        <tr>
                                                            <td class="setBoarder" style="background-color: #F0FFFF">
                                                                <b>Folders: </b>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td>
                                                                <asp:Panel runat="server" ID="pnlFolder" ScrollBars="Vertical" Height="300px">
                                                                    <br />
                                                                    <asp:GridView ID="gvFolder" CssClass="setBoarder" runat="server" AutoGenerateColumns="False"
                                                                        EnableModelValidation="True" ShowHeader="False" Width="100%" OnRowDataBound="gvFolder_RowDataBound"
                                                                        OnRowCommand="gvFolder_RowCommand" OnRowEditing="gvFolder_RowEditing" OnRowDeleting="gvFolder_RowDeleting">
                                                                        <Columns>
                                                                            <asp:TemplateField>
                                                                                <ItemTemplate>
                                                                                    <asp:Image ID="imgFolder" runat="server" />
                                                                                </ItemTemplate>
                                                                                <ItemStyle Width="5%" />
                                                                            </asp:TemplateField>
                                                                            <asp:TemplateField ShowHeader="False">
                                                                                <ItemTemplate>
                                                                                    <asp:LinkButton ID="lnkFolderName" runat="server" CausesValidation="False" CommandName="Edit"
                                                                                        Text="Edit"></asp:LinkButton>
                                                                                </ItemTemplate>
                                                                            </asp:TemplateField>
                                                                            <asp:TemplateField ShowHeader="False" Visible="False">
                                                                                <ItemTemplate>
                                                                                    <asp:ImageButton ID="imgDelete" runat="server" CausesValidation="false" CommandName="Delete"
                                                                                        ImageUrl="~/images/cross.png" ImageAlign="Middle" Text="Delete" OnClientClick="return confirm('Are you sure to delete?')" />
                                                                                </ItemTemplate>
                                                                                <ItemStyle Width="5%" />
                                                                            </asp:TemplateField>
                                                                        </Columns>
                                                                    </asp:GridView>
                                                                </asp:Panel>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                                <td style="vertical-align: top;">
                                                    <table width="100%">
                                                        <tr>
                                                            <td class="setBoarder" style="background-color: #F0FFFF">
                                                                <b>Files: </b>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td>
                                                                <asp:Panel runat="server" ID="pnlFile" ScrollBars="Vertical" Height="300px">
                                                                    <asp:GridView ID="gvFile" runat="server" AutoGenerateColumns="False" CssClass="setBoarder"
                                                                        EnableModelValidation="True" ShowHeader="False" Width="100%" OnRowEditing="gvFile_RowEditing"
                                                                        OnRowDataBound="gvFile_RowDataBound" OnRowCommand="gvFile_RowCommand" OnRowDeleting="gvFile_RowDeleting">
                                                                        <Columns>
                                                                            <asp:TemplateField>
                                                                                <ItemTemplate>
                                                                                    <asp:Image ID="imgFile" runat="server" />
                                                                                </ItemTemplate>
                                                                                <ItemStyle Width="2%" />
                                                                            </asp:TemplateField>
                                                                            <asp:TemplateField ShowHeader="False">
                                                                                <ItemTemplate>
                                                                                    <asp:LinkButton ID="lnkFileName" runat="server" CausesValidation="False" CommandName="Edit"
                                                                                        Text="Edit"></asp:LinkButton>
                                                                                </ItemTemplate>
                                                                            </asp:TemplateField>
                                                                            <asp:BoundField DataField="LastModifiedDate">
                                                                                <ItemStyle Width="20%" />
                                                                            </asp:BoundField>
                                                                            <asp:BoundField DataField="Size">
                                                                                <ItemStyle Width="15%" />
                                                                            </asp:BoundField>
                                                                            <asp:TemplateField ShowHeader="False">
                                                                                <ItemTemplate>
                                                                                    <asp:ImageButton ID="imgFileDelete" runat="server" CausesValidation="false" CommandName="Delete"
                                                                                        ImageUrl="~/images/cross.png" ImageAlign="Middle" Text="Delete" OnClientClick="return confirm('Are you sure to delete?')" />
                                                                                </ItemTemplate>
                                                                                <ItemStyle Width="2%" />
                                                                            </asp:TemplateField>
                                                                        </Columns>
                                                                    </asp:GridView>
                                                                </asp:Panel>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div class="setBoarder" style="background-color: #F0FFFF">
                                        <b>Actions: </b>
                                        <br />
                                        <div>
                                            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                                            &nbsp;
                                            <asp:FileUpload ID="fuFtp" runat="server" />
                                        </div>
                                        <div>
                                            <asp:Button ID="btnCreateDirectory" runat="server" Text="Create Directory" OnClick="btnCreateDirectory_Click"
                                                ValidationGroup="Dir" />
                                            <asp:TextBox ID="txtDirectory" runat="server" ValidationGroup="Dir"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="rfvDirectory" runat="server" ErrorMessage="Required"
                                                Display="Dynamic" ControlToValidate="txtDirectory" SetFocusOnError="true" ValidationGroup="Dir"></asp:RequiredFieldValidator>
                                                                                    </div>
                                    </div>
                                </div>
                            </div>
                        </asp:View>
                    </asp:MultiView>
                </div>
            </div>
        </div>
    </div>
</asp:Content>




Ftp.aspx.cs page code:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyNameSpace.UI;
using System.Configuration;

public partial class ftp : System.Web.UI.Page
{
    private const string FTPController = "FtpController";
    string FileUploadLocation = ConfigurationManager.AppSettings["FileUploadLocalPath"];

    private void GetFtpFilesAndFolders(FtpController ftp)
    {
        string[] directories = ftp.GetFtpDirectories();
        List<string> floderList = new List<string>();
        List<Files> files = new List<Files>();
        if (directories != null)
        {
            floderList = ftp.GetFolders(directories);
            floderList.Insert(0, "Go up a level");
            gvFolder.DataSource = floderList;
            gvFolder.DataBind();

            files = ftp.GetFiles(directories);
            gvFile.DataSource = files;
            gvFile.DataBind();
        }
        else
        {
            floderList.Insert(0, "Go up a level");
            gvFolder.DataSource = floderList;
            gvFolder.DataBind();

            gvFile.DataSource = files;
            gvFile.DataBind();
        }
    }

    private void DeleteLocalFile(string filePath)
    {
        System.IO.File.Delete(filePath);
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnLogIn_Click(object sender, EventArgs e)
    {
        string serverName = txtServerName.Text.Trim();
        string userName = txtUserName.Text.Trim();
        string password = txtPassWord.Text.Trim();
        FtpController ftp = new FtpController();
        ftp.ServerName = serverName;
        ftp.UserName = userName;
        ftp.Password = password;
        if (ftp.IsConnected())
        {
            string str = "connected";
            mvFtp.ActiveViewIndex = 1;
            ftp.CurrentFtpPath = "";
            string[] directories = ftp.GetFtpDirectories();

            List<string> floderList = ftp.GetFolders(directories); //directories.ToList();
            floderList.Insert(0, "Go up a level");
            gvFolder.DataSource = floderList;
            gvFolder.DataBind();

            List<Files> files = ftp.GetFiles(directories);
            gvFile.DataSource = files;
            gvFile.DataBind();

            lblDirectory.Text = "/";
            Session[FTPController] = ftp;
        }
    }

    protected void gvFolder_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
        {
            string data = (string)e.Row.DataItem;
            LinkButton lnkFolderName = (LinkButton)e.Row.FindControl("lnkFolderName");
            Image imgFolder = (Image)e.Row.FindControl("imgFolder");
            ImageButton imgDelete = (ImageButton)e.Row.FindControl("imgDelete");

            lnkFolderName.Text = data;
            lnkFolderName.Font.Underline = true;
            lnkFolderName.CommandArgument = data;
            imgDelete.CommandArgument = data;

            if (data == "Go up a level")
            {
                imgFolder.ImageUrl = "~/images/source_browser/Up.gif";
            }
            else
            {
                imgFolder.ImageUrl = "~/images/source_browser/folder.gif";
            }
        }
    }

    protected void gvFolder_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            string data = e.CommandArgument.ToString();
            if (data == "Go up a level")
            {
                //Goto upper level
                //data = data.Substring(data.LastIndexOf('/'));
                FtpController ftp = (FtpController)Session[FTPController];
                if (ftp.CurrentFtpPath.Length > 1)
                {
                    int len = ftp.CurrentFtpPath.LastIndexOf('/');
                    string NewPath = ftp.CurrentFtpPath.Substring(0, len);
                    ftp.CurrentFtpPath = NewPath;
                    GetFtpFilesAndFolders(ftp);
                    lblDirectory.Text = string.IsNullOrEmpty(ftp.CurrentFtpPath) ? "/" : ftp.CurrentFtpPath;
                    Session[FTPController] = ftp;
                }
            }
            else
            {
                //Go into selected folder
                FtpController ftp = (FtpController)Session[FTPController];
                ftp.CurrentFtpPath = ftp.CurrentFtpPath + "/" + data;
                GetFtpFilesAndFolders(ftp);
                lblDirectory.Text = ftp.CurrentFtpPath;
                Session[FTPController] = ftp;

            }
        }
        else if (e.CommandName == "Delete")
        {
            string data = e.CommandArgument.ToString();
            if (!string.IsNullOrEmpty(data))
            {
                FtpController ftp = (FtpController)Session[FTPController];
                bool delete = ftp.DeleteDirectoryFromFTP(data);
                if (delete)
                {
                    GetFtpFilesAndFolders(ftp);
                }
            }
        }
    }

    protected void gvFolder_RowEditing(object sender, GridViewEditEventArgs e)
    {
        // Keep this event
    }
    protected void gvFolder_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        // Keep this event
    }

    protected void gvFile_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            string data = e.CommandArgument.ToString();
            if (!string.IsNullOrEmpty(data))
            {
                FtpController ftp = (FtpController)Session[FTPController];
                ftp.FileName = data;
                byte[] strFile = ftp.DownloadFileFromFTP();
                if (strFile != null)
                {
                    Response.AppendHeader("content-disposition", "attachment; filename=" + data);
                    Response.ContentType = "application/octet-stream";
                    Response.BinaryWrite(strFile);
                    Response.End();
                }
            }
        }
        else if (e.CommandName == "Delete")
        {
            string data = e.CommandArgument.ToString();
            if (!string.IsNullOrEmpty(data))
            {
                FtpController ftp = (FtpController)Session[FTPController];
                bool delete = ftp.DeleteFileFromFTP(data);
                if (delete)
                {
                    GetFtpFilesAndFolders(ftp);
                }
            }
        }
    }
    protected void gvFile_RowEditing(object sender, GridViewEditEventArgs e)
    {
        // Keep this event
    }

    protected void gvFile_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        // Keep this event
    }

    protected void gvFile_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
        {
            Files data = (Files)e.Row.DataItem;
            LinkButton lnkFileName = (LinkButton)e.Row.FindControl("lnkFileName");
            Image imgFile = (Image)e.Row.FindControl("imgFile");
            ImageButton imgFileDelete = (ImageButton)e.Row.FindControl("imgFileDelete");
            lnkFileName.Text = data.FileName;
            lnkFileName.Font.Underline = true;
            lnkFileName.CommandArgument = data.FileName;
            imgFileDelete.CommandArgument = data.FileName;
            imgFile.ImageUrl = "~/images/source_browser/file.gif";
        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (fuFtp.HasFile)
        {
            FtpController ftp = (FtpController)Session[FTPController];
            string lPath = Server.MapPath("Uploads");
            string fileName = fuFtp.PostedFile.FileName;
            fuFtp.SaveAs(lPath + "\\" + fileName);
            fuFtp.Dispose();

            ftp.FileName = fileName;
            ftp.UploadFileByFTP(lPath + "\\" + fileName);
            string[] directories = ftp.GetFtpDirectories();
            List<Files> files = ftp.GetFiles(directories);
            gvFile.DataSource = files;
            gvFile.DataBind();
            try
            {
                DeleteLocalFile(lPath + "\\" + fileName);
            }
            catch
            {
            }
        }
    }

    protected void btnCreateDirectory_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(txtDirectory.Text))
        {
            string NewDirectory = txtDirectory.Text.Trim();
            FtpController ftp = (FtpController)Session[FTPController];
            ftp.CreateFtpDirectories(ftp.CurrentFtpPath + "/" + NewDirectory);
            string[] directories = ftp.GetFtpDirectories();
            if (directories != null)
            {
                List<string> floderList = ftp.GetFolders(directories);
                floderList.Insert(0, "Go up a level");
                gvFolder.DataSource = floderList;
                gvFolder.DataBind();
            }
        }
    }
}






Sunday, July 29, 2012

How can I protect by asp.net button from click multiple time or double click at a time?

Problem:  How can I protect by asp.net button from click multiple time or double click at a time?

Solution:
When clicking in save or insert button a user can click multiple times very quickly that sometimes is similar to double click. If you do not protect users from double click while inserting data, it may insert multiple records at a time which is unexpected.  Asp.net developers frequently face the problem.

To protect from this problem you need to add small java script function.

If you are not using validation group in your page then the function will be:


        <script language="javascript" type="text/javascript">
        var crnt = 0;
        function PreventClicks() {

            if (typeof (Page_ClientValidate) == 'function') {
                Page_ClientValidate();
            }

            if (Page_IsValid) {
                if (++crnt > 1) {
                    alert(crnt);
                    return false;
                }
                return true;
            }
            else {
                return false;
            }
        }
    </script>



<asp:Button runat="server" CssClass="primaryAction" ID="btnInsertUser" OnClick="InsertNewUser" Text="Save" OnClientClick="return PreventClicks();" />


If you use validation group then the function will be:


    <script language="javascript" type="text/javascript">
        var crnt = 0;
        function  PreventClicks() {

            if (typeof (Page_ClientValidate('change-password')) == 'function') {
                Page_ClientValidate();
            }

            if (Page_IsValid) {
                if (++crnt > 1) {
                    alert(crnt);
                    return false;
                }
                return true;
            }
            else {
                return false;
            }
        }
    </script>


<asp:Button runat="server" CssClass="primaryAction" ID="btnInsertUser" 

ValidationGroup="change-password"

OnClick="InsertNewUser" Text="Save" dd OnClientClick="return PreventClicks();" />


Hope that it will be helpful for developers.

Thursday, July 19, 2012

How to create session enabled web service?

Problem: How to enable session in web service?

Solution:  By default, ASP.NET session support for each Web method is turned off. You need to add EnableSession=true property for the WebMethod attribute.


For example look at the following code snippet:



WebMethod(EnableSession=true)]
    public static int SessionCounter()
    {
        int counter=0;
        counter=Convert.ToInt32(Session["Counter"]);
        counter++;
        return counter;
    }

You need to confirm that session state is enabled in web config file.

Monday, June 18, 2012

Introduction to Socket Class in .Net

The .NET Framework provides a Socket class that is a wrapper around the WinSock implementation. Since TcpClient, TcpListener, and UdpClient all utilize the Socket class for their own implementations, Socket contains all the functionality of those classes, plus much more. The Socket interface is a generic API that actually covers more than just IP. Here we introduce its usage for TCP and UDP and walk through some common cases where you might use it.

TCP Client with Socket
For a TCP client to use the Socket class, it will perform the following steps:
1. Call the Socket constructor: The constructor specifies the address type, socket
type, and protocol type.
2. Call the Socket Connect() method: Connect() takes an IPEndPoint argument that
represents the server to connect to.
3. Send and receive data: Using the Socket Send() and Receive() calls.
4. Close the socket: Using the Socket Close() method.

Here we present a version of the TcpEchoClient.cs program that uses the Socket
class instead of the TcpClient class.
TcpEchoClientSocket.cs
 using System; // For String, Int32, Console, ArgumentException
 using System.Text; // For Encoding
 using System.IO; // For IOException
 using System.Net.Sockets; // For Socket, SocketException
 using System.Net; // For IPAddress, IPEndPoint

 class TcpEchoClientSocket {

 static void Main(string[] args) {

 if ((args.Length < 2) || (args.Length > 3)) { // Test for correct # of args
 throw new ArgumentException("Parameters: []");
 }

 String server = args[0]; // Server name or IP address
 // Convert input String to bytes
 byte[] byteBuffer = Encoding.ASCII.GetBytes(args[1]);

 // Use port argument if supplied, otherwise default to 7
 int servPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7;

 Socket sock = null;

 try {
 // Create a TCP socket instance
 sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
 ProtocolType.Tcp);

 // Creates server IPEndPoint instance. We assume Resolve returns
 // at least one address
 IPEndPoint serverEndPoint = new IPEndPoint(Dns.Resolve(server).AddressList[0],
 servPort);
 // Connect the socket to server on specified port
 sock.Connect(serverEndPoint);
 Console.WriteLine("Connected to server... sending echo string");

 // Send the encoded string to the server
 sock.Send(byteBuffer, 0, byteBuffer.Length, SocketFlags.None);

 Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);

 int totalBytesRcvd = 0; // Total bytes received so far
 int bytesRcvd = 0; // Bytes received in last read

 // Receive the same string back from the server
 while (totalBytesRcvd < byteBuffer.Length) {
 if ((bytesRcvd = sock.Receive(byteBuffer, totalBytesRcvd,
 byteBuffer.Length - totalBytesRcvd, SocketFlags.None)) == 0) {
 Console.WriteLine("Connection closed prematurely.");
 break;
 }
 totalBytesRcvd += bytesRcvd;
 }

 Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,
 Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));

 } catch (Exception e) {
 Console.WriteLine(e.Message);
 } finally {
 sock.Close();
 }
}
 }

Barcode scanner USB pen reader application in asp.net application

Problem: I have a USB barcode scanner pen. Is there any tutorial or project that I can use to test the pen in asp.net application?

Solution:

In a windows application that is not difficult, it can be done by accessing the Windows.Devices.Input namespace, and then creating a global hook so when a specific input device other than the mouse and keyboard is in use, it will auto return focus to the windows application, and the proper text box.

You won't be able to do that in asp.net though.

Monday, February 20, 2012

How to solve this configuration error while deploying application?

Problem:
I am getting a server error while setting up BugTracker.Net in my local machine.


How can I solve this issue?

 Solution:
This error gives when required .net  framework is not installed on your machine.
To install .net framework go to visual studio 2010  command prompt and write the following command:

aspnet_regiis -i

This will install .net framwork 4 on your machine.


Sunday, February 5, 2012

An alternative to cursor

While working with database we often require to use Cursor. Cursors force the database engine to repeatedly fetch rows. This may slow down your database and locking may occur. As a result cursor are not suggested to use if not extremely necessary.

If there is a primary key on a table, you can usually write a WHILE loop to do the same work without incurring the overhead of a cursor. The following example demonstrate the idea:

Declare @ItemId bigint

Declare @OldItemCode varchar(50)

      SELECT Top 1   @ItemId= ItemId, @OldItemCode=OldItemCode
      FROM         InvItem
      WHERE      (IsStockItem = 'true')

      WHILE @ItemId is not null
      BEGIN
            print 'Item: '+convert(varchar(10),@ItemId)+' - '+convert(varchar(50),@OldItemCode)
            if exists (select ItemId from InvItem where IsStockItem=1 and ItemId>@ItemId)
                  begin
                        SELECT Top 1    @ItemId=ItemId, @OldItemCode=OldItemCode
                        FROM         InvItem
                        WHERE      (IsStockItem = 'true') and ItemId>@ItemId
                  end
                  else
                  begin
                        set @ItemId=null
                  end
      END

Monday, January 30, 2012

How to write data to a CSV file?


The article shows the work of parsing the rows from the dataset into a file stream using a comma delimiter. By loading the data into a dataset, you have access to metadata for the columns. You can retrieve the column name from the metadata when building the row headers for your export file. If the Overwrite parameter is true, then the file will be recreated: otherwise, the data will be appended to the existing file.

public static void CreateCSVFile(DataSet myDs,String FullFilePath, Boolean Overwrite)
{
int i = 0;
int fldCnt = 0;
StreamWriter sw = new StreamWriter(FullFilePath, Overwrite);
fldCnt = myDs.Tables[0].Columns.Count;
//Gather and create csv line for columns
for (int x = 0; x <= fldCnt - 1; x++)
{
sw.Write(“[“ + myDs.Tables[0].Columns[x].ColumnName + “]”);
if (x < fldCnt - 1)
sw.Write(“,”);
}
sw.Write(sw.NewLine);
//Then gather row information into an HTML string
for (int x = 0; x <= myDs.Tables[“TABLE”].Rows.Count - 1; x++)
{
while (i < fldCnt)
{
if (!Convert.IsDBNull(myDs.Tables[“TABLE”].Rows[x][i]))
{
sw.Write(Convert.ToString(myDs.Tables[“TABLE”].Rows[x][i]));
}
if (i < fldCnt - 1)
sw.Write(“,”);
i++;
}
i = 0;
sw.Write(sw.NewLine);
}
sw.Close();
}