转载: .net程序员偏向ASP.NET的面试题

转载自: http://harshthakur.com/blog/

 

Q1. Describe the role of inetinfo.exe, aspnet_isapi.dll, and aspnet_wp.exe in the page loading process.

Short answer

inetinfo.exe receives the incoming request from the client and passes it to aspnet_isapi.dll since aspnet_isapi.dll is registered as the ISAPI extension that handles all the standard ASP .NET file extensions like .aspx, .asmx, .ashx, etc. aspnet_isapi.dll launches aspnet_wp.exe, the ASP .NET worker process, if it is not already running and hands over the request to it. The worker process creates an app domain and loads the HTTP pipeline. The HTTP pipeline passes the request through any registered HTTP modules and instructs the page (the HTTP handler) to process the request and generate the response. The response is returned to inetinfo.exe through aspnet_isapi.dll and thence to the client.

Long answer

Coming soon...

Q2. What events are fired during a page's lifecycle?

Well, a lot of them. Especially if it's ASP .NET 2.0. But the key ones are:

  • Init - The page object is created in memory and initialized. Initialization includes creating the control hierarchy and adding it to the page's control collection, wiring the event handlers, setting default properties etc.
  • LoadViewState - The controls are given a chance to load their ViewState.
  • ProcessPostData - The page examines the post data to determine what caused the postback.
  • Load - Meant for the developers. This is where you put your code to do your stuff in the page. Checking the IsPostBack property is useful if you want to avoid doing some operations each time the page loads.
  • RaisePostBackEvent - After examining the post data, the page raises any events that might be required.
  • PreRender - This is the last chance the developer gets to modify the page's output in any way by updating the server controls. Any changes to the control's view state can be saved.
  • Render - This method is actually protected so the developer cannot do much about it. But it's useful from an understanding perspective. The page object walks down it's controls collection, calling Render on each one of them and passing the same instance of HtmlTextWriter.
  • SaveViewState - The controls get a chance to persist their ViewState.
  • Unload - Called just before the page object is unloaded. This is where developers can write their cleanup code.

Q3. What is event bubbling?

Simply put, to bubble an event means to propagate the event upwards in the control hierarchy and allow one of the parent controls to handle it. For example, let's say there is a DataGridView control that has a LinkButton column and it is desired that the DataGridView also be able to respond to the click of the LinkButton. Normally, when the button is clicked, only it will be notified. If the DataGridView also needs to do something on the click of the LinkButton, it needs to be notified that the click occurred. This is best achieved by allowing the event to Bubble up through the control hierarchy.

Q4. Should user input data validation occur server-side or client-side?

User input data validation must happen on the server-side. Typically, it is also useful to perform the validation on the client-side so as to avoid unnecessary post backs and provide a more responsive UI. Imagine a page with a lot of input controls that does validations only on post backs. That's a sure way to loose your customers.

Q5. What is the difference between Response.Redirect() & Server.Transfer()? Why should I choose one over the other?

This one always brings a smile to my face. I had posted this question on the microsoft.public.dotnet.framework.aspnet newsgroup way back when I used to work at a company called Cybage. In fact, if you do a search on Google Groups for Harsh Thakur that is the first link that comes up. Today, I can add a little bit more to that answer so here goes:

An ASP .NET Response.Redirect() causes IIS to send a 302 Redirect Header to the browser. This is pretty much like telling the browser that the requested content has moved to a different url and it should go and load that. On the other hand, a Server.Transfer() works very differently. The moment ASP .NET encounters a Server.Transfer(), it calls End() on the Response (HttpResponse) object which in turn raises the EndRequest event and causes the thread that is processing the page to be aborted. As a result, a ThreadAbortException is also thrown and this should be just caught and ignored. ASP .NET then transfers control to the page mentioned in Server.Transfer().

Let us now consider the ramifications of all this. Response.Redirect() has a performance penalty since it causes a round-trip to the server since the browser was initially loading one page and then was instructed to go load a different page. So the browser sends 2 requests instead of 1. On the other hand, since the browser knows it received a 302 Redirect Header, it knows what the new page that it loaded is and hence adding to favourites works fine. Also, since the browser is aware that it has to load the new page, one can do a Response.Redirect() to any URI on the web. Even to a machine running Apache on Linux. On the other hand, since a Server.Transfer() happens on the server itself, there is no performance penalty. Moreover, the new page can access the context of the old page. This is incredibly useful in many cases, for example, in wizards with multiple pages. On the flip side, since the Transfer happens on the server, one cannot do a Server.Transfer() to a different machine. Also, since the browser never realizes that it was in fact served a different page, the browser will still display the URI of the originally requested page. This causes problems with bookmarking etc. Also, ASP .NET does not rerun the authentication and authorization logic for the new page. But this is not usually a problem since the security checks were already performed for the original request.

To summarize, if performance is important, use Server.Transfer(). If you want to be able to redirect to anywhere on the web or if bookmarking is important to your users use Response.Redirect().

Q6. What is the purpose of Global.asax?

Global.asax can be used to define Application and Session level events. The key ones are:

  • Application_Start & Application_End - Can be used for performing operations that are required when the application starts up or shuts down.
  • Application_Error - Can be used as a centralized error handler. For example, one can redirect the user to a central error page and avoid the need for putting this code in every page.
  • Session_Start & Session_End - Session_Start is raised whenever a new Session is started. A new Session starts when a browser on a different machine or a new instance of the browser on the same machine makes a request. Session_End is only raised if sessionState mode="InProc" in the web.config.
  • Application_BeginRequest & Application_EndRequest - These events are raised whenever a new request is received and the response sent back.

Q7. Compare ASP and ASP .NET

The first and most important difference is that ASP was interpreted whereas ASP .NET is compiled. Even the HTML in the .aspx file is compiled into a temporary assembly. This obviously means a tremendous performance boost and also much better scalability.

The second important difference is the increase in developer productivity due to the segregation of the HTML/JavaScript and the C#/VB code into separate files a.k.a. the Code-behind model. Even more so with the advent of partial classes with .NET 2.0. This results in cleaner code that is easier to understand.

The other differences have to do with the much greater variety of standard controls, the much better tool support, and the much greater flexibility in the HTTP pipeline.


 

Q8. What is ViewState?

Simply put, ViewState is a mechanism that allows ASP .NET server controls to maintain their state between postbacks.

ASP .NET works over HTTP and HTTP is a state-less protocol. This means there is nothing in the protocol itself that allows it to remember the state of a page as it is served to a client. To illustrate, imagine a page with a text box for entering an email address and a drop down list that allows the user to select a city from a list. By default, the developer (who created the drop down list) would default the selected value in the drop down list to "Select a city" or some such value. Imagine a scenario where the user selects a city, say New York, and submits the page without entering the email address. What would happen? The page would be re-displayed to the user along with an error message saying that he forgot to enter the email address. But what would happen to the city (New York) that he selected in the drop down list? His selection would vanish and be replaced with the default, "Select a city".

To avoid this situation, the developer has a number of options. First approach, he could perform all validations on the client side as well as the server side. The problem with this approach is that there will always be some validations that cannot be performed on the client side. A second approach could be that upon a submit, he could take the selected value from the drop down list and store it somewhere, say in a hidden form field. When the page is re-displayed, he could use some JavaScript to take the value from the hidden field and re-do the selection in the drop down list. But this means writing extra code. And imagine what would happen if there are a whole lot of input controls, including multiple drop down lists. You've got a coding and maintenance nightmare.

This is where ViewState comes to the rescue. What happens is something like this; Remember the SaveViewState event from Q2. Well, in this event ASP .NET walks down the control hierarchy in the page and asks each control, "Hey, do you want to save something before I send the page out to the client?". Interested controls say yes and then they pass the data as key-value pairs to the page. The page collects all the key-value pairs for all the controls and saves it to a hidden form field called __VIEWSTATE. When the page is submitted, ASP .NET again walks down the control hierarchy in the page, this time in the LoadViewState event. ASP .NET asks each control, "Hey, if you saved some data during SaveViewState this is your chance to recover that data." And it takes the key-value pairs from the hidden form field and passes them to each control. The controls then take whatever key-value pairs they had saved and use them to recover their state or to raise post back events or do other processing.

So , the ASP .NET ViewState implementation is not much different from the 2nd approach mentioned above. But it saves us developers from a lot of unnecesary effort, at least when working with standard ASP .NET controls. Of course, if you're creating a custom ASP .NET server control, you'll have to use the Save and Load ViewState events to persist your key-value pairs. But that's it. ASP .NET takes care of the rest.

Q9. What are the advantages & pitfalls of using ViewState?

The advantages of ViewState:

  • The careful use of ViewState can help the developer avoid a lot of plumbing code and instead focus on the business challenges. If required, one can always disable/enable ViewState at the page level or the control level.
  • The developer can also use ViewState to store values. (C# - ViewState["VARNAME"] = VALUE;)
  • The scope of data stored in the ViewState is limited to the page. This means one does not have to worry about cleanup as in the case of data stored in the Session.

The pitfalls of using ViewState:

  • Since ViewState is stored on the client side, it does a round trip from the server to the client for each page load or postback. This means we should watch the size of ViewState very carefully for each page that uses it. Because an increase in the ViewState would mean more load on the network and slower response times. Since a developer can also store data in the ViewState, one should be doubly careful not to abuse it.
  • ViewState is ultimately persisted to a hidden form field and this means that the key-value pairs need to be serialized. One ramification of this is that only serializable objects may be stored in ViewState. The second ramification is that it can have an adverse effect on performance since the objects in ViewState will have to serialized\de-serialized on every round-trip.

Q10. Is ViewState secure by default? Can it be secured? How?

By default, the value of the __VIEWSTATE hidden form field is Base64 encoded and not encrypted. Hence, by default data in ViewState is not secure.

Yes, data in the ViewState can be secured. There are two things that may be done. The first is to use SSL. The second is to ensure that EnableViewStateMac is set to true. This will ensure that the ViewState will be encrypted and also checked against tampering. The default encryption algorithm is SHA1 but it can be changed to MD5 or 3DES, if desired.
That said, one should bear in mind that there is almost always a trade-off between increased security and performance. It is best to avoid storing sensitive data in the ViewState and incurring the performance penalities due to the need to increase security.

Q11. ViewState is never used on the client side. Then why is ViewState stored on the client side?

ViewState is stored on the client side simply to avoid consuming critical server resources.
It is of course possible to over-ride the default ViewState persistence mechanism and instead store ViewState on the server. But this is unlikely to bring any real benefits except maybe in some rare cases. It can also get very tricky. In fact it is very likely that vast benefits may be obtained by just making sure that ViewState is used intelligently and turned off wherever it's not required.

Q12. Describe how a browser-based Form POST becomes a Server-Side event like Button1_OnClick.

Let's start with the known fact that the browser only understands HTML and JavaScript. It has no idea about something called ASP .NET. Or PHP for that matter. This would lead us to the logical conclusion that under the covers ASP .NET must be doing something with HTML and JavaScript that allows it to recognize which control was "clicked" on the client side and accordingly raise the corresponding server-side events like the OnClick event for Button1 etc. So where do we start? We start by loading an ASP .NET page that has some server controls (say, a DropDownList with AutoPostBack=true) into a browser and then saying "View Source". When we look at the source we see a number of hidden fields like __EVENTTARGET, __EVENTARGUMENT, and __VIEWSTATE. We already know what __VIEWSTATE is used for. But what are the other ones used for? Let's look for more clues. We scroll down further and look at the DropDownList control. We know a bit of JavaScript and see the DropDownList control has some JavaScript code for the onchange event. Now we seem to be getting somewhere because we know that there is a server-side event handler for the SelectedIndexChanged event. So there must be a connection and this is where it must be. We look further and realize that the JavaScript code is calling some JavaScript function called __doPostBack and passing it's own id as one of the arguments. Okay, so now we go and look for that __doPostBack function and sure enough we find it near the top. And what does the JavaScript function do? It assigns the value of the arguments to the hidden fields __EVENTTARGET and __EVENTARGUMENT and just does a form.submit(). Hmmm...we sit back, think about it for a while and then we have the answer.
So this is what happens. When the user changes the selection in the DropDownList, the JavaScript event onchange is fired. The code that executes is the __doPostBack function which just sets the __EVENTTARGET and __EVENTARGUMENT fields and submits the form to the server. On the server, there must be some code that checks the value of these two fields and figures out that the DropDownList caused the post back. It then uses the id value in __EVENTTARGET and finds a corresponding server side control and raises the SelectedIndexChanged event for the control. And something similar must also be happening for the button click. In fact, in the case of a Button, it's much simpler. The fields __EVENTTARGET and __EVENTARGUMENT are not even used because ASP .NET renders the Button as an HTML submit control. So it implicitly knows which control triggered the post back and accordingly it raises the OnClick event on the server side.

Q13. What is a PostBack?

Simply put, a PostBack is the action of a page that is submitting to itself on the server. ASP .NET pages are submitted to the server by using the HTTP POST method and hence the name. To illustrate, Page1.aspx is sent from server to browser. The user clicks a button on Page1.aspx. The browser POSTs the page back to the server where it is again handled by Page1.aspx.

 

 

 

Q14. What is the <machinekey> element and what two ASP.NET technologies is it used for?

The <machinekey> element is an ASP.NET configuration element that controls the encryption and decryption of forms authentication cookie data and view-state data, and for verification of out-of-process session state identification.

As mentioned above, the ASP.NET technologies it is used for are Session and ViewState.

Normally you don't have to worry about it but this element becomes really important when you're working with a Web Farm scenario.

I'll be adding some more details about this so do check back later.

Q15. What different Session State modes are available in ASP.NET?

ASP.NET supports the following Session State modes:

  • Off: Session state is disabled.
  • InProc: Stores session state in memory on the Web server. This is the default.
  • StateServer: Stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • SQLServer: Stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • Custom: Session state is stored in a custom data store.

Q16. Compare the Session State providers available in ASP.NET.

In-Process:

Pros:

  • The only provider that supports the Session_OnEnd event.
  • Since it stores state in the same process any type of object may be stored. No serialization requirement.
  • Fastest since it's in the same process and doesn't require the objects to be serialized.

Cons:

  • Not durable - session state is lost if the worker process is recycled or on IIS/Server restarts.
  • Cannot be used in Web Farm scenarios.
  • Can hurt performance if too much data is stored in the Session since server memory consumption will increase.

State Server:

Pros:

  • Slower than In-Proc but faster than SQL Server, especially if the state server runs on a different machine.
  • More durable than In-Proc and can survive worker process recycling or IIS restarts.
  • Can be used in Web Farm scenarios.

Cons:

  • Requires that the objects stored in Session be serializable.
  • Cannot survive machine restarts.
  • Increased configuration overheads.
  • Single point of failure since it does not provide any failover mechanism.

SQL Server:

Pros:

  • Completely durable and can even survive SQL Server restarts.
  • Can be used in Web Farm scenarios.
  • Supports failover through SQL Server failover clusters.

Cons:

  • Requires that the objects stored in Session be serializable.
  • Slowest.
  • Increased configuration overheads.

Q17. What is Web Gardening? How would using it affect a design?

Web Gardening is using multiple CPUs on the same web server to process ASP.NET requests by launching multiple worker processes. Normally, even on a multi CPU machine only one CPU is used to process ASP.NET requests. But it is possible to distribute the load among different CPUs by using the <processModel> section of the machine.config file.

One should keep in mind the following design considerations when working with a Web Garden:

  • The decision on how many CPUs to use must be carefully weighed in light of the number of services running on the server. For example, it would not make sense to devote all CPUs to ASP.NET if you also have an SQL Server running on the same server.
  • All processes will have their own copy of application state, in-process session state, ASP.NET cache, static data, and all that is needed to run applications. This means the more stateful the applications are the more they risk to pay in terms of real performance. It would probably be best to use an Out-of-Process Session State provider but that would have its own performance impact.
  • The <processModel> section is the only configuration section that cannot be placed in an application-specific web.config file. This means that the Web garden mode applies to all applications running on the machine. It is, of course, possible to adapt machine-wide settings on a per-application basis by using the <location> node in the machine.config.

All in all, careful application benchmarking is an absolute must before deciding whether to go with a Web Garden based model. In all likelihood it would be far cheaper to just use multiple servers coupled with a load-balancer. Since the cost of all that benchmarking would almost certainly be more than the cost of putting in additional servers.

Q18. Given one ASP.NET application, how many application objects does it have on a single proc box? A dual? A dual with Web Gardening enabled? How would this affect a design?

The HttpRuntime maintains a pool of HttpApplication objects for processing requests. Each HttpApplication object handles only one request at one time. Each request is handled on a different thread by using an HttpApplication object from the pool. The number of concurrent threads is specified in the processModel section of the machine.config file by the maxWorkerThreads element. The default value for this element is 20. Further, this value is specified on a per-CPU basis. So on any box, whether single proc or multiple procs, the maximum number of application objects will be 20, unless of course, a different value is supplied.

Of course, with Web Gardening enabled, the situation changes. The number of application objects will be maxWorkerThreads * number of CPUs. The design considerations are similar to those generally applicable to Web Gardening. For a detailed treatment of this topic and ASP.NET performance in general visit this page.

Q19. Are threads reused in ASP.NET between requests? Does every HttpRequest get its own thread? Should you use Thread Local storage with ASP.NET?

Yes. But only one request is processed on each thread at one time. So each HttpRequest gets it's own thread. Also, it should be noted that these are .NET Thread Pool threads and not Windows threads.

The answer to the last part should be obvious from the fact that the threads in question are .NET Thread Pool threads and not Windows threads. And the answer is... you guessed it, No! Since ASP.NET uses .NET Thread Pool threads, it's quite possible that thread switching may happen and you would loose the information stored in TLS (Thread Local Storage).

 

 

 

 

posted on 2010-01-02 06:05  林大虾  阅读(555)  评论(1编辑  收藏  举报

导航