ASP.NET FAQ's: Part 2

Introduction

In this section we will touch base on one of important concepts in ASP. Net.

For ASP.NET FAQ's - Part I

Happy job hunting...... 

(I) Do session use cookies?

Twist:- How can we make session to not to use cookies ?

Left to the user, you will enjoy to find this answer.

(I) How can we force all the validation control to run?

Page.Validate

(B) How can we check if all the validation control are valid and proper?

Using the Page.IsValid () property you can check whether all the validation are done.

(A) If client side validation is enabled in your Web page, does that mean server side code is not run.

When client side validation is enabled server emit's JavaScript code for the custom validators. However, note that does not mean that server side checks on custom validators do not execute. It does this redundant check two times, as some of the validators do not support client side scripting.

(A)Which JavaScript file is referenced for validating the validators at the client side?

WebUIValidation.js JavaScript file installed at "aspnet_client" root IIS directory is used to validate the validation controls at the client side

 (B)How to disable client side script in validators?

Set 'EnableClientScript' to false.

 (A)How can I show the entire validation error message in a message box on the client side?

In validation summary set "ShowMessageBox" to true.

 (B)You find that one of your validations is very complicated and does not fit in any of the validators, what will you do?

Best is to go for CustomValidators. Below is a sample code for a custom validator, which checks that a textbox should not have zero value

<asp:CustomValidator id="CustomValidator1" runat="server"
ErrorMessage="Number not divisible by Zero"
ControlToValidate="txtNumber"
OnServerValidate="ServerValidate"
ClientValidationFunction="CheckZero" /><br>

Input:

<asp:TextBox id="txtNumber" runat="server" />
<script language="javascript">
<!--function CheckZero(source, args) {
int val = parseInt(args.Value, 10);
if (value==0) {
args.
IsValid = false;
}
}
// -->
</script>

(I)What exactly happens when ASPX page is requested from a browser?

Note: - Here the interviewer is expecting complete flow of how an ASPX page is processed with respect to IIS and ASP.NET engine.

Following are the steps which occur when we request a ASPX page :-

The browser sends the request to the webserver. Let us assume that the webserver at the other end is IIS.

Once IIS receives the request he looks on which engine can serve this request.When we mean engine means the DLL who can parse this page or compile and send a response back to browser. Which request to map to is decided by file extension of the page requested.

Depending on file extension following are some mapping

  • .aspx, for ASP.NET Web pages,
  • .aspx, for ASP.NET Web pages,
  • .asmx, for ASP.NET Web services,
  • .config, for ASP.NET configuration files,
  • .ashx, for custom ASP.NET HTTP handlers,
  • .rem, for remoting resources

You can also configure the extension mapping to which engine can route by using the IIS engine.

 
Figure: - 7.1 following screen shows some IIS mappings

Example an ASP page will be sent to old classic ASP.DLL to compile. While .ASPX pages will be routed to ASP.NET engine for compilation.

  • As this book mainly will target ASP.NET we will look in to how ASP.NET pages that is ASPX pages generation sequence occurs. Once IIS passes the request to ASP.NET engine page has to go through two section HTTP module section and HTTP handler section. Both these section have there own work to be done in order that the page is properly compiled and sent to the IIS. HTTP modules inspect the incoming request and depending on that, they can change the internal workflow of the request. HTTP handler actually compiles the page and generates output. If you see your machine.config file you will see following section of HTTP modules

    <httpModules>
    <add name="OutputCache" type="System.Web.Caching.OutputCacheModule" />
    <add name="Session" type="System.Web.SessionState.SessionStateModule" />
    <add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule" />
    <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
    <add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule" />
    <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
    <add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule" />
    <add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule,
    System.Web.Mobile, Version=1.0.5000.0,
    Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </httpModules>


    The above mapping will show which Namespace handles which functionality. Example FormsAthuentication is handled by "System. Web.
    Security.FormsAuthenticationModule". If you look at the web.config, section HTTP module is where authentication and authorization happens.

    Ok now the HTTP handler is where the actual compilation takes place and the output is generated. Following is a paste from HTTP handler section of WEB.CONFIG file.

    <httpHandlers>
    <add verb="*" path="*.vjsproj" type="System.Web.HttpForbiddenHandler" />
    <add verb="*" path="*.java" type="System.Web.HttpForbiddenHandler" />
    <add verb="*" path="*.jsl" type="System.Web.HttpForbiddenHandler" />
    <add verb="*" path="trace.axd" type="System.Web.Handlers.TraceHandler" />
    <add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory" />
    <add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory" />
    ...
    </httpHandlers>
     

  • Depending on the File extension handler decides which Namespace will generate the output. Example all .ASPX extension files will be compiled by System.Web.UI.PageHandlerFactory
  • Once the file is compiled it will be send back again to the HTTP modules and from there to IIS and then to the browser.

    Figure: - 7.2 IIS flow from various sections.

