Selecting and Sorting in DataTable – ASP.net C#

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags with Leave a comment on Selecting and Sorting in DataTable – ASP.net C#

Demonstrates that how to select and sort the Datatable in ASP.Net , C#

DataTable in C# have very reach features to store the data in Tabular forms and also to display sorted or selected data on predefined category. Below i have provided the source code which demonstrates that how to select and sort the Datatable in ASP.Net.

Sorting and Selecting DataTable in ASP

below is the snap of C# File:

 public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = prepareTable();
            GridView1.DataSource = dt;
            GridView1.DataBind();

            dt.DefaultView.Sort = "DOB ASC";
            GridView2.DataSource = dt;
            GridView2.DataBind();

            dt.DefaultView.Sort = "Age DESC";
            GridView3.DataSource = dt;
            GridView3.DataBind();

            dt.DefaultView.Sort = "Id DESC, Age ASC";
            GridView4.DataSource = dt;
            GridView4.DataBind();

            DataRow[] dtRows = dt.Select("Age > 20", "Age ASC");
            DataTable dt1 = new DataTable();
            dt1.Columns.Add("Id", typeof(int));
            dt1.Columns.Add("Name", typeof(string));
            dt1.Columns.Add("Age", typeof(int));
            dt1.Columns.Add("DOB", typeof(DateTime));

            foreach (DataRow dr in dtRows)
            {
                dt1.Rows.Add(dr[0], dr[1], dr[2],dr[3]);
            }

            GridView5.DataSource = dt1;
            GridView5.DataBind();
        }

        /// <summary>
        /// Prepares the table for Data.
        /// </summary>
        /// <returns></returns>
        private DataTable prepareTable()
        {
            DataTable rs = new DataTable();
            rs.Columns.Add("Id", typeof(int));
            rs.Columns.Add("Name", typeof(string));
            rs.Columns.Add("Age", typeof(int));
            rs.Columns.Add("DOB", typeof(DateTime));

            AddItems(rs,1,"Tuiya",24,DateTime.Now.AddYears(-20));
            AddItems(rs, 2, "Sonu", 20, DateTime.Now.AddYears(-21));
            AddItems(rs, 4, "Rohan", 19, DateTime.Now.AddYears(-22));
            AddItems(rs, 4, "Manoranjan", 27, DateTime.Now.AddYears(-23));
            AddItems(rs, 1, "Santosh", 24, DateTime.Now.AddYears(-20));

            return rs;
        }

        /// <summary>
        /// Adds the items.
        /// </summary>
        /// <param name="rs">The DataTable.</param>
        /// <param name="id">The id.</param>
        /// <param name="name">The name.</param>
        /// <param name="age">The age.</param>
        /// <param name="dob">The dob.</param>
        private static void AddItems(DataTable rs,int id,string name,int age,DateTime dob)
        {
            DataRow dtRow = rs.NewRow();
            dtRow[0] = id;
            dtRow[1] = name;
            dtRow[2] = age;
            dtRow[3] = dob;
            rs.Rows.Add(dtRow);
        }
    }

Working Demo of DataTable

Telerik RadSchedular Tips and Tricks

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags with Leave a comment on Telerik RadSchedular Tips and Tricks

Change the style of the Today Cell in Month View and Bind Extra Column / Add Argument in RadSchedular

Change the style of the Today Cell in Month View

Lots of time, we are in need in telerik control that todays date should be highlighted. There is no need in case of Day View and in Week View.  But in month view, most of the times we confused between any event and todays date. So below is few CSS hacks which can be used in Telerik Controls.

div.RadScheduler_#skinName# .rsMonthView
.rsTodayCell
{
background-color: #CCFF00;
color: #000;
border: 1px solid #000;
}

Example:

div.RadScheduler_Office2007 .rsMonthView .rsTodayCell
{
background-color: #FFEFB8;
color: #000;
border: 2px solid #EE9311;
}

Bind Extra Column / Add Argument in RadSchedular

Add Custom Column as follow on page load event

RadSchedulerEvent.CustomAttributeNames = new string[] { "OwnerId" };

Note: OwnerId column name must be available in DataTable

Get Value of custom Column on AppointmentCreated Event

String ownerId = e.Appointment.Attributes["OwnerId"];

Opening RadWindow from another RadWindow – Telerik Control

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags with Leave a comment on Opening RadWindow from another RadWindow – Telerik Control

Opening RadWindow from another RadWindow:

Telerik Control in ASP.NET
Telerik Control in ASP.NET

Sometime it may require opening the radwindow from another radwindow. But believe me; it will not be easy.Problems I faced were:

  • New window opened behind the parent radwindow.
  • New window open in area of parent window only. So we cannot resize the window as per required.
    To overcome all these properties:

Create a java script function which will open the RadWindow in parent page. We will call this function from Radwindow to open new Radwindow so that new window should have complete screen as a width and height.

function OpenParentWnd()
{
var oWnd = $find("<%=Parent.ClientID %>");//Parent is radwindow ID name
oWnd.show();
}

In current RadWindow, call the above function like this:

function CreateWindowInParent()
{
//One way to open a window from parent page
var oBrowserWnd = GetRadWindow().BrowserWindow;
oBrowserWnd.OpenParentWnd();
}

Background and foreground thread in c#

Author posted by Jitendra on Posted on under category Categories c# and tagged as Tags with 1 Comment on Background and foreground thread in c#

Example of Threading in C#. Includes Foreground and Background Threading.

  • Foreground threads have the ability to prevent the current application from terminating. The CLR will not shut down an application (which is to say, unload the hosting AppDomain) until all foreground threads have ended.
  • Background threads (sometimes called daemon threads) are viewed by the CLR as expendable paths of execution that can be ignored at any point in time (even if they are currently laboring over some unit of work). Thus, if all foreground threads have terminated, any and all background threads are automatically killed when the application domain unloads.
  • It is important to note that foreground and background threads are not synonymous with primary and worker threads. By default, every thread you create via the Thread.Start() method is automatically a foreground thread. Again, this means that the AppDomain will not unload until all threads of execution have completed their units of work. In most cases, this is exactly the behavior you require.

    Example:

    Thread Foreground Background
    Threading in CSharp
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    namespace TestThread
    {
    class Program
    {
    static void Main(string[] args)
    {
    Program obj = new Program();
    obj.printInfo();
    //Create object of parameterized thread, so that you can pass parameter to any thread
    ParameterizedThreadStart pst = new ParameterizedThreadStart(obj.function1);
    //Bydefault threads are Foreground Thread
    Thread t1 = new Thread(pst);
    //Set Thread Name
    t1.Name = "Thread1";
    //Passs Parameter to thread
    t1.Start(true);
    //Create object of ThreadStart, it does not have any parameter
    ThreadStart ts = new ThreadStart(obj.function2);
    Thread t2 = new Thread(ts);
    t2.Name = "Thread2";
    //Make it Background Thread
    t2.IsBackground = true;
    //Run the thread
    t2.Start();
    Console.ReadKey();
    }
    public void function1(object val)
    {
    for (int i = 0; i < 5; i++)
    {
    Console.WriteLine("This is parameterized function1 by {0} and Value passed is {1} ", Thread.CurrentThread.Name, val);
    }
    }
    public void function2()
    {
    for (int i = 0; i < 5; i++)
    {
    Console.WriteLine("This is function2 by : " + Thread.CurrentThread.Name);
    }
    }
    public void printInfo()
    {
    System.Text.StringBuilder sb = new StringBuilder();
    sb.Append("*******************************************************n");
    sb.Append("            read Demo by ShivaSoft                     n");
    sb.Append("*******************************************************n");
    System.Console.WriteLine(sb);
    }
    }
    }
    
    

    Tracing ASP.NET Website

    Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , , with 1 Comment on Tracing ASP.NET Website

    Demonstrates that how to Trace ASP.NET web applications

    In ASP.NET there two types of Tracing

    • Application Level
    • Page Level

    Page level Tracing takes the precedence over the Application Level tracing.

    Lets start with creating new website.

    In web.config add following entries to enable Application level tracing below System.web element.

    <system.web>
    <trace
    pageOutput="true"
    enabled="true"
    requestLimit="10"
    localOnly="false"
    mostRecent="true"
    traceMode="SortByTime"
    />
    </system.web>
    

    where:

    pageOutput=”true” – add the tracing information at the bottom of the ASPX page.

    localOnly=”false” – tracing will be available to any web page.

    requestLimit=”10″ – How many request should be saved on the server.

    mostRecent=”true” – whether or not display the recent tracing information if the request reach at the limit.

    After adding above tag in web.config, the output of ASP.NET page will look like:

    ASP.NET Tracing Output

    Here you can see much of informations displayed like SessionId, Request Status, Controls available on that page,  All the events of the page with start and end time etc and thus you can figure out the performance of your web application.

    No Trace for a particular Page

    Create a web page and in aspx file and at header write the tag Trace=”false”

    Create few controls like link button and view the page in browser. You will see that the page is displayed with no tracing information, although its turned ON in web.config but page level tracing has the precedence over application level tracing.

    Writing Custom Trace Information

    Now on the click event of Link buttons write the custom trace information.

    protected void lblwriteMessage_Click(object sender, EventArgs e)
    {
    	Trace.Write("Custome Message", "Write Link Button clicked");
    }
    protected void lblwarnMessage_Click(object sender, EventArgs e)
    {
    	Trace.Warn("Custome Message", "Warn Link Button clicked");
    }
    

    when you will click on the WriteLink button, below output will be seen.

    ASP.NET Trace
    ASP.NET Trace

    and when you will click on warn button, the message will be displayed in Red color. so it is suggested to display the the important trace message as a warn.

    ASP.NET Trace
    ASP.NET Trace

    Page.Trace Vs System.Diagnostics.Trace

    Create a new class file and write a static function which will write the Trace Message. You will notice that Trace object is not available by default like ASPX page instead you will need to import the package “System.Diagnostics”.

    So, there is lot difference in System.Diagnostic.Trace and Page.Trace.

    Trace from Diagnostics display the trace information in output window of Visual studio whereas the Trace from page displays the Trace information in ASPX Page.

    Integrate System.Diagnostics with ASPX Page (Routing all Trace information to web page)

    We will need to add the listener in web.config file to route all the tracing information to the single web page.

    To integrate the System.Diagnostics Trace with ASPX page, write below line of code in web.config.

    <system.diagnostics>
      <trace>
        <listeners>
           <add name="WebPageTraceListener"
                type="System.Web.WebPageTraceListener, System.Web, Version=2.0.3600.0, Culture=neutral,
    PublicKeyToken=b03f5f7f11d50a3a"/>
        </listeners>
      </trace>
    </system.diagnostics>
    

    The output will look like below image:
    ASP.NET Tracing Application Level
    trace.axd file

    This file contains all the information about the tracing of the application.

    To view the trace information just write the file name and you will get page which will look like below snap.

    path structure : http://<servername>/webapp/trace.axd

    Application Trace in ASP.NET
    Application Trace in ASP.NET

    Creating Custom Trace Listeners

    Database trace listener

    .NET has provided us the flexibility of writing our own Trace Listeners in the form of the TraceListener class. Every Trace Listener is inherited from this class; therefore, in order to implement your own Trace Listener, you must inherit your Trace Listener class from this class.

    TraceListener class has many virtual and abstract methods; at the very least, each inheritor of this class must implement the Write and WriteLine methods; other important methods are Fail, Close, and Flush. Inheritors are not supposed to implement these methods but it is a good idea to implement these methods. Descriptions of these methods are given in the beginning of the article.

    Method Name Result
    Fail Outputs the specified text with the Call Stack.
    Write Outputs the specified text.
    WriteLine Outputs the specified text and a carriage return.
    Flush Flushes the output buffer to the target media.
    Close Closes the output stream in order to not receive the tracing/debugging output.

    Write and WriteLine methods are overloaded; following is a list of all the overloaded version of the Write method:

    • public override void Write(string message)
    • public override void Write(object o)
    • public override void Write(string message, string category)
    • public override void Write(object o, string category)

    For this article, I have created a Trace Listener, DatabaseTraceListener, which actually stores trace and debug messages into a database.

    add below code in Web.config which stores the connection string information.

    <appSettings></pre>
    <pre><add key="ConnectionString" value="Data Source=.SQLExpress;Integrated Security=True;User Instance=True;
    AttachDBFilename=|DataDirectory|TraceDB.mdf" /></pre>
    <pre><add key="MaximumRequests" value="2" /></pre>
    <pre></appSettings>
    

    The structure of Table is:

  • TraceDateTime column stores the date and time of the trace message
  • TraceCategory column stores the actual category of the trace message
  • TraceDescription column stores the trace message
  • StackTrace column contains the stack trace
  • DetailedErrorDescription column contains the detailed error message which will be passed in second parameter of the Fail method.
  • create below stored procedure in SQLExpress

    Stored Procedure ASP.NET Tracing
    Now create a class named “DatabaseTraceListener” which inherit the abstract class “TraceListener”. You can check the code snippets in Source code of this article.

    if you want to implement your own Trace Listener, simply derive your listener class from TraceListener class, implement at least the Write and WriteLine methods and you are done.
    In our Example, Flush and Close methods simply save all the cached messages into the database.

    Saving Trace information in File

    We can also save the trace information in log files.

    To save the trace information in File, simply add the following entry in web.config

    <add name="myListener"
    type="System.Diagnostics.TextWriterTraceListener"
    initializeData="TextWriterOutput.log" />
    

    DataGrid Sorting and Paging Example – Part 2

    Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with Leave a comment on DataGrid Sorting and Paging Example – Part 2

    For Part 1, visit This URL https://jitendrazaa.com/blog/?p=191

    In this part, i will show that how to Sort the Datagrid Component of ASP.NET.

    To sort Datagrid, we will need DataView and then assign Dataview as datasource to our Grid control.

    We will need to change our code of Part 1.

    Previously, we used DataSet as a Datasource. This time we will use DataTable and get the DataView from DataTable using below line.

    DataView dv = dt.DefaultView; //Where dt id DataTable
    

    So we have created a function, which will return the DataTable as shown below:

    private DataTable GetTableFromDataBase()
    {
    SqlConnection con = null;
    SqlDataAdapter adp = null;
    DataTable dt = new DataTable();
    try
    {
    con = new SqlConnection(conString);
    con.Open();
    adp = new SqlDataAdapter("Select * from Employee",con);
    adp.Fill(dt);
    return dt;
    }
    catch (CustomException ex)
    {
    ex.logException();
    }finally{
    con.Close();
    }
    return null;
    }
    

    we will need to create the function on Sortcommand of the DataGrid.

    The format for sorting the grid is like:

    SortExpression+”asc”

    OR

    SortExpression+”desc”

    Below is the code snap used for the sorting:

    protected void grdEmp_Sort(object source, DataGridSortCommandEventArgs e)
    {
    DataTable dt = GetTableFromDataBase();
    DataView dv = dt.DefaultView;
    string dir = string.Empty;
    if (e.SortExpression.Length > 0)
    {
    if (Session["OldSortDir"] == null)
    {
    Session["OldSortDir"] = e.SortExpression;
    }
    else
    {
    string oldSortExp = Session["OldSortDir"].ToString();
    if (oldSortExp == "asc")
    {
    dir = "desc";
    Session["OldSortDir"] = "desc";
    }
    else
    {
    dir = "asc";
    Session["OldSortDir"] = "asc";
    }
    }
    dv.Sort = e.SortExpression+"  "+dir;
    }
    grdEmp.DataSource = dv;
    grdEmp.DataBind();
    }
    

    The code for the Pagination is written below. Consider Page Size as 3.

    protected void grdEmp_Paging(object source,DataGridPageChangedEventArgs p)
    {
    grdEmp.CurrentPageIndex = p.NewPageIndex;
    BindTable();
    }
    

    Download Source code

    DataGrid Example – Part 1

    Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with 1 Comment on DataGrid Example – Part 1

    For the basics of DataGrid please refer this post: https://jitendrazaa.com/blog/?p=188

    In this example, i will explain the basics of DataGrid control like Theming, Databinding etc.

    We will start our example with creating the SQL Express database of Employee which will contain the following fields : Id, FName, LName, Email.

    Now create a stored procedure to insert the data into Table.

    CREATE PROCEDURE dbo.AddEmployee
    @FName varchar(50),
    @LName varchar(50),
    @Email varchar(50)
    AS
    INSERT INTO Employee (FName,LName,Email) values (@FName,@LName,@Email)
    

    In ASPX page, write the code to input the Employee information.

    First Name : <asp:TextBox ID="txtFName" runat="server"/><br />
    Last Name :<asp:TextBox ID="txtLName" runat="server"/><br />
    Email :<asp:TextBox ID="txtEmail"; runat="server"/><br />
    <asp:Button ID="btnSubmit" Text="Add Record" runat="server" OnClick="btnSubmit_Click"/>
    

    Go to the property of Employee.mdf and select connection string as shown in below image.

    On the click event of the button write below function:

    string conString = @"Data Source=.SQLEXPRESS;AttachDbFilename=""|DataDirectory|Employee.mdf"";Integrated Security=True;User Instance=True";
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
    SqlConnection con = null;
    SqlCommand cmd = null;
    try {
    con = new SqlConnection(conString);
         con.Open();
         cmd = new SqlCommand("AddEmployee", con);
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.Parameters.AddWithValue("@FName", txtFName.Text);
         cmd.Parameters.AddWithValue("@LName", txtLName.Text);
         cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
         cmd.ExecuteNonQuery();
         showConfirmationMessage();
    }
    catch (CustomException ex) {
    ex.logException();
    }finally{
        con.Close();
    }
    }
     private void showConfirmationMessage()
    {
          ClientScriptManager csMngr = Page.ClientScript;
          csMngr.RegisterStartupScript(Page.GetType(), "Success", "alert('Record Added succesfully');", true);
    }
    

    ASPX Code for data grid

    <asp:DataGrid ID="grdEmp" runat="server">
    <HeaderStyle CssClass="Header" />
    <AlternatingItemStyle CssClass="AlternateItemStyle" />
    </asp:DataGrid>
    

    Write below code to bind the data into DataGrid.

    private void bindData()
    {
    SqlConnection con = null;
    SqlDataAdapter adp = null;
    try
    {
    con = new SqlConnection(conString);
    con.Open();
    adp = new SqlDataAdapter("Select * from Employee",con);
    DataSet ds = new DataSet();
    adp.Fill(ds);
    grdEmp.DataSource = ds;
    grdEmp.DataBind();
    }
    catch (CustomException ex)
    {
    ex.logException();
    }finally{
    con.Close();
    }
    }
    

    Final output:

    Download Code

    ASP.NET DataGrid basic questions

    Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with 2 Comments on ASP.NET DataGrid basic questions
    1. What is datagrid? The DataGrid Web server control is a powerful tool for displaying information from a data source. It is easy to use; you can display editable data in a professional-looking grid by setting only a few properties. At the same time, the grid has a sophisticated object model that provides you with great flexibility in how you display the data.
    2. What’s the difference between the System.Web.UI.WebControls.DataGrid and System.Windows.Forms.DataGrid? The Web UI control does not inherently support master-detail data structures. As with other Web server controls, it does not support two-way data binding. If you want to update data, you must write code to do this yourself. You can only edit one row at a time. It does not inherently support sorting, although it raises events you can handle in order to sort the grid contents. You can bind the Web Forms DataGrid to any object that supports the IEnumerable interface. The Web Forms DataGrid control supports paging. It is easy to customize the appearance and layout of the Web Forms DataGrid control as compared to the Windows Forms one.
    3. How do you customize the column content inside the datagrid? If you want to customize the content of a column, make the column a template column. Template columns work like item templates in the DataList or Repeater control, except that you are defining the layout of a column rather than a row.
    4. How do you apply specific formatting to the data inside the cells? You cannot specify formatting for columns generated when the grid’s AutoGenerateColumns property is set to true, only for bound or template columns. To format, set the column’s DataFormatString property to a string-formatting expression suitable for the data type of the data you are formatting.
    5. How do you display an editable drop-down list? Displaying a drop-down list requires a template column in the grid. Typically, the ItemTemplate contains a control such as a data-bound Label control to show the current value of a field in the record. You then add a drop-down list to the EditItemTemplate. In Visual Studio, you can add a template column in the Property builder for the grid, and then use standard template editing to remove the default TextBox control from the EditItemTemplate and drag a DropDownList control into it instead. Alternatively, you can add the template column in HTML view. After you have created the template column with the drop-down list in it, there are two tasks. The first is to populate the list. The second is to preselect the appropriate item in the list “” for example, if a book’s genre is set to “fiction,” when the drop-down list displays, you often want “fiction” to be preselected.
    6. How do you check whether the row data has been changed? The definitive way to determine whether a row has been dirtied is to handle the changed event for the controls in a row. For example, if your grid row contains a TextBox control, you can respond to the control’s TextChanged event. Similarly, for check boxes, you can respond to a CheckedChanged event. In the handler for these events, you maintain a list of the rows to be updated. Generally, the best strategy is to track the primary keys of the affected rows. For example, you can maintain an ArrayList object that contains the primary keys of the rows to update.

    You can find more questions on Datagrid at http://msdn.microsoft.com/en-us/library/Aa289519

    Handlers in ASP.NET

    Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags with 2 Comments on Handlers in ASP.NET

    HTTP Handlers is a new technique presented in ASP.NET that was not present in the “Classic ASP”. HTTP Handlers are components that implement the System.Web.IHttpHandler interface. Unlike ASP.NET pages Handlers dont have HTML-markup file, no events and other supporting. All they have is a code-file (written in any .NET-compatible language) that writes some data to the server HTTP response.

    ASP.NET handlers have “.ashx” file extension (unlike pages, that have “.aspx” file extension).

    Handlers are considered to be more lightweight object than pages. That’s why they are used to serve dynamically-generated images, on-the-fly generated PDF-files and similar content to the web-browser.

    One such scenario which may arise in any product is that if  I owe a site and I want to restrict the user from downloading a file if he/she is not logged in. But if the user (not logged) is allowed to see the url of the downloading file then he can just copy the url and paste it in another tab and he can easily download the file from there, i.e. my protection mechanism failed. Now here comes the use of handlers.

    The handlers will restrict the user to even view  the url of the file to be downloaded unless he is logged in.

    How to create the Handlers in ASP.NET in Visual Studio 8.0.

    First step is to create new project-

    Step 1) Open Visual Studio an Goto – File Menu ->New -> Project.

    Step 1
    Step 1

    Step 2) Now new window will open then select  Web -> ASP.NET Web Appliction. Then rename it and click ok.

    Step 2
    Step 2


    Step 3) Now we have to add the Handler (Don’t call it the page, its all different thing) Follow the steps to include the handler in the current project.

    First Right Click on the Solution Explorer -> Add -> New Item ->

    Step 3

    Step 4) Then new window will be displayed. Then select the Generic Handler and rename it then click on Add–>

     

    ASP.Net Handlers
    Step 4

    Step 5) Now open the Default.asp page in Design view and design the form as required using Button Tool from toolbox.

    Step 5
    Step 5

    Step 6) Then write the following code on the click event of both the buttons in Default.aspx.cs page (Just double click on the buttons and it will automatically generate the block in source page)

    protected void btnWoutSecurity0_Click(object sender, EventArgs e)
    {
         Response.Redirect("LinkSecurty.ashx?isSecure = 1");
    }
    protected void btnWoutSecurity_Click(object sender, EventArgs e)
    {
          Response.Redirect("LinkSecurty.ashx");
    }
    
    Step 7) Now open the Handler which we have created earlier i.e. LinkSecurity.aspx.cs  and write the following code–
    public class LinkSecurity : IHttpHandler
    {
         public void ProcessRequest(HttpContext context)
         {
            if (context.Request["isSecure"] == null)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("You are not Logged In.... Please Login to access this page...");
            }else
            {
                context.Response.ContentType = "image/png";
                context.Response.WriteFile("imageName.png")
            }
          }
          public bool IsReusable
          {   get{return false;}
          }
    }
    

    Upload Files in ASP.NET at Production server

    Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , , , with Leave a comment on Upload Files in ASP.NET at Production server

    In this article, i am going to demonstrate that how to upload the file in ASP.NET production server.

    Most of the case, a developer created a code to upload the file and test it on his local machine. program runs smoothly, but as he forward the same code on production. He stuck in the file permission error as on the local he has the full permission whereas on development its not the case.

    So i decided to write this tutorial for the beginners which will demonstrate lots of ASP.NET features.

    First we need to create a folder in Server and share it with ASP.NET web server as described.

    Right click on folder, select Web sharing tab and select the radio button “Share this folder”. One  window appear, give it alias name which will be used in coding.

    After this, open Run box and type “inetmgr“. you will see that your web shared folder appears in the IIS.

    Right click on folders property. one window will opened.

    Select “Directory Security” tab then click on “Edit” button and then check “Anonymous access”. And because of this setting any body can access or download that file.

    Now we are ready, to create a sample application which will demonstrate that how to upload the file and use it.

    Create ASP.NET project in Visual Studio. Create a webpage with fileupload, hyperlink and button control.

    <form id="form1" runat="server">
    <asp:FileUpload ID="uploadFile" runat="server" /><br />
    <asp:HyperLink ID="hypLink" runat="server" Visible="false" Target="_blank"></asp:HyperLink><br />
    <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="btnUpload_Click" />
    </form>
    
    

    In web.config add two keys.  One for actual folder location in which we are going to upload the files and other its alias name. we can also hard code that, but its good practice to make it configurable at any time because in near future we may want to change the location.

    
    <appSettings>
    
    <add key="DemoAttachment" value="D:ShareDemoShare"></add>
    
    <add key="DemoAttachmentVirtualPath" value="http://localhost/DemoShare/"></add>
    
    </appSettings>
    
    

    In DemoAttachmentVirtualPath key, value should like “http://machinename/” + Alias folder name.

    On click event of button, write below code:

    string strPath = ConfigurationManager.AppSettings["DemoAttachment"];
    uploadFile.SaveAs(strPath + System.IO.Path.GetFileName(uploadFile.FileName));
    hypLink.Visible = true;
    string VirtualPath = ConfigurationManager.AppSettings["DemoAttachmentVirtualPath"];
    hypLink.Text = System.IO.Path.GetFileName(uploadFile.FileName);
    hypLink.NavigateUrl = VirtualPath + uploadFile.FileName;
    string strPath = ConfigurationManager.AppSettings["DemoAttachment"];
    
    uploadFile.SaveAs(strPath + System.IO.Path.GetFileName(uploadFile.FileName));
    hypLink.Visible = true;
    string VirtualPath = ConfigurationManager.AppSettings["DemoAttachmentVirtualPath"];
    
    hypLink.Text = System.IO.Path.GetFileName(uploadFile.FileName);
    
    hypLink.NavigateUrl = VirtualPath + uploadFile.FileName;
    
    

    The output will look like:

    Download Source code

    For the file size limitation, please visit this article : https://jitendrazaa.com/blog/?p=125