SlideShare a Scribd company logo
1 of 7
1. Request and response

We need a basic knowledge about what is Request & Response objects. The following information may be
helpful to all. How beautifully these are handling things occurring in a Page class.

              Request and Response are the properties of the Page class. The Request property allows you
to access the HTTPRequest object, which contains information,such as path of the request, about the
HTTP request for the page. The Response property allows you to access the HTTPResponse object, which
in turn allows you to send data to the browser as the result of the request.

             In fact, Request and Response properties map directly to HttpRequest and HttpResponse
objects respectively. Therefore, you can directly access these objects in ASP.NET pages by using the
Request and Response properties.

            Querystrings is the method of the HttpRequest object, which returns the parameter that's
passed with the page URL. The Write method of the HTTPResponse object is used to display text in a
browser. You can use the html formatting elements to format the text.

   2. Applications

Mobile gadgets such as cell phones and PDAs have become ubiquitous. Just about everyone today
possesses a cell phone and most cell phones are equipped with features such as downloading ringtones,
getting sports updates, news headlines and so forth. ASP.NET 2.0 enables you to easily create applications
targeting such devices.

The following links give you a head start on mobile application development with ASP.NET:

   •   .NET Mobile Tutorial
   •   Building Mobile Web Applications with .NET Mobile Web SDK & ASP.NET
   •   ASP.NET For Mobiles
   •   ASP.NET Mobile Web Development Overview
   •   Introduction to ASP.NET Mobile
   •   Code Project Article

Since most developers will not actually use cellular devices to test their mobile applications, device
emulators have been created by companies like Microsoft, Nokia and others for testing purposes. A device
emulator is software that simulates a mobile device. The Visual Studio IDE includes built-in emulator
SDKs for Pocket PC and SmartPhone.

   3. Session

ASP.NET Session state provides a place to store values that will persist across page requests.
Values stored in Session are stored on the server and will remain in memory until they are explicitly
removed or until the Session expires.

Storing and retrieving a value in the Session is as simple as:

       VB
Session("Name") = "John Doe"'orSession.Add("Name","John Doe")'retrieving

Dim Name As String = Session("Name")

       C#

Session["Name"] = "John Doe";//orSession.Add("Name","John Doe");//retrievingstring

Name = (string)Session["Name"];

By default the Session will be created within the same process that your web site runs in (InProc). This is
controlled by a setting in the web.config file:

<sessionState mode="InProc" />

Although running the Session In Process is very convenient, it does mean that all Session values will be
lost whenever the application recycles (such as when deploying updates) . There are alternate modes you
can use that will allow the Session state to survive even when the application recycles. The available
options are:

   •   Off - No session state will be stored
   •   InProc - (The Default) Session state exists within the process the web is using
   •   StateServer - Session data is sent to the configured stateserver service
   •   SQLServer - Session data is store in the configured sql server database

Both the StateServer mode and the SQLServer mode allow Session state to survive an application recycle.
But, when storing reference type objects (such as class instances), they can only be stored to StateServer or
SQLServer if they have been marked with the Serializable attribute.

An important consideration for using Session state is that the Session does expire. By default, if a user
does not access their Session data within 20 minutes (by default), the Session will expire and all items that
had been stored in the Session will be discarded. Because of this, it is important to check the object that
is returned from the Session to see if it exists or if it is null before you try to work with it. For example:

object sessionObject = Session["someObject"];
if (sessionObject != null) {
  myLabel.Text = sessionObject.ToString();
}

The Session Timeout is adjustable through a web.config setting but increasing the timeout value can put
memory pressure on your server that may be undesirable.

<sessionState timeout="number of minutes" />

Other commonly used Session methods are:

   •   Session.Abandon() - removes the Session and all items that it contains
   •   Session.Clear() - removes all items from the Session
   •   Session.RemoveAll() - removes all items from the Session
   •   Session.Remove("itemName") - removes the item that was stored under the name "itemName"


   4. Response .redirect
Using Response.Redirect and Response.End in Try...Catch block

In ASP.NET if you are using Response.End - Used for terminating page execution or Response.Redirect -
used for redirecting page to some other page, and you are including these statements in TRY... CATCH
block here is what you need to remember.

Problem:

When Response.Redirect or Response.End is written in TRY block, code in catch block is executed.

Reason:

ASP.NET executes these 2 methods on Response object by throwing ThreadAbort Exception. When
written in simple Try...Catch block this results in Catch block catching this exception and processing code
written in catch block. This causes unwanted code execution e.g. error logging or genric error display code
which is generally written in Catch block.

Solution:

You need to handle ThreadAbort exception separately and do nothing if it is thrown. Refer following code
patch:

try
{
          // Your actual code

          Response.End();
}
catch (ThreadAbortException exc)
{
          // This should be first catch block i.e. before generic Exception
          // This Catch block is to absorb exception thrown by Response.End
}
catch (Exception exc)
{
            // Write actual error handling code here
}


      5. Server . transfer


Your website project has generated an error while your page load code is running. It may be because a bad
request was generated by the client. Use Server.Transfer to return a 404 error. Here we look at the
Server.Transfer method in ASP.NET and how it can improve your programs.

Example

Sometimes on a site it is best to assume things will go as planned, and handle "exceptional" problems with
try/catch. Here is a way to redirect to a 404 page in your ASP.NET project when an error occurs.

Example method [C#]

protected override void OnLoad(EventArgs e)
{
    string query = Request.QueryString["id"]; // for example
    ISitePage sitePage;
try
       {
         sitePage = new SitePageContent(this, query);
       }
       catch
       {
         // Hit when we don't have the key in the hash.
         Server.Transfer("~/404.aspx");
         return;
       }
}
404 pages

To solve the 404 problem, we can simply use Server.Transfer() to our 404 page and then return from the
OnLoad/Page_Load method. This saves a request from the browser, so the user waits less, and your server
does less work.

How to Use the Server.Transfer Method. This new method is an alternative to using the
Response.Redirect method to transfer to another page, and allows the transfer of the ASP built-in and
Error objects to a second page. In addition, the transfer takes place on the server instead of forcing the
browser to redirect to a new page.

Is it efficient?

Yes. It reduces work on your server—work that would be completely useless to your business. It results in
faster response times as well. This saves bandwidth and can be very helpful in some situations.

Summary

In this article, we looked at the Server.Transfer method. I tested this method and it does eliminate one
request from the browser. Server.Transfer is useful in many other situations, but this is an adequate
example of its use. The URL in the browser will remain the same.

    6. Server .execute

         The HttpServerUtility.Execute method executes a request to another page using the
         specified URL path to the page. The Execute method continues execution of the original
         page after execution of the new page is completed.
         e.g.
         Server.Execute(“ProcessTestAnswers.aspx”) ;

         Server.transfer :
         Terminates execution of the current page and begins execution of a new page for the
         current request.
         The page transferred to should be another Web Forms page (.aspx page) in the same
         application. You cannot use Server.Transfer to redirect to an .asp or .asmx page. Make
         sure that the target page exists. Because Server.Transfer is executed on the server, the
         browser does not have a record of the page change. Therefore, if the user refreshes the
         page, unexpected results can occur.
         e.g.
         Server.Transfer("Logon.aspx");

    7. How you can transfer value & data one page to another page
Introduction

       As developper We always come into situations in which we need to transfer values from one page
       to another page. In this article, I will show you some ways of transferring values from one page to
       another page. You can see how this work by visiting http://www.makaistudio.com/inquiry.aspx.

       Using Response.Redirect

       Let's first see how to transfer using Response.Redirect method. Let's says you have a text box with
       data in it when you Press the finish submit or finish button.

       Tip: Sometimes we want to transfer to another page inside the catch exception, meaning exception
       is caught and we want to transfer to another page. If you try to do this, it may give you a
       System.Threading exception. This exception is raised because you are transferring to another page
       leaving behind the thread running. You can solve this problem using:

       Response.Redirect("WebForm.aspx",false);

       This tells the compiler to go to page "WebForm.aspx", and "false" here means that don't end what
       you were doing on the current page. You should also look at the System.Threading class for
       threading issues. Below, you can see the C# code of the button event. "txtName" is the name of the
       text field whose value is being transferred to a page called "WebForm.aspx". "Name" which is just
       after "?" sign is just a temporary response variable which will hold the value of the text box.

       private void Button1_Click(object sender, System.EventArgs e)
       {
         // Value sent using HttpResponse
         Response.Redirect("WebForm.aspx?Name="+txtName.Text);
       }

       Now, where do I collect the values? First, we check that the value entered is not null. If it's not,
       then we simply display the value on the page using a Label control. Note: When you use
       Response.Redirect method to pass the values, all the values are visible in the URL of the browser.
       You should never pass credit card numbers and confidential information via Response.Redirect.

       if (Request.QueryString["Name"]!= null)
          Label3.Text = Request.QueryString["Name"];

   8. What will happen when exception occurs whether finalization with call or not


While reviewing some code this weekend, I had the thought to do a search for the following string
throughout the codebase, "catch(Exception" (using the regular expression search of course it looked more
like "catchs*(s*Exception").

My intent was to take a look to see how badly Catch(Exception...) was being abused or if it was being
used correctly. One interesting pattern I noticed frequently was the following snippet...

try
{
      fs = new FileStream(filename, FileMode.Create);
      //Do Something
}
catch(Exception ex)
{
throw ex;
}
finally
{
    if(fs != null)
        fs.Close();
}

My guess is that the developer who wrote this didn’t realize that you don’t need a catch block in order to
use a finally block. The finally block will ALWAYS fire whether or not there is an exception block. Also,
this code is resetting the callstack on the exception as I’ve written about before.

This really just should be.

try
{
      fs = new FileStream(filename, FileMode.Create);
      //Do Something
}
finally
{
    if(fs != null)
        fs.Close();
}

Another common mistake I found is demonstrated by the following code snippet.

try
{
      //Do Something.
}
catch(Exception e)
{
    throw e;
}

This is another example where the author of the code is losing stack trace information. Even worse, there
is no reason to even perform a try catch, since all that the developer is doing is rethrowing the exact
exception being caught. I ended up removing the try/catch blocks everywhere I found this pattern.

   9.Session Management in asp.net

Introduction

One of the core aspects that classic ASP developers (including me) always deal with when building
applications is handling state information. This task is made more difficult in Web applications because
HTTP is, by its very nature, a stateless protocol that doesn�t remember anything about a user between
requests.
The problem with user sessions in ASP

The stateless nature of HTTP makes the inclusion of a mechanism to save application state between user
requests a must�the server must be able to identify the same user across multiple requests. Classic ASP
included a Session object that accomplished this, but unfortunately, that implementation has two main
weaknesses.

First, the 120-bit session ID used to identify the session is always stored as a cookie on the browser. So, if
the security policy of a user's employer disallows cookies, the Session object cannot be populated.

Second, the data associated with the session and accessed through the session ID is stored on the Web
server that processed the initial request and started the session. As a result, the session data can�t be
shared in a web farm scenario where multiple web servers are processing requests from multiple clients.
Although programmatic techniques, and system software such as the Windows 2000 clustering services
and Application Center 2000, can be configured to force a client to access the same web server for each
request (referred to as �sticky IP�), the overhead and possible imbalance that this situation creates
reduces scalability.

                         ASP.NET�s improved model offers more alternatives.

The ASP.NET session implementation addresses both of these weaknesses by allowing for "cookieless"
sessions and off-server storage of session data. The ASP.NET session state module is configured
declaratively in the Web.config file like so:




   IT Service Management Office
   info@swpbiz.com
   www.swpbiz.com

More Related Content

Viewers also liked

0212.269.92.32- 0212.591.62.65 BOSCH Servis Tamir Bakım Montaj servisi Çamaşı...
0212.269.92.32- 0212.591.62.65 BOSCH Servis Tamir Bakım Montaj servisi Çamaşı...0212.269.92.32- 0212.591.62.65 BOSCH Servis Tamir Bakım Montaj servisi Çamaşı...
0212.269.92.32- 0212.591.62.65 BOSCH Servis Tamir Bakım Montaj servisi Çamaşı...
sertambak
 
0212.269.92.32- 0212.591.62.65 Servis Tamir Bakım Montaj Çamaşır makinesi, Bu...
0212.269.92.32- 0212.591.62.65 Servis Tamir Bakım Montaj Çamaşır makinesi, Bu...0212.269.92.32- 0212.591.62.65 Servis Tamir Bakım Montaj Çamaşır makinesi, Bu...
0212.269.92.32- 0212.591.62.65 Servis Tamir Bakım Montaj Çamaşır makinesi, Bu...
sertambak
 

Viewers also liked (8)

0212.269.92.32- 0212.591.62.65 BOSCH Servis Tamir Bakım Montaj servisi Çamaşı...
0212.269.92.32- 0212.591.62.65 BOSCH Servis Tamir Bakım Montaj servisi Çamaşı...0212.269.92.32- 0212.591.62.65 BOSCH Servis Tamir Bakım Montaj servisi Çamaşı...
0212.269.92.32- 0212.591.62.65 BOSCH Servis Tamir Bakım Montaj servisi Çamaşı...
 
Ig tn r-2009-243
Ig tn r-2009-243Ig tn r-2009-243
Ig tn r-2009-243
 
Số phân một con người
Số phân một con ngườiSố phân một con người
Số phân một con người
 
0212.269.92.32- 0212.591.62.65 Servis Tamir Bakım Montaj Çamaşır makinesi, Bu...
0212.269.92.32- 0212.591.62.65 Servis Tamir Bakım Montaj Çamaşır makinesi, Bu...0212.269.92.32- 0212.591.62.65 Servis Tamir Bakım Montaj Çamaşır makinesi, Bu...
0212.269.92.32- 0212.591.62.65 Servis Tamir Bakım Montaj Çamaşır makinesi, Bu...
 
Letras de musicas
Letras de musicasLetras de musicas
Letras de musicas
 
Constituição federal
Constituição federalConstituição federal
Constituição federal
 
CMSday 2013 - Doper votre audience en optimisant votre référencement ?
CMSday 2013 - Doper votre audience en optimisant votre référencement ?CMSday 2013 - Doper votre audience en optimisant votre référencement ?
CMSday 2013 - Doper votre audience en optimisant votre référencement ?
 
Matinale eZ Publish : la personnalisation dynamique
Matinale eZ Publish : la personnalisation dynamiqueMatinale eZ Publish : la personnalisation dynamique
Matinale eZ Publish : la personnalisation dynamique
 

Recently uploaded

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 

Asp net interview questions

  • 1. 1. Request and response We need a basic knowledge about what is Request & Response objects. The following information may be helpful to all. How beautifully these are handling things occurring in a Page class. Request and Response are the properties of the Page class. The Request property allows you to access the HTTPRequest object, which contains information,such as path of the request, about the HTTP request for the page. The Response property allows you to access the HTTPResponse object, which in turn allows you to send data to the browser as the result of the request. In fact, Request and Response properties map directly to HttpRequest and HttpResponse objects respectively. Therefore, you can directly access these objects in ASP.NET pages by using the Request and Response properties. Querystrings is the method of the HttpRequest object, which returns the parameter that's passed with the page URL. The Write method of the HTTPResponse object is used to display text in a browser. You can use the html formatting elements to format the text. 2. Applications Mobile gadgets such as cell phones and PDAs have become ubiquitous. Just about everyone today possesses a cell phone and most cell phones are equipped with features such as downloading ringtones, getting sports updates, news headlines and so forth. ASP.NET 2.0 enables you to easily create applications targeting such devices. The following links give you a head start on mobile application development with ASP.NET: • .NET Mobile Tutorial • Building Mobile Web Applications with .NET Mobile Web SDK & ASP.NET • ASP.NET For Mobiles • ASP.NET Mobile Web Development Overview • Introduction to ASP.NET Mobile • Code Project Article Since most developers will not actually use cellular devices to test their mobile applications, device emulators have been created by companies like Microsoft, Nokia and others for testing purposes. A device emulator is software that simulates a mobile device. The Visual Studio IDE includes built-in emulator SDKs for Pocket PC and SmartPhone. 3. Session ASP.NET Session state provides a place to store values that will persist across page requests. Values stored in Session are stored on the server and will remain in memory until they are explicitly removed or until the Session expires. Storing and retrieving a value in the Session is as simple as: VB
  • 2. Session("Name") = "John Doe"'orSession.Add("Name","John Doe")'retrieving Dim Name As String = Session("Name") C# Session["Name"] = "John Doe";//orSession.Add("Name","John Doe");//retrievingstring Name = (string)Session["Name"]; By default the Session will be created within the same process that your web site runs in (InProc). This is controlled by a setting in the web.config file: <sessionState mode="InProc" /> Although running the Session In Process is very convenient, it does mean that all Session values will be lost whenever the application recycles (such as when deploying updates) . There are alternate modes you can use that will allow the Session state to survive even when the application recycles. The available options are: • Off - No session state will be stored • InProc - (The Default) Session state exists within the process the web is using • StateServer - Session data is sent to the configured stateserver service • SQLServer - Session data is store in the configured sql server database Both the StateServer mode and the SQLServer mode allow Session state to survive an application recycle. But, when storing reference type objects (such as class instances), they can only be stored to StateServer or SQLServer if they have been marked with the Serializable attribute. An important consideration for using Session state is that the Session does expire. By default, if a user does not access their Session data within 20 minutes (by default), the Session will expire and all items that had been stored in the Session will be discarded. Because of this, it is important to check the object that is returned from the Session to see if it exists or if it is null before you try to work with it. For example: object sessionObject = Session["someObject"]; if (sessionObject != null) { myLabel.Text = sessionObject.ToString(); } The Session Timeout is adjustable through a web.config setting but increasing the timeout value can put memory pressure on your server that may be undesirable. <sessionState timeout="number of minutes" /> Other commonly used Session methods are: • Session.Abandon() - removes the Session and all items that it contains • Session.Clear() - removes all items from the Session • Session.RemoveAll() - removes all items from the Session • Session.Remove("itemName") - removes the item that was stored under the name "itemName" 4. Response .redirect
  • 3. Using Response.Redirect and Response.End in Try...Catch block In ASP.NET if you are using Response.End - Used for terminating page execution or Response.Redirect - used for redirecting page to some other page, and you are including these statements in TRY... CATCH block here is what you need to remember. Problem: When Response.Redirect or Response.End is written in TRY block, code in catch block is executed. Reason: ASP.NET executes these 2 methods on Response object by throwing ThreadAbort Exception. When written in simple Try...Catch block this results in Catch block catching this exception and processing code written in catch block. This causes unwanted code execution e.g. error logging or genric error display code which is generally written in Catch block. Solution: You need to handle ThreadAbort exception separately and do nothing if it is thrown. Refer following code patch: try { // Your actual code Response.End(); } catch (ThreadAbortException exc) { // This should be first catch block i.e. before generic Exception // This Catch block is to absorb exception thrown by Response.End } catch (Exception exc) { // Write actual error handling code here } 5. Server . transfer Your website project has generated an error while your page load code is running. It may be because a bad request was generated by the client. Use Server.Transfer to return a 404 error. Here we look at the Server.Transfer method in ASP.NET and how it can improve your programs. Example Sometimes on a site it is best to assume things will go as planned, and handle "exceptional" problems with try/catch. Here is a way to redirect to a 404 page in your ASP.NET project when an error occurs. Example method [C#] protected override void OnLoad(EventArgs e) { string query = Request.QueryString["id"]; // for example ISitePage sitePage;
  • 4. try { sitePage = new SitePageContent(this, query); } catch { // Hit when we don't have the key in the hash. Server.Transfer("~/404.aspx"); return; } } 404 pages To solve the 404 problem, we can simply use Server.Transfer() to our 404 page and then return from the OnLoad/Page_Load method. This saves a request from the browser, so the user waits less, and your server does less work. How to Use the Server.Transfer Method. This new method is an alternative to using the Response.Redirect method to transfer to another page, and allows the transfer of the ASP built-in and Error objects to a second page. In addition, the transfer takes place on the server instead of forcing the browser to redirect to a new page. Is it efficient? Yes. It reduces work on your server—work that would be completely useless to your business. It results in faster response times as well. This saves bandwidth and can be very helpful in some situations. Summary In this article, we looked at the Server.Transfer method. I tested this method and it does eliminate one request from the browser. Server.Transfer is useful in many other situations, but this is an adequate example of its use. The URL in the browser will remain the same. 6. Server .execute The HttpServerUtility.Execute method executes a request to another page using the specified URL path to the page. The Execute method continues execution of the original page after execution of the new page is completed. e.g. Server.Execute(“ProcessTestAnswers.aspx”) ; Server.transfer : Terminates execution of the current page and begins execution of a new page for the current request. The page transferred to should be another Web Forms page (.aspx page) in the same application. You cannot use Server.Transfer to redirect to an .asp or .asmx page. Make sure that the target page exists. Because Server.Transfer is executed on the server, the browser does not have a record of the page change. Therefore, if the user refreshes the page, unexpected results can occur. e.g. Server.Transfer("Logon.aspx"); 7. How you can transfer value & data one page to another page
  • 5. Introduction As developper We always come into situations in which we need to transfer values from one page to another page. In this article, I will show you some ways of transferring values from one page to another page. You can see how this work by visiting http://www.makaistudio.com/inquiry.aspx. Using Response.Redirect Let's first see how to transfer using Response.Redirect method. Let's says you have a text box with data in it when you Press the finish submit or finish button. Tip: Sometimes we want to transfer to another page inside the catch exception, meaning exception is caught and we want to transfer to another page. If you try to do this, it may give you a System.Threading exception. This exception is raised because you are transferring to another page leaving behind the thread running. You can solve this problem using: Response.Redirect("WebForm.aspx",false); This tells the compiler to go to page "WebForm.aspx", and "false" here means that don't end what you were doing on the current page. You should also look at the System.Threading class for threading issues. Below, you can see the C# code of the button event. "txtName" is the name of the text field whose value is being transferred to a page called "WebForm.aspx". "Name" which is just after "?" sign is just a temporary response variable which will hold the value of the text box. private void Button1_Click(object sender, System.EventArgs e) { // Value sent using HttpResponse Response.Redirect("WebForm.aspx?Name="+txtName.Text); } Now, where do I collect the values? First, we check that the value entered is not null. If it's not, then we simply display the value on the page using a Label control. Note: When you use Response.Redirect method to pass the values, all the values are visible in the URL of the browser. You should never pass credit card numbers and confidential information via Response.Redirect. if (Request.QueryString["Name"]!= null) Label3.Text = Request.QueryString["Name"]; 8. What will happen when exception occurs whether finalization with call or not While reviewing some code this weekend, I had the thought to do a search for the following string throughout the codebase, "catch(Exception" (using the regular expression search of course it looked more like "catchs*(s*Exception"). My intent was to take a look to see how badly Catch(Exception...) was being abused or if it was being used correctly. One interesting pattern I noticed frequently was the following snippet... try { fs = new FileStream(filename, FileMode.Create); //Do Something } catch(Exception ex) {
  • 6. throw ex; } finally { if(fs != null) fs.Close(); } My guess is that the developer who wrote this didn’t realize that you don’t need a catch block in order to use a finally block. The finally block will ALWAYS fire whether or not there is an exception block. Also, this code is resetting the callstack on the exception as I’ve written about before. This really just should be. try { fs = new FileStream(filename, FileMode.Create); //Do Something } finally { if(fs != null) fs.Close(); } Another common mistake I found is demonstrated by the following code snippet. try { //Do Something. } catch(Exception e) { throw e; } This is another example where the author of the code is losing stack trace information. Even worse, there is no reason to even perform a try catch, since all that the developer is doing is rethrowing the exact exception being caught. I ended up removing the try/catch blocks everywhere I found this pattern. 9.Session Management in asp.net Introduction One of the core aspects that classic ASP developers (including me) always deal with when building applications is handling state information. This task is made more difficult in Web applications because HTTP is, by its very nature, a stateless protocol that doesn�t remember anything about a user between requests.
  • 7. The problem with user sessions in ASP The stateless nature of HTTP makes the inclusion of a mechanism to save application state between user requests a must�the server must be able to identify the same user across multiple requests. Classic ASP included a Session object that accomplished this, but unfortunately, that implementation has two main weaknesses. First, the 120-bit session ID used to identify the session is always stored as a cookie on the browser. So, if the security policy of a user's employer disallows cookies, the Session object cannot be populated. Second, the data associated with the session and accessed through the session ID is stored on the Web server that processed the initial request and started the session. As a result, the session data can�t be shared in a web farm scenario where multiple web servers are processing requests from multiple clients. Although programmatic techniques, and system software such as the Windows 2000 clustering services and Application Center 2000, can be configured to force a client to access the same web server for each request (referred to as �sticky IP�), the overhead and possible imbalance that this situation creates reduces scalability. ASP.NET�s improved model offers more alternatives. The ASP.NET session implementation addresses both of these weaknesses by allowing for "cookieless" sessions and off-server storage of session data. The ASP.NET session state module is configured declaratively in the Web.config file like so: IT Service Management Office info@swpbiz.com www.swpbiz.com