(B) How can we kill a user session?

Session abandon

(I) How do you upload a file in ASP.NET?

I will leave this to the readers ... Just a hint we have to use System.Web.HttpPostedFile class.

(I) How do I send email message from ASP.NET?

ASP.NET provides two namespace SystemWEB.mailmessage class and System.Web.Mail.Smtpmail class. Just a small homework creates a Asp.NET project and send a email at [email protected]. Do not Spam.

(A) What are different IIS isolation levels?

IIS has three level of isolation:-

LOW (IIS process):- In this main IIS, process, and ASP.NET application run in same process. So if any one crashes the other is also affected. Example let us say (well this is not possible) I have hosted yahoo, hotmail .amazon and goggle on a single PC. So all application and the IIS process runs on the same process. In case any website crashes, it affects every one.

 
Figure: - 7.3 LOW IIS process scenario

Medium (Pooled):- In Medium pooled scenario, the IIS, and web application run in different process. Therefore, in this case there are two processes process1 and process2. In process1, the IIS process is running and in process2, we have all Web application running

 
Figure: - 7.4 Medium pooled scenario

High (Isolated):-In high isolated scenario every process is running is there own process. In below figure there are five processes and every one handling individual application. This consumes heavy memory but has highest reliability.

 
Figure: - 7.5 High isolation scenario

(A)ASP used STA threading model, what is the threading model used for ASP.NET.

ASP.NET uses MTA threading model.

(A)What is the use of <%@ page aspcompat=true %> attribute?

This attribute works like a compatibility option. As mentioned before ASP worked in STA model and ASP.NET works in MTA model, but what if your ASP.NET application is using a VB COM component. In order that VB COM runs properly in ASP.NET threading model, we have to set attribute. After defining the ASPCOMPAT directive attribute ASP.NET pages runs in STA model thus building the compatibility between ASP.NET and old COM components that does not support MTA model.

 (B) Explain the differences between Server-side and Client-side code?

Server side code is executed at the server side on IIS in ASP.NET framework, while client side code is executed on the browser.

(I)Can you explain Forms authentication in detail?

In old ASP if you where said to create a login page and do authentication you have to do hell lot of custom coding. Now in ASP.NET that has made easy by introducing Forms authentication. So let us see in detail what form authentication is.

Forms authentication uses a ticket cookie to see that user is authenticated or not. That means when user is authenticated first time a cookie is set to tell that this user is authenticated. If the cookies expire then Forms authentication mechanism sends the user to the login page.

