Saturday, July 12, 2008


With ASP.NET, there are six(6) controls included. They are:

The RequiredFieldValidation Control
The CompareValidator Control
The RangeValidator Control
The RegularExpressionValidator Control
The CustomValidator Control

Validator Control Basics

All of the validation controls inherit from the base class BaseValidator so they all have a series of properties and methods that are common to all validation controls. They are:

ControlToValidate - This value is which control the validator is applied to.
ErrorMessage - This is the error message that will be displayed in the validation summary.
IsValid - Boolean value for whether or not the control is valid.
Validate - Method to validate the input control and update the IsValid property.
Display - This controls how the error message is shown. Here are the possible options:
None (The validation message is never displayed.)
Static (Space for the validation message is allocated in the page layout.)
Dynamic (Space for the validation message is dynamically added to the page if validation fails.)

The RequiredFieldValidation Control

The first control we have is the RequiredFieldValidation Control. As it's obvious, it make sure that a user inputs a value. Here is how it's used:

Required field:
ErrorMessage="* You must enter a value into textbox1" Display="dynamic">*

In this example, we have a textbox which will not be valid until the user types something in. Inside the validator tag, we have a single *. The text in the innerhtml will be shown in the controltovalidate if the control is not valid. It should be noted that the ErrorMessage attribute is not what is shown. The ErrorMessage tag is shown in the Validation Summary (see below).

The CompareValidator Control

Next we look at the CompareValidator Control. Usage of this CompareValidator is for confirming new passwords, checking if a departure date is before the arrival date, etc. We'll start of with a sample:

Textbox 1:

Textbox 2:

ControlToValidate="textbox1" ControlToCompare="textbox2"
ErrorMessage="* You must enter the same values into textbox 1 and textbox 2"

Here we have a sample where the two textboxes must be equal. The tags that are unique to this control is the ControlToCompare attribute which is the control that will be compared. The two controls are compared with the type of comparison specified in the Operator attribute. The Operator attribute can contain Equal, GreterThan, LessThanOrEqual, etc.
Another usage of the ComapareValidator is to have a control compare to a value. For example:

ErrorMessage="* You must enter the a number greater than 50" Display="dynamic">*

The data type can be one of: Currency, Double, Date, Integer or String. String being the default data type.

The RangeValidator Control

Range validator control is another validator control which checks to see if a control value is within a valid range. The attributes that are necessary to this control are: MaximumValue, MinimumValue, and Type.

Enter a date from 1998:

ErrorMessage="* The date must be between 1/1/1998 and 12/13/1998" Display="static">*

The RegularExpressionValidator Control

The regular expression validator is one of the more powerful features of ASP.NET. Everyone loves regular expressions. Especially when you write those really big nasty ones... and then a few days later, look at it and say to yourself. What does this do?
Again, the simple usage is:

ErrorMessage="* Your entry is not a valid e-mail address."

Here is a webpage I like to use to check my regular expressions.

The CustomValidator Control

The final control we have included in ASP.NET is one that adds great flexibility to our validation abilities. We have a custom validator where we get to write out own functions and pass the control value to this function.

ErrorMessage="*This box is not valid" dispaly="dynamic">*

We notice that there are two new attributes ClientValidationFunction and OnServerValidate. These are the tell the validation control which functions to pass the controltovalidate value to. ClientValidationFunction is usually a javascript funtion included in the html to the user. OnServerValidate is the function that is server-side to check for validation if client does not support client-side validation.
Client Validation function:


Server Validation function:

Sub ServerValidate (objSource As Object, objArgs As ServerValidateEventsArgs)
' Code goes here
End Sub


Validation Summary
ASP.NET has provided an additional control that complements the validator controls. This is the validation summary control which is used like:

ShowSummary="true" DisplayMode="List" />


The validation summary control will collect all the error messages of all the non-valid controls and put them in a tidy list. The list can be either shown on the web page (as shown in the example above) or with a popup box (by specifying ShowMessageBox="True")

