Skip to content
July 22, 2011 / Manoranjan

Speed up your ASP.Net website by using HTTP compression


Page loading speed is very important thing for any website. If your website takes too much time to load webpage then it may affects your user. So, you need to speed up your page loading. There are several techniques available to speed up the site. HTTP compression is one of the technique. There are two types of compression available in .Net. i.e. :

  • GZip
  • deflate

By using above two compression technique you can speed up your asp.net website.

Compression can be performed in two stages. i.e. IIS level or Web Site level. If you enable in IIS level then it will reflect to all website hosted on that IIS. if you want to setup IIS level compression then click here. If you want to do in a single website then you can do by little changes in code. In this article i am going to explain in detail about page level or website level compression.

How to do HTTP Compression?

To accomplish this, We need to compress the response output. It can be easily done by DeflateStream or GzipStream classes.  These two classes available in System.IO.Compression  namespace. Between these two deflate is the more fast than Gzip. Because Gzip contains more header info than deflate. To use HTTP compression in our ASP.NET website without editing each and every single page, we will use ASP.NET web application’s life cycle events in Global.asax file.

A Global.asax file is placed in your root folder. There are several methods available in Global.asax file to handle ASP.Net life cycle events. We will handle PreRequestHandlerExecute event to insert our code in this method. This event occurs just before ASP.NET starts executing an event handler.

To do the HTTP  compression follow below steps :

1.  create Global.asax file in the root directory(if there is no Global.asax file).

2. Then make some changes as per the below code.

<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.IO.Compression" %>

<script runat="server">

    void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;
        string acceptEncoding = app.Request.Headers["Accept-Encoding"];
        Stream prevUncompressedStream = app.Response.Filter;

        if (!(app.Context.CurrentHandler is Page ||
            app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
            app.Request["HTTP_X_MICROSOFTAJAX"] != null)
            return;

        if (acceptEncoding == null || acceptEncoding.Length == 0)
            return;

        acceptEncoding = acceptEncoding.ToLower();

        if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
        {
            // defalte
            app.Response.Filter = new DeflateStream(prevUncompressedStream,
                CompressionMode.Compress);
            app.Response.AppendHeader("Content-Encoding", "deflate");
        }
        else if (acceptEncoding.Contains("gzip"))
        {
            // gzip
            app.Response.Filter = new GZipStream(prevUncompressedStream,
                CompressionMode.Compress);
            app.Response.AppendHeader("Content-Encoding", "gzip");
        }
    }
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }

    void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown

    }

    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.

    }

</script>

The above code will enable HTTP compression in your ASP.NET website.

The first thing we do is to tell the ASP.NET compiler that we are using C# language. It means all the below codes are in C# language.

<%@ Application Language="C#" %>

As i said above the DeflateStream and GZipStream classes are available in the System.IO.Compression namespace. So we need to import this namespace.

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.IO.Compression" %>

Next, we need to declare the method which will handle the PreRequestHandlerExecute life cycle event.

void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
	...
}

Then in this method, We need to confirm that the requested ASP.NET resource is either a valid ASP.NET page or a Web Service. If it is not, then we just return and do nothing. we also check for “HTTP_X_MICROSOFTAJAX” item in the HttpRequest collection. This item is present if we are using AJAX in our web site.  because if we use AJAX and then compress the HTTP then it will through an exception.

app.Response.Filter exposes a Stream which we override with a GZipStream object or deflate object, this will cause the raw text response to get compressed, then we need to tell the browser that this response is compressed. So we need to add this to header by  app.Response.AppendHeader.

July 20, 2011 / Manoranjan

Temporary Tables in SQL Server


Introduction

Temporary table is very useful tool in SQL Server for developer. It provided short term use of data. These tables can be created at runtime and can do the all kinds of operations that one normal table can do. But, based on the table types, the scope is limited. These tables are created inside tempdb database. There are two types of temporary table in SQL Server:
1. Local
2. Global

Local : Local temporary tables are only available to the current connection to the database for the current user. These are dropped automatically when the connection is closed.

Global : Global temporary tables are available to all connections that created and exist to that database. These are dropped when the last connection using it is closed.

Both types of temporary tables are created in the system database tempdb.

How to create Temporary Tables?

Temporary tables can be created like any table in SQL Server with a CREATE TABLE or SELECT..INTO statement.
To make the table as local temporary table, attach (#) as prefix with the name of the table.
To make the table as global temporary table, attach (##) as prefix with the name of the table.

Create Local Temporary Table using Create Table statement.
Code :

CREATE TABLE #TempTable1
(
tempfield1 INT,
tempfield2 VARCHAR(50)
)

Create Local Temporary Table using SELECT … INTO statement.
Code :

SELECT
tempfield1 as id,
tempfield2 as Name
INTO #TempTable1 FROM ActualTable1

Above sample codes will create a local temporary table named #TempTable1 with two fields with name tempfield1 and tempfield2.

Create Global Temporary Table using Create Table statement.
Code :

--replace # to ##
CREATE TABLE ##TempTable1
(
tempfield1 INT,
tempfield2 VARCHAR(50)
)

Create Global Temporary Table using SELECT … INTO statement.
Code :

SELECT
tempfield1 as id,
tempfield2 as Name
INTO ##TempTable1 FROM ActualTable1

How to check if Temporary table exist?

use below stored procedure for checking local temp table:

IF OBJECT_ID('tempdb..#TempTable1') IS NOT NULL
BEGIN
PRINT '#TempTable1 exists'
END
ELSE
BEGIN
PRINT '#TempTable1 does not exist'
END

use below code for checking global TempTable1 table :

IF OBJECT_ID('tempdb..##TempTable1') IS NOT NULL
BEGIN
PRINT '##TempTable1 exists'
END
ELSE
BEGIN
PRINT '##TempTable1 does not exist'
END
July 19, 2011 / Manoranjan

Displaying image in a gridview


Can not display images in gridview?

Many times I have seen people getting problem to show image in a gridview. This problem arises normally due to wrong image URL. This is because web server was not able to find the image.

Consider an example where, in my root directory I have a folder name images and my root directory also presents in a physical media(HardDrive). and i saved the image file in database with physical path(ex : c:\\mywebsite\images\a.jpg).

Then i tried to fetch the path from database and showing in gridview. At this time it will give the physical path to the image control. but in case of website, all data present in a virtual directory. So we need to give the virtual path to the image. Because when we open the page on browser it will search the content of images from virtual path.

When you save the path into database, just save the virtual path of the image. To get virtual path follow below code :

string filename=Server.MapPath(“~/images/a.jpg”);

Then you can save filename into database.

To show the image into gridview design gridview like below code :

<asp:GridView runat="server" ID="gv_Products" AutoGenerateColumns="false"  >

<Columns>
<asp:BoundField DataField="ProductNm" HeaderText="Product Name" ItemStyle-Height= "100px" ItemStyle-Width = "200px" />
<asp:BoundField DataField="Price" HeaderText="Price" ItemStyle-Height= "100px" ItemStyle-Width = "200px"/>
<asp:TemplateField>
       <ItemTemplate>
               <img src='<%# Eval("ProductImgPath") %>' />
       </ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
May 23, 2011 / Manoranjan

Create simple guest book in ASP.Net and C#.Net


Sometimes we need to put guest book in our website. Suppose we don’t have any database to save the data. At that time, what can we do to save the data?

We can use simple text file to save the data.

check below code :

in page.ASPX page :

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>GuestBook</title>
    <style >
    hr
    {
        height:1px;
        background:#446791;
    }
    .time
    {
        font-size :11px;
        font-family :Arial;
    }
    .name
    {
        font-family :Arial ;
        font-size :11px;
        font-weight :bold;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <asp:Timer ID="Timer1" runat="server" Interval="2000" ontick="Timer1_Tick">
        </asp:Timer>
        <asp:UpdatePanel ID="UpdatePanel1" UpdateMode ="Conditional"  runat="server">
        <Triggers >
           <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
        </Triggers>
        <ContentTemplate >
            <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
            <div style ="width :815px; height :500px; overflow :auto ">
                <asp:Label ID="lblMsg" style="padding:5px" runat="server" Text="" Width ="800px" BorderColor ="Teal" BorderWidth ="1px" BorderStyle ="Solid" BackColor ="AliceBlue"  ></asp:Label>
            </div>
        </ContentTemplate>
        </asp:UpdatePanel>
        <asp:UpdatePanel ID="UpdatePanel2" UpdateMode ="Conditional" runat ="server" >
        <Triggers >
        <asp:PostBackTrigger ControlID ="btnSend" />
        </Triggers>
        <ContentTemplate >
        <br /><br />
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate ="txtName" ErrorMessage="Enter Your Name"></asp:RequiredFieldValidator>
            <br />
            <asp:TextBox ID="txtMsg" TextMode ="MultiLine" Width="500px" Height="60px" runat="server" ></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate ="txtMsg" ErrorMessage="Enter Message"></asp:RequiredFieldValidator>
            <asp:Button ID="btnSend" runat="server" Text="Submit" Font-Bold ="true"  onclick="btnSend_Click" />
        </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

Now download for full source code and cs code file :

Download Full Working Source Code from below links :

1. http://uploading.com/files/1832m6ee/GuestBook.zip/

Thank You.

April 23, 2011 / Manoranjan

How to access the server control of content page inside the javascript?


Hello,
Sometime i used to create websites using Master Page. Some server controls are added into content page. For some cases i need to use to change the value of those control at client side. So usually write javascript code.

For example : Suppose i want to add two number and show the result. I want to perform addition in client side and show the result on content page’s Label control.

for this first i wrote the below code :

function addNumber(val1,val2)
{
var result=val1+val2;
document.getElementById('Label1').innerHTML = result;
}

But the above code gives javascript error. i.e : unrecognised id.
Because the content page’s control id converted as per contentplace holder id.
So i modified the code to below code.

function addNumber(val1,val2)

{

var result=val1+val2;

document.getElementById('<%=Label1.ClientID%>').innerHTML = result;

}
 

The above code works fine.

so whenever you want to access the content page’s control at client side just put the clientID of that control not the control id only.

April 23, 2011 / Manoranjan

Create HitCounter using ASP.Net and C#.Net


Hello Friends,
Some of our user writes to post the code for hit counter and i created a sample application.
Here i posted the code and sample application.

To do so follow the below steps :

Step 1 :

Open your project. then add one text file with name “hitcounter.txt”.

Step 2 :

Then open the page where you want to place the hit counter.

Step 3 :

Then Goto Page_Load event of that page. and put the below code.
Note : Here i used to put the code with Response.Write method. you can set the counter to a Label control. To show on Label Control use : Label1.Text=gethitcounts(); instead of Response.Write(gethitcounts());

Code :

using System.IO;
protected void Page_Load(object sender, EventArgs e)
{
    Application.Lock();
    Response.Write(gethitcounts()); //you can change here for label control
    Application.UnLock();
}
public string gethitcounts()
{
    string lastcount = "";
    try
    {
        StreamReader SR = File.OpenText(Server.MapPath("hitcounter.txt"));
        string getcount = null;
        while ((getcount = SR.ReadLine()) != null)
        {
            lastcount = lastcount + getcount;
        }
        SR.Close();
        long newcount = Convert.ToInt64(lastcount);
        newcount++;
        TextWriter TxtWtr = new StreamWriter(Server.MapPath("hitcounter.txt"));
        TxtWtr.WriteLine(Convert.ToString(newcount));
        TxtWtr.Close();
        SR = File.OpenText(Server.MapPath("hitcounter.txt"));
        getcount = null;
        lastcount = "";
        while ((getcount = SR.ReadLine()) != null)
        {
            lastcount = lastcount + getcount;
        }
        SR.Close();
    }
    catch (Exception ex)
    {
        TextWriter TxtWtr = new StreamWriter(Server.MapPath("hitcounter.txt"));
        TxtWtr.WriteLine(Convert.ToString("1"));
        TxtWtr.Close();
        lastcount = "1";
    }
    return lastcount;
}

Download Sample Code

1. http://www.filesonic.com/file/1026929374/Hit_Counter.zip

2. http://www.fileserve.com/file/w7EcdZf

3. http://uploading.com/files/3ae87245/Hit_Counter.zip/

4. http://letitbit.net/download/47886.405cee85e9b5a71b90f8b92256c5/Hit_Counter.zip.html

Thank You.

Regards,
Manoranjan Sahoo
http://www.dotnetsquare.com

October 7, 2010 / Manoranjan

Upload Files in ASP.NET at Production Web server


Most of the case, a developer created a code to upload the file and test it on his local machine. Program runs perfectly on local machine, but after publish that onto production server. He stuck in the file permission error as on the local machine he has the full permission whereas on the production server its not the case.

So i decided to write this tutorial for the beginners which will demonstrate how to upload a file onto webserver or production server.

Step 1 :

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.

Step 2 :

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

Step 3 :

Right click on folders property. one window will opened like below.

Step 4 :

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.

Step 5 :

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

<form runat="server">
<asp:FileUpload runat="server" /><br />
<asp:HyperLink runat="server" Visible="false" Target="_blank"></asp:HyperLink><br />
<asp:Button Text="Upload" runat="server" />
</form>

Step 6 :

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:\Share\DemoShare\"></add>
<add key="DemoAttachmentVirtualPath" value="http://localhost/DemoShare/"></add>
</appSettings>

Note : In DemoAttachmentVirtualPath key, value should like http://machinename/&#8221; + Alias folder name.

Step 7 :

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;

FileUploadDemo

This Post is provided by my friend Jitendra. Find his useful post here

May 17, 2010 / Manoranjan

Export GridView To Excel using C#.Net


Here I provide the simple code for export gridview to excel in c#.net. Here i considered that, there is one gridview and two button.One button to fetch the data and show on gridview and other is to export that data into excel. To export follow the below steps.

Step 1 :

Create one .aspx file. Add one gridview and two button to this.

Step2 :

Now Name one of those button as btnExportToExcel. then write the following code to the click event of that button. Make changes the sql query as per your need.

Code :

protected void btnExportToExcel_Click(object sender, EventArgs e)
{
    try
    {
		string lblSQLQry="select * from  tablename where <condition>";
		string fileName="FileName";//you can also pass a unique file name here
        ExportToExcelwithDatareader1(lblSQLQry, fileName);
    }
    catch (SqlException ex){}
    catch (SystemException ex){}
}

Step3 :

Below the above click event method write the following method. Make changes the connection details as per your need.

Code :

public void ExportToExcelwithDatareader1(string strqry, string strfileName)
{
    try
    {
        SqlDataReader dr = null;
        StringBuilder sb = new StringBuilder();
		SqlCommand cmdexreader = new  SqlCommand();
		SqlConnection sqlconn="Your SQL Server Connection String";
        sqlconn.Open();
        cmdexreader.CommandText = strqry;
        cmdexreader.CommandTimeout = 0;
        cmdexreader.Connection =sqlconn;
        dr = cmdexreader.ExecuteReader(CommandBehavior.CloseConnection);
		string headername="Report";
        sb.Append("<TABLE border='1'><Center><thead style='font-size:16;font-family:Verdana;color:green'><font color='green' size='5'><b>" + headername + "</font></thead></Center>");
        for (int count = 1; count < dr.FieldCount - 3; count++)
        {
            string thname = "";
            thname = dr.GetName(count).ToString();
            sb.Append("<TH width='71' style='background-color:orange;position:fixed;color:White;font-family:Verdana;white-space: pre-wrap ;font-size:14'><b>" + thname + "</b></TH>");
        }
        while (dr.Read())
        {
            sb.Append("<TR>");
            for (int col = 1; col < dr.FieldCount - 3; col++)
            {
                sb.Append("<TD align='Center'><font color='black'>" + dr.GetValue(col).ToString() + "</font></TD>");
            }
            sb.Append("</TR>");
        }
        dr.Dispose();
        sb.Append("</TABLE>");
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=" + strfileName + ".xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        stringWrite.WriteLine(sb.ToString());
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        Response.Write(stringWrite.ToString());
        Response.Flush();
        Response.End();
    }
    catch (Exception ex){}
}

Step 4 :

That’s it. Now you can run the file to see the output.

Thank You.

May 12, 2010 / Manoranjan

How to get the result as 00 format for month or date of a datetime from SQL ?


Hi,
One day i need to fetch the month part of a date field of my sql database. i tried the following code to get the month part :

select datepart(MONTH,[Date]) from tablename

but it gives the result as :

1,2,3…

But i need as 01,02,03….

so i change the sql syntax as below :

SELECT RIGHT(REPLICATE('0', 2) + CAST(datepart(MONTH,[Date]) AS VARCHAR(2)), 2) FROM Tablename

or you can use simple :

SELECT RIGHT('0' + convert(varchar(2),datepart(MONTH,[Date])), 2) FROM <TableName>

it gives me the correct result…

Thank You.


March 16, 2010 / Manoranjan

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.

Bbut 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.

Follow

Get every new post delivered to your Inbox.