Tuesday, September 18, 2012

How to solve error: 404.2 The page you are requesting cannot be served

Problem: 
I get the error while trying to visit home page of a deployed asp.net 4 application in IIS7: 404.2 The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

How can I solve this issue?

 Solution:
This error occurs because the requested ISAP(Internet Server API) and/or CGI(Common Gateway Interface) resource is restricted on the computer that is running IIS 7. After installing .NET Framework 4.0 on a machine there is a few configuration changes you need to do to IIS in order to get a ASP.NET 4.0 page running.

To resolve this issue you have to follow steps mentioned below:

1. Open IIS and Click on the sever name.
2. In Feature View Double click "ISAPI and CGI Restrictions"

3. Select ASP.Net V4 and click Allow in action panel. It will be set to Allowed.

Now your application should run.


Tuesday, September 4, 2012

How to call server side a direct method from ext.net gridpanel?


In ext.net you can call server side direct method from your client side code. This is an excellent way to doing jobs on server side from client side java script function and grid panel, button or other controls. Here we will see how we can do this job done in a grid panel.
In the following code snippet will call a direct method against an action in a grid panel action column. Also we will pass some arguments from our grid to direct method that we require for data manipulation on server side.
Let see code for grid panel:
<ext:GridPanel ID="gpList" runat="server" StripeRows="true" Title="BO List" AutoExpandColumn="name"
                                    Collapsible="true" AnchorHorizontal="100%" Height="350">
                                    <Store>
                                        <ext:Store ID="gpListStore" runat="server" OnRefreshData="gpListStore_RefreshData"
                                            OnSubmitData="gpListStore_SubmitData">
                                            <Reader>
                                                <ext:JsonReader IDProperty="cno">
                                                    <Fields>
                                                        <ext:RecordField Name="dividendyear" />
                                                        <ext:RecordField Name="declareid" />
                                                        <ext:RecordField Name="wno" />
                                                        <ext:RecordField Name="name" />
                                                        <ext:RecordField Name="boid" />
                                                        <ext:RecordField Name="shares" />
                                                        <ext:RecordField Name="dividendM" />
                                                        <ext:RecordField Name="taxrate" />
                                                        <ext:RecordField Name="taxamt" />
                                                        <ext:RecordField Name="netamt" />
                                                        <ext:RecordField Name="actionid" />
                                                        <ext:RecordField Name="status" />
                                                    </Fields>
                                                </ext:JsonReader>
                                            </Reader>
                                        </ext:Store>
                                    </Store>
                                    <ColumnModel ID="ColumnModel1" runat="server">
                                        <Columns>
                                            <ext:RowNumbererColumn />
                                            <ext:Column ColumnID="cdeclareid" Header="Declare Id" DataIndex="declareid" Width="70" />
                                            <ext:Column ColumnID="cdividendyear" Header="Year" DataIndex="dividendyear" Width="50">
                                            </ext:Column>
                                            <ext:Column ColumnID="cBoid" Header="Boid" DataIndex="boid" Width="130" />
                                            <ext:Column ColumnID="cname" Header="Name" DataIndex="name" />
                                            <ext:Column ColumnID="cshares" Header="Shares" DataIndex="shares" Width="50" />
                                            <ext:Column ColumnID="cdividendM" Header="Dividend" DataIndex="dividendM" Width="50" />
                                            <ext:Column ColumnID="ctaxrate" Header="Tax Rate" DataIndex="taxrate" Width="50" />
                                            <ext:Column ColumnID="ctaxamt" Header="Tax Amt" DataIndex="taxamt" Width="50" />
                                            <ext:Column ColumnID="cnetamt" Header="Net Amt" DataIndex="netamt" Width="50" />
                                            <ext:Column ColumnID="cStatus" Header="Status" DataIndex="status" />
                                            <ext:CommandColumn Header="Action" Width="90">
                                                <Commands>
                                                    <ext:GridCommand Icon="ApplicationViewDetail" CommandName="ViewDetail">
                                                        <ToolTip Text="View Detail" />
                                                    </ext:GridCommand>
                                                    <ext:CommandSeparator />
                                                    <ext:GridCommand Icon="AsteriskRed" CommandName="Action">
                                                        <ToolTip Text="Action" />
                                                    </ext:GridCommand>
                                                    <ext:CommandSeparator />
                                                    <ext:GridCommand Icon="Connect" CommandName="Communication">
                                                        <ToolTip Text="Communication with people." />
                                                    </ext:GridCommand>
                                                </Commands>
                                            </ext:CommandColumn>
                                        </Columns>
                                    </ColumnModel>
                                    <SelectionModel>
                                        <ext:CheckboxSelectionModel ID="CheckboxSelectionModel1" runat="server" />
                                    </SelectionModel>
                                    <BottomBar>
                                        <ext:PagingToolbar ID="PagingToolBar1" runat="server" PageSize="10" />
                                    </BottomBar>
                                    <Listeners>
                                        <Command Handler="Ext.net.DirectMethods.ExecuteActionCommand(command, record.data.wno, record.data.declareid, record.data.boid);" />
                                    </Listeners>
                                    <DirectEvents>
                                        <AfterEdit OnEvent="gpList_AfterEdit">
                                            <EventMask ShowMask="true" Target="This" />
                                            <ExtraParams>
                                                <ext:Parameter Name="field" Value="e.field" Mode="Raw" />
                                                <ext:Parameter Name="id" Value="e.record.id" Mode="Raw" />
                                                <ext:Parameter Name="record" Value="e.record.data" Mode="Raw" Encode="true" />
                                            </ExtraParams>
                                        </AfterEdit>
                                    </DirectEvents>
                                </ext:GridPanel>


Direct method is called using listener in ext.net which always woks at client side.
<Listeners>
          <Command Handler="Ext.net.DirectMethods.ExecuteActionCommand(command, record.data.wno, record.data.declareid, record.data.boid);" />
</Listeners>


Here in Action column we have three action commands:
1.  ViewDetail
2.  Action
3.  Communication
These commands will pass to parameter command and on server side we will decide which action actually performed. Server side code is here:

[DirectMethod]
    public void ExecuteActionCommand(string command, string wno,  string declareid, string boid)
    {
        if (command == "ViewDetail")
        {
            //Display bo holder detail info
            var win = new Window
            {
                ID = "BOWindow",
                Title = "Bo Detail",
                Width = Unit.Pixel(800),
                Height = Unit.Pixel(380),
                Modal = true,
                Collapsible = true,
                Maximizable = false,
                Hidden = false,

            };

            win.AutoLoad.Url = "~/BoMasterDetails.aspx?boid=" + boid + "&declareid=" + declareid;
            win.AutoLoad.Mode = LoadMode.IFrame;

            win.Render(this.Form); win.Dispose();
        }
        else if (command == "Action")
        {
            var win = new Window
            {
                ID = "ActionWindow",
                Title = "Corporate Action",
                Width = Unit.Pixel(800),
                Height = Unit.Pixel(550),
                Modal = true,
                Collapsible = true,
                Maximizable = false,
                Hidden = false,

            };

            win.AutoLoad.Url = "~/ActionLogEntryPopup.aspx?wno=" + wno + "&boid=" + boid + "&declareid=" + declareid;
            win.AutoLoad.Mode = LoadMode.IFrame;

            win.Render(this.Form); win.Dispose();
        }
        else if (command == "Communication")
        {
            dividend div = new dividendBLL().dividend_GetAll_By_wno(wno).FirstOrDefault();
            var win = new Window
            {
                ID = "CommWindow",
                Title = "Communication",
                Width = Unit.Pixel(800),
                Height = Unit.Pixel(550),
                Modal = true,
                Collapsible = true,
                Maximizable = false,
                Hidden = false,

            };

            win.AutoLoad.Url = "~/CommunicationLogEntryPopup.aspx?wno=" + wno + "&boid=" + boid + "&declareid=" + declareid;
            win.AutoLoad.Mode = LoadMode.IFrame;

            win.Render(this.Form); win.Dispose();
        }
    }

How to display a popup dynamically in ext.net?