What data types do the RangeValidator control support?

Integer, String, and Date.

Explain the differences between Server-side and Client-side code?

Server-side code executes on the server. Client-side code executes in the client's browser.

What type of code (server or client) is found in a Code-Behind class?

The answer is server-side code since code-behind is executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code.

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

All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user.

What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?

Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.

What is the Global.asax used for?

The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.
The Global.asx file is an optional file that contains code for responding to application level events raised by ASP.NET. This file is also called as ASP.NET application file. This file resides in the root directory of an application. If we are not defining this file in application, the ASP.NET page framework assumes that you have not defined any applicationa/Session events in the application.

Followign are the list of events handled in the global.asax file.

Event: Application_Start

When an application starts. This event occurs only one time in an application’s life cycle. It occurs again when you restart the application. It’s the best place to count number of visitors.

Event: Application_End

This event occurs when application ends.

Event: Session_Start

This event occurs whenever a new session starts. This is the best place to count user sessions for an application

Practical Usage: Setting user specific values, caching items based upon user context.

Event: Session_End

This event Opposite of the previous event.

Event: Application_Error

This event occurs when an unhandled error or exception occurs in an application.

Event: Application_BeginRequest

This event occurs every time when server makes a request. This event may occur multiple times in an applications life cycle.

Event: Application_End

This event occurs when an application closes

What are the Application_Start and Session_Start subroutines used for?

This is where you can set the specific variables for the Application and Session objects.

Can you explain what inheritance is and an example of when you might use it?

When you want to inherit (use the functionality of) another class. Example: With a base class named Employee, a Manager class could be derived from the Employee base class.

Describe the difference between inline and code behind?

Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.

Explain what a diffgram is, and a good use for one?

The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.

Whats MSIL, and why should my developers need an appreciation of it if at all?

MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.

Can you edit data in the Repeater control?

No, it just reads the information from its data source.

Which template must you provide, in order to display data in a Repeater control?


How can you provide an alternating color scheme in a Repeater control?

Use the AlternatingItemTemplate.

What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control?

You must set the DataSource property and call the DataBind method.

What base class do all Web Forms inherit from?

The Page class.

Name two properties common in every validation control?

ControlToValidate property and Text property.

Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?

DataTextField property.

Which control would you use if you needed to make sure the values in two different controls matched?

CompareValidator control.

How many classes can a single .NET DLL contain?

It can contain many classes.

How can we create Tree control in


How do I upload a file from my ASP.NET page?

A: In order to perform file upload in your ASP.NET page, you will need to use two classes: the System.Web.UI.HtmlControls.HtmlInputFile class and the System.Web.HttpPostedFile class. The HtmlInputFile class represents and HTML input control that the user will use on the client side to select a file to upload. The HttpPostedFile class represents the uploaded file and is obtained from the PostedFile property of the HtmlInputFile class. In order to use the HtmlInputFile control, you need to add the enctype attribute to your form tag as follows:

Also, remember that the /data directory is the only directory with Write permissions enabled for the anonymous user. Therefore, you will need to make sure that the your code uploads the file to the /data directory or one of its subdirectories.
Below is a simple example of how to upload a file via an ASP.NET page in C# and VB.NET.
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.UI.HtmlControls" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Drawing" %>




479. How do I send an email message from my ASP.NET page?
A: You can use the System.Web.Mail.MailMessage and the System.Web.Mail.SmtpMail class to send email in your ASPX pages. Below is a simple example of using this class to send mail in C# and VB.NET. In order to send mail through our mail server, you would want to make sure to set the static SmtpServer property of the SmtpMail class to mail-fwd.
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.Mail" %>

Mail Test

Write a program to create a user control with name and surname as data members and login as method and also the code to call it.

(Hint use event delegates) Practical Example of Passing an Events to delegates

How can you read 3rd line from a text file?

Which method do you use to redirect the user to another page without performing a round trip to the client?

