1. Request and responseWe need a basic knowledge about what is Request & Response objects. The following information may b...
Session("Name") = "John Doe"orSession.Add("Name","John Doe")retrievingDim Name As String = Session("Name")       C#Session...
Using Response.Redirect and Response.End in Try...Catch blockIn ASP.NET if you are using Response.End - Used for terminati...
try       {         sitePage = new SitePageContent(this, query);       }       catch       {         // Hit when we dont h...
Introduction       As developper We always come into situations in which we need to transfer values from one page       to...
throw ex;}finally{    if(fs != null)        fs.Close();}My guess is that the developer who wrote this didn’t realize that ...
The problem with user sessions in ASPThe stateless nature of HTTP makes the inclusion of a mechanism to save application s...
Upcoming SlideShare
Loading in...5

Asp net interview questions


Published on

asp net interview questions and answers

Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Asp net interview questions

  1. 1. 1. Request and responseWe need a basic knowledge about what is Request & Response objects. The following information may behelpful 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 youto access the HTTPRequest object, which contains information,such as path of the request, about theHTTP request for the page. The Response property allows you to access the HTTPResponse object, whichin 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 HttpResponseobjects respectively. Therefore, you can directly access these objects in ASP.NET pages by using theRequest and Response properties. Querystrings is the method of the HttpRequest object, which returns the parameter thatspassed with the page URL. The Write method of the HTTPResponse object is used to display text in abrowser. You can use the html formatting elements to format the text. 2. ApplicationsMobile gadgets such as cell phones and PDAs have become ubiquitous. Just about everyone todaypossesses 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 applicationstargeting 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 ArticleSince most developers will not actually use cellular devices to test their mobile applications, deviceemulators have been created by companies like Microsoft, Nokia and others for testing purposes. A deviceemulator is software that simulates a mobile device. The Visual Studio IDE includes built-in emulatorSDKs for Pocket PC and SmartPhone. 3. SessionASP.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 explicitlyremoved or until the Session expires.Storing and retrieving a value in the Session is as simple as: VB
  2. 2. Session("Name") = "John Doe"orSession.Add("Name","John Doe")retrievingDim Name As String = Session("Name") C#Session["Name"] = "John Doe";//orSession.Add("Name","John Doe");//retrievingstringName = (string)Session["Name"];By default the Session will be created within the same process that your web site runs in (InProc). This iscontrolled 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 belost whenever the application recycles (such as when deploying updates) . There are alternate modes youcan use that will allow the Session state to survive even when the application recycles. The availableoptions 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 databaseBoth 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 orSQLServer 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 userdoes not access their Session data within 20 minutes (by default), the Session will expire and all items thathad been stored in the Session will be discarded. Because of this, it is important to check the object thatis 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 putmemory 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. 3. Using Response.Redirect and Response.End in Try...Catch blockIn 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... CATCHblock 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. Whenwritten in simple Try...Catch block this results in Catch block catching this exception and processing codewritten in catch block. This causes unwanted code execution e.g. error logging or genric error display codewhich is generally written in Catch block.Solution:You need to handle ThreadAbort exception separately and do nothing if it is thrown. Refer following codepatch: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 . transferYour website project has generated an error while your page load code is running. It may be because a badrequest was generated by the client. Use Server.Transfer to return a 404 error. Here we look at theServer.Transfer method in ASP.NET and how it can improve your programs.ExampleSometimes on a site it is best to assume things will go as planned, and handle "exceptional" problems withtry/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. 4. try { sitePage = new SitePageContent(this, query); } catch { // Hit when we dont have the key in the hash. Server.Transfer("~/404.aspx"); return; }}404 pagesTo solve the 404 problem, we can simply use Server.Transfer() to our 404 page and then return from theOnLoad/Page_Load method. This saves a request from the browser, so the user waits less, and your serverdoes less work.How to Use the Server.Transfer Method. This new method is an alternative to using theResponse.Redirect method to transfer to another page, and allows the transfer of the ASP built-in andError objects to a second page. In addition, the transfer takes place on the server instead of forcing thebrowser 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 infaster response times as well. This saves bandwidth and can be very helpful in some situations.SummaryIn this article, we looked at the Server.Transfer method. I tested this method and it does eliminate onerequest from the browser. Server.Transfer is useful in many other situations, but this is an adequateexample 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. 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 Lets first see how to transfer using Response.Redirect method. Lets 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 dont 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 its 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 notWhile reviewing some code this weekend, I had the thought to do a search for the following stringthroughout the codebase, "catch(Exception" (using the regular expression search of course it looked morelike "catchs*(s*Exception").My intent was to take a look to see how badly Catch(Exception...) was being abused or if it was beingused correctly. One interesting pattern I noticed frequently was the following snippet...try{ fs = new FileStream(filename, FileMode.Create); //Do Something}catch(Exception ex){
  6. 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 touse 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, thereis no reason to even perform a try catch, since all that the developer is doing is rethrowing the exactexception being caught. I ended up removing the try/catch blocks everywhere I found this pattern. 9.Session Management in asp.netIntroductionOne of the core aspects that classic ASP developers (including me) always deal with when buildingapplications is handling state information. This task is made more difficult in Web applications becauseHTTP is, by its very nature, a stateless protocol that doesn�t remember anything about a user betweenrequests.
  7. 7. The problem with user sessions in ASPThe stateless nature of HTTP makes the inclusion of a mechanism to save application state between userrequests a must�the server must be able to identify the same user across multiple requests. Classic ASPincluded a Session object that accomplished this, but unfortunately, that implementation has two mainweaknesses.First, the 120-bit session ID used to identify the session is always stored as a cookie on the browser. So, ifthe security policy of a users 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 Webserver that processed the initial request and started the session. As a result, the session data can�t beshared 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 servicesand Application Center 2000, can be configured to force a client to access the same web server for eachrequest (referred to as �sticky IP�), the overhead and possible imbalance that this situation createsreduces 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 configureddeclaratively in the Web.config file like so: IT Service Management Office info@swpbiz.com www.swpbiz.com