Following are the steps, which defines steps for Forms authentication:-

  • Configure Web.config file with forms authentication. As shown below in the config file you can see we have give the cookie name and loginurl page.

    <configuration>
    <system.web>
    <!-- Other settings omitted. -->
    <authentication mode="Forms">
    <forms name="logincookies"
    loginUrl="login.aspx"
    protection="All"
    timeout="30"
    path="/" />
    </authentication>
    </system.web>
    </configuration> 

  • Remove anonymous access to the IIS web application, following are changes done to web.config file.

    <configuration>
    <system.web>
    <!-- Other settings omitted. -->
    <authorization>
    <deny users="?" />
    </authorization>
    </system.web>
    </configuration>
     
  • Create the login page, which will accept user information. You will have create your login page that is the Login.aspx, which will actually take the user data.
  • Finally a small coding in the login button.

    Let us assume that the login page has two textboxes TX name and txtapssword.

    Also, import System.Web.Security and put the following code in login button of the page.

    If Page.IsValid Then
    If FormsAuthentication.Authenticate(txtName.Text, txtPassword.Text) Then
    FormsAuthentication.RedirectFromLoginPage(txtName.Text, False)
    Else
    lblStatus.Text = "Error not proper user"
    End If
    End If

(A)How do I sign out in forms authentication?

FormsAuthentication.Signout ()

(A)If cookies are not enabled at browser end does form Authentication work?

No, it does not work.

(A)How to use a checkbox in a data grid?

Twist: - How can I track event in checkbox, which is one of the columns of a data grid?

Note: - This is normally asked when the interviewer want to see that have you really worked practically on a project.

Following are the steps to be done:-

In ASPX page you have to add Item template tag in data grid.

<ItemTemplate>
<asp:CheckBox id="CheckBox1" runat="server" AutoPostBack="True" OnCheckedChanged="Check_Clicked"></asp:CheckBox>
</ItemTemplate>

If you look at the Item template, we have "OnCheckChanged" event. This "OnCheckChanged" event has "Check Clicked" subroutine is actually in behind code. Note this method, which is in behind code, should either be "protected" or "public"
Following below is the subroutine, which defines the method

Protected Sub Check Clicked (By Val sender As Object, By Val e As EventArgs)
'Do something
End Sub

The above steps should be defined in short to the interviewer, which will give a quick feeling of your practical experience with ASP.NET'

(I)What are the steps to create a windows service in VB.NET?

Windows Services are long-running executable applications that run in its own Windows session, which then has the ability to start automatically when the computer boots and also can be manually paused, stopped or even restarted.

Following are the steps to create a service:-

Create a project of type "Windows Service".

 
Figure 7.6:- Create project for Windows Service


If you see, the class created it is automatically inheriting from "System.ServiceProcess.ServiceBase".

You can override the following events provided by service and write your custom code. All the three main events can be used that is Start, stop and continue.

protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
protected override void OnContinue()
{
}

Now to install the service you need to do run the install util exe.

InstallUtil <Project Path>\BIN\MyNewService.exe

(A) What is the difference between "Web farms" and "Web garden"?

"Web farms" are used to have some redundancy to minimize failures. It consists of two or more web server of the same configuration and they stream the same kind of contents. When any request comes there is switching / routing logic, which decides which web server from the farm, handles the request. For instance, we have two servers "Server1" and "Server2" which have the same configuration and content. Therefore, there is a special switch, which stands in between these two servers and the users and routes the request accordingly.

 
Figure 7.7: - Web Farm in action

Above figure explains in detail how web farm work. You can see there is a router in between which takes a request and sees which one of the server is least loaded and forwards the request to that server. Therefore, for request1 it route is server1, for request2 it routes server2, for request3 it routes to server3 and final request4 is routed to server4. So you can see because we have web farm at place server1 and server2 are loaded with two request each rather than one server loading to full. One more advantage of using this kind of architecture is if one of the servers goes down we can still run with the other server thus having 24x7 uptime.

The routing logic can be a number of different options:-

  • Round robin: Each node gets a request sent to it "in turn". Therefore, server1 gets a request, then server2 again, then server1, then server2 again. As shown in the above figure.
  • Least Active: Whichever node show to have the lowest number of current connects gets new connects sent to it. This is good to help keep the load balanced between the server nodes.
  • Fastest Reply: Whichever node replies faster is the one that gets new requests. This is also a good option - especially if there are nodes that might not be "equal" in performance. If one performs better than the other, then send more requests there rather than which is moving slowly?
Before we try to understand what a web garden is let's try to understand how IIS handles processes. All requests to IIS are routed to "aspnet_wp.exe" for IIS 5.0 and "w3wp.exe" for IIS 6.0. In normal case i.e. with out web garden, we have one worker process instance ("aspnet_wp.exe" / "w3wp.exe") across all requests. This one instance of worker process uses the CPU processor as directed by the operating system.
 
 
Figure 7.8: - with out Web Garden
 
However, when we enable web garden for a web server it creates different instances of the worker process and each of these worker process runs on different CPU. You can see in the below diagram we have different worker process instances created which run on different CPU's.

 

Figure 7.9: - With Web Garden

In short, we can define a model in which multiple processes run on multiple CPUs in a single server machine are termed as Web garden.

(A) How do we configure "Web Garden"?

"Web garden" can be configured by using process model settings in "machine.config" or "Web.config" file. The configuration section is named <process Model> and is shown in the following example. The process model is enabled by default (enable="true"). Below is the snippet from config file.

<process Model
enable="true"
timeout="infinite"
idle Timeout="infinite"
shutdown Timeout="0:00:05"
requestLimit="infinite"
requestQueueLimit="5000"
memoryLimit="80"
webGarden="false"
cpuMask="12"
userName=""
password=""
logLevel="errors"
clientConnectedCheck="0:00:05"
/>

From the above process model section for web garden, we are concerned with only two attributes "web garden" and "cpuMask".

Web Garden: - Controls CPU affinity. True indicates that processes should be affinities to the corresponding CPU. The default is False.

CpuMask:- Specifies which processors on a multiprocessor server are eligible to run ASP.NET processes. The cpuMask value specifies a bit pattern that indicates the CPUs eligible to run ASP.NET threads. ASP.NET launches one worker process for each eligible CPU. If web Garden is set to false, cpuMask is ignored and only one worker process will run regardless of the number of processors in the machine. If web Garden is set to true, ASP.NET launches one worker process for each CPU that corresponds to a set bit in cpuMask. The default value of cpuMask is 0xffffffff.

Below are detail steps of how to implement web garden

  • Click Start and then click Run.
  • Type calc.exe and then click OK.
  • Go to View menu, click Scientific.
  • Go to View menu, click Binary.
  • Use zero and one to specify the processors ASP.NET can or cannot use.
    Use one for the processor that you want to use for ASP.NET. Use 0 for the processor that you do not want to use for ASP.NET. For example, if you want to use the first two processors for ASP.NET of a four-processor computer, type 1100.
  • On the View menu, click Decimal. Note the decimal number.
  • Open the Web.config or machine.config file in a text editor such as Notepad. The Web.config file is located in the folder where the application is saved.
  • In the Web.config file, add the process Model configuration element under the System. Web element. Before adding <process Model> to Web.config file, the user has to make sure that the allow Definition attribute in the <process Model> section of the Web.config file is set to everywhere.
  • Add and then set the web Garden attribute of the process Model element to True.
  • Add and then set the cpuMask attribute of the process Model element to the result that is determined in your calculation.
    Do not preface the number with zerox because the result of the calculation is a decimal number.
The following example demonstrates the process Model element that is configured to enable only the first two processors of a four-processor computer.

<processModel
enable="true"
webGarden="true"
cpuMask="12" />

Save the Web.config file. The ASP.NET application automatically restarts and uses only the specified processors.

(B) What is the main difference between Grid layout and Flow Layout?

Grid Layout provides absolute positioning for controls placed on the page. Developers that have their roots in rich-client development environments like Visual Basic will find it easier to develop their pages using absolute positioning, because they can place items exactly where they want them. On the other hand, Flow Layout positions items down the page like traditional HTML. Experienced Web developers favor this approach because it results in pages that are compatible with a wider range of browsers.

If you look in to the HTML code created by absolute positioning you can notice lot of DIV tags. While in Flow layout, you can see more of using HTML table to position elements, which is compatible with wide range of browsers.

(I) What's the difference between trace and debug in ASP.NET?

Debug and trace enables you to monitor the application for errors and exception with out VS.NET IDE. In Debug mode compiler inserts some debugging code inside the executable. As the debugging code is the part of the executable they run on the same thread where the code runs and they do not given you the exact efficiency of the code ( as they run on the same thread). So for every full executable DLL you will see a debug file also as shown in figure 'Debug Mode'.

 
Figure 7.10 : - Debug mode

Trace works in both debug as well as release mode. The main advantage of using trace over debug is to do performance analysis which can not be done by debug. Trace runs on a different thread thus it does not impact the main code thread.

Note: - There is also a fundamental difference in thinking when we want to use trace and when want to debug. Tracing is a process about getting information regarding program's execution. On the other hand debugging is about finding errors in the code.

(A) How do you enable tracing in on an ASP.NET page?

To enable tracing on an ASP.NET page we need to put the 'trace' attribute to true on the page attribute as shown in figure 'Tracing in Action' ( Its numbered as 1 in the figure). In the behind code we can use the trace object to put tracing like one we have shown on the page load numbered as (4). We have used the 'trace.write' to display our tracing. You can also see the trace data which is circled. 2 and 3 show the actual data. You can see how trace shows in details the tracing information for a page with events and time period for execution. If you make the 'trace' as false you will only see the actual display i.e. 'This is the actual data'. So you can enable and disable trace with out actually compiling and uploading new DLL's on production environment.

 

 

Figure 7.11 : - Tracing in Action

The above sample enables tracing only at page level. To enable tracing on application level we need to modify the 'web.config' file and put the 'trace' tag with 'enabled=true'.

<trace enabled="true" requestLimit="10" pageOutput="false" localOnly="true" />

(B) Which namespace is needed to implement debug and trace ?

Debug and trace class belongs to 'System.Diagnostic' namespace.

(A) Can you explain the concept of trace listener?

'Tracelistener' are objects that get tracing information from the trace class and they output the data to some medium. For instance you can see from the figure 'TraceListener' how it listens to the trace object and outputs the same to UI, File or a windows event log. There are three different types of 'tracelistener' first is the 'defaulttracelistener' (this outputs the data to UI), second is 'textwritertracelistener' (this outputs to a file) and the final one is 'Eventlogtracelistener' which outputs the same to a windows event log

 
Figure 7.12 : - TraceListener

Below is a code snippet for 'textwritertracelistener' and 'eventlogtracelistener'. Using 'textwritertracelistener' we have forwarded the trace's to 'ErrorLog.txt' file and in the second snippet we have used the 'Eventlogtracelistener' to forward the trace's to windows event log.

 
Figure 7.13 :- Tracelistener in action

(I) What are trace switches?

Trace switches helps us to control and govern the tracing behavior of a project. There are two types of trace switches 'BooleanSwitch' and 'TraceSwitch'. BooleanSwitch, as the name says, is a kind of on/off switch which can be either enabled (true) or disabled (false).

 
Figure 7.14 :- Trace switches

'TraceSwitch' on the other hand offers more options rather than simple true/false like 'BooleanSwitch'. Tracing is enabled for a TraceSwitch object using the Level property. When we set the Level property of a switch to a particular level, it includes all levels from the indicated level down. For example, if you set a TraceSwitch's Level property to TraceLevel.Info, then all the lower levels, from TraceLevel.Error to TraceLevel.Warning, will be taken in to account.

Below are the various levels in 'TraceSwitch' object.

Off a Outputs no messages to Trace Listeners
Error a Outputs only error messages to Trace Listeners
Warning a Outputs error and warning messages to Trace Listeners
Info a Outputs informational, warning and error messages to Trace Listeners
Verbose a Outputs all messages to Trace Listeners

TraceSwitch objSwitch = new TraceSwitch("TraceWarningandError", "Error in trace") ;
objSwitch.Level = TraceLevel.Warning ;

Up Next
    Ebook Download
    View all
    Learn
    View all