What is the difference between Server.Transfer and Response. Redirect? Why would I choose one over the other?

Server.Transfer vs. Response.Redirect

Server.Transfer Response.Redirect
1 is more user-friendly
2 visitor can bookmark
3 pages appear to the client as a different url than they really are
4 Server.Transfer has an optional parameter to pass the form data to the new page
5 Round trip will not be happened
It will take round trip to server
6 Context.Items dictionary to pass the
state from the source page to new page.

Response.Redirect is more user-friendly, as the site visitor can bookmark the page that they are redirected to. Transferred pages appear to the client as a different url than they really are. This means that things like relative links / image paths may not work if you transfer to a page from a different directory.
Server.Transfer has an optional parameter to pass the form data to the new page.
Since the release version, this no longer works, because the Viewstate now has more security by default (The EnableViewStateMac defaults to true), so the new page isn’t able to access the form data. You can still access the values of the original page in the new page, by requesting the original handler:

Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the requested page. Data can be persist accros the pages using Context.Item collection, which is one of the best way to transfer data from one page to another keeping the page state alive.

Response.Redirect() :client know the physical loation (page name and query string as well). Context.Items loses the persisitance when nevigate to destination page

Redirect and Transfer both cause a new page to be processed. But the interaction between the client (web browser) and server (ASP.NET) is different in each situation.

Redirect: A redirect is just a suggestion – it’s like saying to the client “Hey, you might want to look at this”. All you tell the client is the new URL to look at, and if they comply, they do a second request for the new URL.

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

Transfer: A transfer happens without the client knowing – it’s the equivalent of a client requesting one page, but being given another. As far as the client knows, they are still visiting the original URL.

Sharing state between pages is much easier using Server.Transfer – you can put values into the Context.Items dictionary, which is similar to Session and Application, except that it lasts only for the current request. (search for HttpContext in MSDN). The page receiving postback can process data, store values in the Context, and then Transfer to a page that uses the values.


Using for new page to be processed
Visitor can bookmark the page [the URL will change]
Use the URL, Session to pass the state from the source page to new page.
Context.Items will loses the state
It will take round trip to server


Using for new page to be processed
Visitor cannot bookmark the page [the URL remain same]
Use the Session to pass the state from the source page to new page.
Use the Context.Items dictionary to pass the state from the source page to new page.
Round trip will not be happened

What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?

Server.Transfer is used to post a form to another page. Response.Redirect is used to redirect the user to another page or site.

What is the difference between ASP and ASP.NET?

ASP is interpreted.
ASP.NET Compiled event base programming.

What does the "EnableViewState" property do? Why would I want it on or off?

What base class do all Web Forms inherit from?

How do you debug an ASP.NET application?

How do you deploy an ASP.NET application?

How do you separate business logic while creating an ASP.NET application?

Specify the best ways to store variables so that we can access them in various pages of ASP.NET application?

How would you get ASP.NET running in Apache web servers - why would you even do this?

How would ASP and ASP.NET apps run at the same time on the same server?

What are ASP.NET Web Forms? How is this technology different than what is available though ASP (1.0-3.0)?

webFarm Vs webGardens

A web farm is a multi-server scenario. So we may have a server in each state of US. If the load on one server is in excess then the other servers step in to bear the brunt. How they bear it ...

Using COM Component in .Net

As most of you know that .Net does not encourage the development of COM components and provides a different solution to making reusable components through Assemblies. But, there are a lot of ...

Using ActiveX Control in .Net

ActiveX control is a special type of COM component that supports a User Interface. Using ActiveX Control in your .Net Project is even easier than using COM component. They are bundled usually...

How do you turn off cookies for one page in your site?

How do you create a permanent cookie?

Making a persistent cookie(Permanent)
Dim Objcookie as new HTTPCookie("Mycookie")
Dim Date as Datetime = Objcookie.Expires = now.addhours(1)
Setting the Expires property to MinValue means that the Cookie never expires.
seeting the Expires Property to date less than todays date

