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

    cannot access a closed file – FileUpload in ASP.NET

    Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with 16 Comments on cannot access a closed file – FileUpload in ASP.NET

    This was very interesting error, i got during development of file upload control in ASP.NET.

    On my local system, every thing was just fine. but when i deployed my application on development server, my control was able to upload only small size files.

    whenever i tried to upload large size file i got error “cannot access a closed file”

    After going through MSDN i found that there is one new element added in ASP.NET 2.0 known as httpRuntime.

    So i just added this new Tag in my web.config and every thing was right.

    <system.web>
    <httpRuntime  maxRequestLength="15360" requestLengthDiskThreshold="15360"/>
    </system.web>
    

    Note :

    requestLengthDiskThreshold should not exceed the maxRequestLengthattribute.
    
    To read more about this, please visit http://msdn.microsoft.com/en-us/library/e1f13641(VS.80).aspx
    
    

    XML Parsing Error: no element found

    Author posted by Jitendra on Posted on under category Categories ASP.NET, Tech Tips and tagged as Tags , with 3 Comments on XML Parsing Error: no element found

    Few Days ago, i found strange error like “XML Parsing Error: no element found“.

    I was unable to find the exact root cause. Most of the times it happens if you are missing any closing tag in your ASPZ application. I checked my complete page and reconfirmed but error still persist.

    somehow i found that ASP.NET treat the response of page as XML document and that’s why we receive XML Parsing Error: no element found error.

    so explicitly i set the response type of my page as text/HTML. Response.ContentType = “text/HTML”.

    And this line tells the ASPX that page is HTML, not XML.

    ASP.Net Error: Response is not available in this context

    Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags with 2 Comments on ASP.Net Error: Response is not available in this context

    This error occurred when  i tried to call Response.Redirect method from a class file. Then i tried to find the solution and i got to know that when we use the response object from an aspx page either from aspx page or it’s codebehind page, the response object is directly available because all these derived from the page object.

    When we use the response object in our own class, the object is not directly available, so we got this message.

    But we can use it by the following method :

    HttpContext.Current.Response.Redirect(http://google.com“);

    Same problem happens when we tried to call a function from Response object.

    Thank You.

    App_Offline.htm in ASP.NET

    Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags with 1 Comment on App_Offline.htm in ASP.NET

    If you place a file with the name App_Offline.htm in the root of a web application directory, ASP.NET 2.0 will shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application.

    ASP.NET will also then respond to all requests for dynamic pages in the application by sending back the content of the App_offline.htm file (for example: you might want to have a “site under construction” or “down for maintenance” message).

    Once you remove the App_offline.htm file, the next request into the application will cause ASP.NET to load the application and app-domain again, and it will be back to normal.

    If you place a file with the name App_Offline.htm in the root of a web application directory, ASP.NET 2.0 will shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application.

    ASP.NET will also then respond to all requests for dynamic pages in the application by sending back the content of the App_offline.htm file (for example: you might want to have a “site under construction” or “down for maintenance” message).

    Once you remove the App_offline.htm file, the next request into the application will cause ASP.NET to load the application and app-domain again, and it will be back to normal.

    Limitation:

    Note that the file must be at least 512kb in size or it will not work. This a well known ‘limitation’.