Here I will show you quick tips on how you can create a dynamic popup control in your ext.net application.
Look at the following server side ext.net code snippet:
            var win = new Window
            {
                ID = "CommWindow",
                Title = "Communication",
                Width = Unit.Pixel(800),
                Height = Unit.Pixel(550),
                Modal = true,
                Collapsible = true,
                Maximizable = false,
                Hidden = false,

            };

            win.AutoLoad.Url = "~/CommunicationLogEntryPopup.aspx?wno=" + wno + "&boid=" + boid + "&declareid=" + declareid;
            win.AutoLoad.Mode = LoadMode.IFrame;

            win.Render(this.Form); win.Dispose();

First create a window and define all its properties and load your page into the window and IFrame.
Hope this will help you guys. 

Sunday, August 5, 2012

How to convert a file to byte array and create file from byte array?

Problem:
How to convert a file to byte array? and how can I create the file from byte array?

Solution:

To convert a file to byte array you need to used FileStream class. You have to open instance of the class in read mode and class Read() method to read bytes in byte array.

To retrieve the file from byte array you have to open the instance of the class in create mode with write access and call Write() method to write bytes and create file.

Look at following code example:


string sessionId = Session.SessionID;
        imgDocImage.ImageUrl = string.Empty;
        string fileName = hdfImagePath.Value.ToString();
        string docDtlId = hfDoctDtlId.Value.ToString();
        string tempPath = Server.MapPath("~/Uploads");
        tempPath = tempPath + "\\" + sessionId + "\\" + fileName;
        string newPath = Server.MapPath("~/Uploads");
        newPath = newPath + "\\" + docDtlId;
        if (!System.IO.Directory.Exists(newPath))
        {
            System.IO.Directory.CreateDirectory(newPath);
        }
        newPath = newPath + "\\" + fileName;
        int id = 0;
        if (!System.IO.File.Exists(newPath))
        {
            FileStream fsr = new FileStream(tempPath, FileMode.Open, FileAccess.Read);
            int bytesInFile = (int)fsr.Length;
            byte[] fileContent = new byte[bytesInFile];
            long bytesRead = fsr.Read(fileContent, 0, bytesInFile);
            fsr.Close();

            FileStream fs = new FileStream(newPath, FileMode.Create, FileAccess.Write);
            fs.Write(fileContent, 0, fileContent.Length);
            fs.Close();
        }

Monday, July 30, 2012

My Open source FTP client project


Dev Studio 17 Web-Based FTP Client is now on codeplex.com and is open for learners and professionals and free for commercial use also. This is a complete web base ftp client application that will help in your work.

Project Description
Dev Studio 17 Web-Based FTP Client is a web based ftp application built using asp.net, c#.

Features:
  • Upload files to FTP Server
  • Downloads files from FTP Server
  • Create Directory
  • Remove Directory
  • Delete files
  • Traverse back to upper directory
 To download the application please visit: http://ds17ftp.codeplex.com/

Thanks

How can I save record using jQuery in ASP.Net?

Problem: How can I save record using jQuery in ASP.Net? Please provide me source code for save record using jquery in asp.net.

Solution:

You need to create a web service and add a web method for saving record and call the method from jquery.
Look at the following example:
You need to add a method in your web service which is marked with WebMethod attribute. Similar to following code snipppet:


[WebMethod]
        public bool MarkProjectComplete(long projectID)
        {
            bool result = false;
            EnumStatus status = ProjectFacade.MarkProjectComplete(projectID);
            if (status == EnumStatus.Successfull)
            {
                result = true;
                if (projectID > 0)
                {
                    Project project = null;
                    project = ProjectFacade.GetProjectByID(projectID);
                }
            }
            return result;
        }
 

Then call your method from your jquery function. Look at following code snippet:

function MarkProjectComplete(projectID) {
            if (confirm('Are you sure you would like to mark this project as ‘Mark Project Complete’?')) {
                $.ajax({
                    type: "POST",
                    url: "<%= ApplicationPath %>/WebServices/YourWebService.asmx/MarkProjectComplete",
                    data: "{'projectID' : '" + projectID + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        if (msg.d == true) {
                            alert("Mark Project Complete Successfully");
                            
                        }
                    },
                    error: function () {
                    }
                });
            }
        }

Hope it will be helpful. Thanks.


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();
            }
        }
    }
}