Explain the differences between Server-side and Client-side code?

Describe the difference between inline and code behind - which is best in a loosely coupled solution?

Which two properties are on every validation control?

What type of code (server or client) is found in a Code-Behind class?

As .NET is featured with Event Driven Programming code behind pages are used to separate the even-procedures from content of page. So it containts Server Side code.

Should validation (did the user enter a real date) occur server-side or client-side? Why?

In what order do the events of an ASPX page execute. As a developer is it important to understand these events?

Describe session handling in a webfarm, how does it work and what are the limits

Briefly explain how the server control validation controls work.

Events in the Life Cycle of a Web Application?

A web application lives as long as it has active sessions while web forms live for a short moment.

Web application begins when a browser requests the start page of the application, the server
starts the executable (DLL) that responds to that request creates an instance of the requested Web form,
generates the HTML to respond to the request, posts that response to the browser destroys the instance of the Web form The browser, after receiving the generated HTML, allows the user to type in text boxes,
select option buttons, perform other tasks until triggering a post-back event (e.g. a button click)
sends (when triggered by Post-back events) the page's data (view state) back to the server for event processing When the server receives the view state, it creates a new instance of the Web fills in the data from the view state processes any events that occurred posts the resulting HTML back to the browser destroys the instance of the Web form. A web form may link to another page of the application The session ends when the user chooses to close the browser or go to some other site. If there are no other sessions from other users, the (multi-user) application ends but an Application_End event occurs only when it is garbage-collected by ASP.NET (which is unpredictable), not by reference count.

Preserving Data on a Web Form?

View State
is data that ASP.NET preserves between requests.

Data entered in controls is sent with each request and restored to controls in Page_Init.
Data in these controls is then available in the Page_Load event.
Data is saved in state variables in the Application or Session objects:
Application state variables: are available to all users of an application, thus it is a multi-user global data which can be read or written by all sessions.
Session state variables: are available only to a single session(user), like global data in an application but is only accessible by the current session.
State variables are created dynamically:
protected void Session_Start(Object sender, EventArgs e)
// Initialize Clicks Session state variable.
Session["Clicks"] = 0;
private void Button1_Click(object sender, System.EventArgs e)
// Increment click count.
Session["Clicks"] = (int)Session["Clicks"]+1;
// Display the number of clicks.
Response.Write("Number of clicks: " + Session["Clicks"] + "

Application state variables must be initialized, e.g. the Clicks state variable must be initialized before performing the cast

Application and Session Events?

Event handling code are written in the Global.asax file:

Application Events: used to initialize objects and data and made available to all the current sessions:
Application_Start -- The first user visits the start page of your Web application
Application_End -- There are no more users of the application
Application_BeginRequest -- At the beginning of each request to the server. A request happens every time a browser goes to any of the pages in the application.
Application_EndRequest -- At the end of each request to the server.
Session_Start -- A new user visits the start page of your application
Session_End -- A user leaves your application, either by closing his or her browser or by timing out.
A session is a unique instance of the browser
A single user can have multiple instances of the browser running on his or her machine. Each instance visiting your web application has a unique session.
Example in Global.asax.cs
public class Global : System.Web.HttpApplication
protected void Application_Start(Object sender, EventArgs e)
// Create Application state variables.
Application["AppCount"] = 0;
Application["SessCount"] = 0;
// Record application start.
Application["AppCount"] = (int)Application["AppCount"] + 1;
protected void Session_Start(Object sender, EventArgs e)
// Count sessions.
Application["SessCount"] = (int)Application["SessCount"] + 1;
// Display session count.
Response.Write("Number of applications: " +
Application["AppCount"] + "
// Display session count.
Response.Write("Number of sessions: " +
Application["SessCount"] + "
// Initialize Clicks Session state variable.
Session["Clicks"] = 0;
protected void Session_End(Object sender, EventArgs e)
// Decrement sessions.
Application["SessCount"] = (int)Application["SessCount"] - 1;
protected void Application_BeginRequest(Object sender, EventArgs e)
protected void Application_EndRequest(Object sender, EventArgs e)
protected void Application_End(Object sender, EventArgs e)

Web Form Events?

Events to process and maintain data used on a web page, to respond to data binding, and to handle exceptions:

Page_Init -- The server controls are loaded and initialized from the Web form's view state. This is the first step in a Web form's life cycle.
Page_Load -- The server controls are loaded on the Page object. View state information is available at this point, so this is where you put code to change control settings or display text on the page.
Page_PreRender -- The application is about to render the Page object.
Page_Unload -- The page is unloaded from memory.
Page_Error -- An unhandled exception occurs
Page_AbortTransaction - A transaction is aborted
Page_CommitTransaction - A transaction is accepted
Page_DataBinding -- A server control on the page binds to a data source
Page_Disposed -- The Page object is released from memory. This is the last event in the life of a Page object.
A Page_Load event is coupled with the IsPostback property to initialize data the first time a user visits a web form.
Similar to a Session_Start event, but it occurs at the page level rather than the application level.
The following initializes an object and stores it in the Session state the first time a page is viewed:
//declare a new object
FlashCardClass FlashCard = new FlashCardClass();
private void Page_Load(object sender, System.EventArgs e)
if (!IsPostBack)
//Shuffle the FlashCards
//Store the object in a Session variable
Session["FlashCard"] = FlashCard;
//Get the Session FlashCard variable
FlashCard = (FlashCardClass) Session["FlashCard"];

Server Control Events?

Server controls such as a Button, TextBox, and DropDownList each have their own sets of events that occur in response to user actions, but not all server control events are created equal:

Post-back events -- cause the Web page to be sent back to the server for immediate processing, it affect perceived performance as they trigger a round trip to the server
Cached events are saved in the page's view state to be processed when a post-back event occurs
Validation events are handled on the page without posting back or caching (the validation server controls use these type of events.)
Create a web form with a TextBox, a RequiredFieldValidator, and a Button server control
Set ControlToValidate property of the validator control to TextBox1, and then add the following code to the TextBox and Button event handlers:
private void Button1_Click(object sender, System.EventArgs e)
Response.Write("Button Clicked!
private void TextBox1_TextChanged(object sender, Syustem.EventArgs s)
Respons.Write("Text has changed!
Test: leave the TextBox blank and click OK, the RequiredFieldValidator is displayed-- no other events are processed and the page is not posted back to the server
Test: Type in the TextBox and click OK, the page is posted back and the TextChanged event occurs before the Click event.;

Where Processing Occurs?

Web applications use IIS to manage their processes on the server
The boundaries of a web application are determined by its folder structure.
The application boundary starts in the folder containing the start page of the application and it ends at the last subordinate folder (e.g. bin)
When VS.NET creates a new web application project, it creates a new folder for the project and identifies the first Web form in the project (e.g. Webform1.aspx as the start page
An alternate Start Page can be selected.
A subordinate web application can be included as part of a single, large containing application.
A large, multi-folder application can be broken up into smaller applications.
Application state variables are affected when application boundaries change, since all DLLs within an application boundary have access to the same Application state.

Managing Processes?

Options for how the server runs a web application:

In-process with IIS (Inetinfo.exe) -- all calls are made in-process. faster
offers no protection, therefore can corrupt memory, Inetinfo.exe and other applications running in-process.
Pooled with other Web application processes in DLLHost.exe -- the default option which provides a balance between protection and performance. Failure affects other applications in the pool but will not affect Inetinfo.exe
Isolated in its own instance of DLLHost.exe -- protected from other programs, but makes less efficient cross-process-boundary calls.

Determining When an Application Ends?

Sessions allow ASP.NET to keep user-specific data called the Session state.
Sessions determine when the application. If the last session ends, the IIS ends the application.
A time-out interval (default = 20 minutes) can be modified on the Web.config.

No comments: