Popular Posts

Friday, 15 July 2011

Server.Transfer v/s Response.Redirect ASP.Net

Both are the objects of ASP.NET. Both are used to transfer a user from one page to another page. Both are used for the same purpose but still there are some differences are there between both that are as follows:

  • Response.Redirect it first sends the request for the new page to the browser then browser sends the request for the new page to the webserver then after your page changes.
But in case of Server.Transfer it directly communicate with the server to change the page hence it saves a roundtrip in the whole process.

  • If you are using Server.Transfer then you can directly access the values, controls and properties of the previous page which you can’t do with Response.Redirect.

  • Response.Redirect changes the URL in the browser’s address bar. So they can be bookmarked. Whereas Server.Transfer retains the original URL in the browser’s address bar. It just replaces the contents of the previous page with the new one.

  • Response.Redirect can be used for both .aspx and html pages whereas Server.Transfer can be used only for .aspx pages and is specific to ASP and ASP.NET.

  • Response.Redirect can be used to redirect a user to an external websites. Server.Transfer can be used only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page running on a different server.


Description in Detail with Example:

Suppose you are currently on the Default1.aspx and now you are transferring the user to the Default2.aspx using Response.Redirect then When the Default2 page is requested, Default1 has been flushed from the server’s memory and no information can be retrieved about it unless the developer explicitly saved the information using some technique like session, cookie, application, cache etc.
But in case of Server.Transfer variables can stay in scope and Default2 can read properties directly from Default1 because it’s still in memory, as you know the Server.Transfer just changes the focus from Default1 to Default2 So in this case browser doesn’t know that any change is happen there that’s why with this method you can access the information about the previous page.


If you want to pass state from the source page to the new page, you have to pass it either on the URL (such as a database key, or message string), or you can store it in the Session object (caveat: there may be more than one browser window, and they’ll all use the same session object). 

e.g. Redirect to the Default1.aspx page, passing an ID on the query string. "true" stops processing the current page: 
protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default2.aspx?id=34", true);
    }


Now fetching value of id on Default2.aspx Page, type following:


protected void Page_Load(object sender, EventArgs e)
    {
               Response.Write(Request.QueryString["id"].ToString());
          }

Passing TextBox Value from Default1.aspx to Default2.aspx by using Response.Transfer

Create Controls on Default1.aspx form like this:

<html>
<body>

    <form>   
     <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="btn_Submit" runat="server" onclick="btn_Submit             _Click" Text="Submit" />
    </div>
    </form>

</body>
</html>

Coding in .cs Class:

protected void btn_Submit_Click(object sender, EventArgs e)
    {
        Server.Transfer("Default2.aspx");
    }

Coding for Default2.aspx Page:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           Page originalPage = (Page)Context.Handler;
           TextBox textBox1 =  (TextBox)originalPage.FindControl("TextBox1");
           Response.Write(textBox1.Text);
        }
    }

Note: Now run the project, type “Welcome ASP.net” in TextBox1 of Default1.aspx Page. Now click on Submit Button.
After this, Default2.aspx Page will open with text “Welcome ASP.net” on Screen.

Response.Write VS Server.Transfer ASP.Net

Response.Write 

This Method is used to write a string to HTTP output. It is very useful and mostly used to write out the content of variables.

Write this in .cs class on Page_Load Event:

protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("Welcome ASP.Net !!!"  );
}

Server.Transfer

The Transfer method sends (transfers) all the state information (all application/session variables and all items in the request collections) created in one ASP file to a second ASP file.




When the second ASP page completes its tasks, it will NOT return to the first ASP page (like the Execute method).
Note: The Transfer method is an efficient alternate for the Response.Redirect. A redirect forces the Web server to handle an extra request while the Server.Transfer method transfers execution to a different ASP page on the server, and avoids the extra round trip.
Syntax:

Server.Transfer(path)

Example:

Page Default1.aspx
protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("Page1 Content. Part 1 <br />");
        Response.Write("Page1 Content. Part 2 <br />");
        Server.Transfer("Default2.aspx" );       
    }

Page Default2.aspx

protected void Page_Load(object sender, EventArgs e)
    {
Response.Write("Page 2 Content <br />");
     }

Run this project and Click Button1, It will redirect on Other Page named Default2.aspx


Result Will Look like this

Page1 Content. Part 1
Page1 Content. Part 2
Page 2 Content

Install IIS on Different Operating Systems

Install IIS on Windows XP and Windows 2000

Follow these steps to install IIS on Windows XP and Windows 2000:

  1. On the Start menu, click Settings and select Control Panel
  2. Double-click Add or Remove Programs
  3. Click Add/Remove Windows Components
  4. Click Internet Information Services (IIS)
  5. Click Details
  6. Select the check box for World Wide Web Service, and click OK
  7. In Windows Component selection, click Next to install IIS
After you have installed IIS, make sure you install all patches for bugs and security problems. (Run Windows Update).


Install IIS on Windows Server 2003

  1. When you start the Windows Server 2003, you should see the Manage Your Server wizard
  2. If the wizard is not displayed, go to Administrative Tools, and select Manage Your Server
  3. In the wizard, click Add or Remove a Role, click Next
  4. Select Custom Configuration, click Next
  5. Select Application Server role, click Next
  6. Select Enable ASP.NET, click Next
  7. Now, the wizard may ask for the Server 2003 CD. Insert the CD and let it run until it is finished, then click the Finish button
  8. The wizard should now show the Application Server role installed
  9. Click on Manage This Application Server to bring up the Application Server Management Console (MMC)
  10. Expand the Internet Information Services (IIS) Manager, then expand your server, and then the Web Sites folder
  11. You should see the Default Web Site, and it should not say (Stopped)
  12. IIS is running!
  13. In the Internet Information Services (IIS) Manager click on the Web Service Extensionsfolder
  14. Here you will see that Active Server Pages are Prohibited (this is the default configuration of IIS 6)
  15. Highlight Active Server Pages and click the Allow button
  16. ASP is now active!

Monday, 11 July 2011

Clear all Textbox Contents from ASP.Net Page

Suppose you have n number of Textboxes on the page and want to clear all at single click.


HTML Page code :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
   
    </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    </form>
</body>
</html>


Write a procedure in .cs class as below ;

private void ClearControls()
    {
        foreach (Control c in Page.Controls)
        {
            foreach (Control ctrl in c.Controls)
            {
                if (ctrl is TextBox)
                {
                    ((TextBox)ctrl).Text = string.Empty;
                }
            }
        }
    }


protected void Button1_Click(object sender, EventArgs e)
    {
        ClearControls();
    }

Fatch Images in Gridview From DataBase ASP.Net

Suppose you have database with following fields;


Now suppose you have already insert some data in table something like this;



You can see how make ASP.Net page to insert image in Database

Adding HTTPHandler:

To add HTTPHandler right click on the project explorer --> AddNewItem --> Generic Handler from the templete eg given pic below and Name it as ImageHanlder.ashx ;


Create a procedure like Proc_GetImageFromDataBase in database.

create procedure Proc_GetImageFromDataBase
 @ImageID int

AS
begin
select * from InsertImageDemoTable where ImageID =@ImageID
end


Now Coding for ImageHandler.ashx

<%@ WebHandler Language="C#" Class="ImageHandler" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public class ImageHandler : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        string strId = context.Request.QueryString["Id"];

        if (!string.IsNullOrEmpty(strId))
        {
            SqlConnection conn = new  SqlConnection(ConfigurationManager.ConnectionStrings["Cms"].ConnectionString);
            SqlDataReader sqlDr = null;
            try
            {
                conn.Open(); //open database connection
                SqlCommand sqlCmd = new SqlCommand("Proc_GetImageFromDataBase", conn);
                sqlCmd.CommandType = CommandType.StoredProcedure;
               
                //Add the parameter to SQLCommand object
                sqlCmd.Parameters.AddWithValue("@Imageid", strId);
                sqlDr = sqlCmd.ExecuteReader();
                sqlDr.Read();
                context.Response.BinaryWrite((Byte[])sqlDr[2]);
                context.Response.End();                               
            }
            catch (Exception ex)
            {
                //Handle error If occured
            }
            finally
            {
                if (sqlDr != null && !sqlDr.IsClosed)
                {
//close SqlDataReader

                    sqlDr.Close();
                }
//close database connection

                conn.Close();
}
        }

    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}


Now add a new form in your project like this;

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

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
   <div>
<asp:TextBox ID="txtImageName" runat="server" Width="110px"> </asp:TextBox>

<asp:FileUpload ID="FileUpload1" runat="server"/>

<asp:Button ID="btnUpload" runat="server"
            OnClick="btnUpload_Click" Text="Upload" style="height: 26px"/>
</div>

   
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
       <Columns>
           <asp:BoundField DataField="ImageID" HeaderText="Header Text" />
           <asp:TemplateField HeaderText="Image Form DataBase">
               <ItemTemplate>
                   <img alt="Image" height="70px" src='<%# "ImageHandler.ashx?Id="+ Eval("ImageId") %>' width="70px" />
               </ItemTemplate>
           </asp:TemplateField>
       </Columns>
   </asp:GridView>


    </form>
</body>
</html>


Coding for .cs Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class Default16 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Load_GridData();
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string strImageName = txtImageName.Text.ToString();
        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
        {
            byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
            HttpPostedFile uploadedImage = FileUpload1.PostedFile;
            uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);
            // Create SQL Connection
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["Cms"].ConnectionString;
            // Create SQL Command
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO InsertImageDemoTable(ImageName,Image)" +
            " VALUES (@ImageName,@Image)";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);
            ImageName.Value = strImageName.ToString();
            cmd.Parameters.Add(ImageName);
            SqlParameter UploadedImage = new SqlParameter
             ("@Image", SqlDbType.Image, imageSize.Length);
            UploadedImage.Value = imageSize;
            cmd.Parameters.Add(UploadedImage);
            con.Open();
            int result = cmd.ExecuteNonQuery();
            con.Close();
            GridView1.DataBind();
        }


    }


     private void Load_GridData()
     {
         SqlConnection conn = new SqlConnection();
         conn.ConnectionString = ConfigurationManager.ConnectionStrings["Cms"].ConnectionString;
        conn.Open();  // open the connection
        SqlDataAdapter Sqa = new SqlDataAdapter("select * from InsertImageDemoTable", conn);
        DataSet ds = new DataSet();
        Sqa.Fill(ds);   // fill the dataset
        GridView1.DataSource = ds; // give data to GridView
        GridView1.DataBind();
        conn.Close();
     }
}

Gridview something look like this: