73
ASP.NET

ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Embed Size (px)

Citation preview

Page 1: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

ASP.NET

Page 2: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

ContentsIntroduction to ASP.net...............................................................................................................................3

Active Server Pages (ASP)........................................................................................................................4

Problems with Traditional ASP............................................................................................................4

Introducing ASP.NET................................................................................................................................5

Advantages of ASP.NET.......................................................................................................................5

ASP.NET Overview...................................................................................................................................5

ASP.net Execution Cycle..........................................................................................................................6

ASP.net Page Life Cycle................................................................................................................................6

1. Object Initialization..............................................................................................................................7

2. Load Viewstate Data............................................................................................................................7

4. Object Load..........................................................................................................................................8

5. Raise Post Back Change Events............................................................................................................9

6. Process Client-Side PostBack Event.....................................................................................................9

7. Prerender the Objects.........................................................................................................................9

8. ViewState Saved................................................................................................................................10

9. Render to HTML.................................................................................................................................10

10. Disposal...........................................................................................................................................10

Application Life Cycle in General...............................................................................................................11

Application Life Cycle Events and the Global.asax file...............................................................................14

Compilation Life Cycle...............................................................................................................................15

Application Restarts...........................................................................................................................16

HTTP Modules...........................................................................................................................................16

ASP.Net & IIS.............................................................................................................................................17

Introduction...........................................................................................................................................17

What is Web Server?.............................................................................................................................17

What is IIS?............................................................................................................................................17

How Asp.Net Request Is Processed at IIS :............................................................................................18

Asp.Net Controls........................................................................................................................................23

Label..........................................................................................................................................................31

2 | P a g e

Page 3: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Textbox......................................................................................................................................................31

Button........................................................................................................................................................31

Sample Program........................................................................................................................................31

Common Properties of ASP.Net Controls..................................................................................................33

Checkbox...................................................................................................................................................33

Radiobutton...............................................................................................................................................34

DropDownList............................................................................................................................................34

Checkbox List.............................................................................................................................................35

FileUpLoad.................................................................................................................................................36

HyperLink..................................................................................................................................................36

Master Page..............................................................................................................................................36

Menus........................................................................................................................................................37

Validation Controls in ASP.net...................................................................................................................37

Introduction...............................................................................................Error! Bookmark not defined.

Understanding the Difference Between Server-Side and Client-Side Validation...................................37

.NET Validation Controls............................................................................................................................38

The RequiredFieldValidator Control......................................................................................................39

The CompareValidator Control..............................................................................................................42

Validating Against Constants.............................................................................................................43

The RangeValidator Control..................................................................................................................45

The RegularExpressionValidator Control...............................................................................................46

The CustomValidator Control................................................................................................................49

Client-side Validation........................................................................................................................49

Server-side Validation.......................................................................................................................51

The ValidationSummary Control............................................................................................................54

Validation Expressions...............................................................................................................................57

Introduction to ASP.net

ASP.NET is the new offering for Web developers from the Microsoft .It is not simply the next-generation of ASP; in fact, it is a completely re-engineered and enhanced technology that offers much, much more than traditional ASP and can increase productivity significantly.

3 | P a g e

Page 4: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Because it has evolved from ASP, ASP.NET looks very similar to its predecessor but only at first sight. Some items look very familiar, and they remind us of ASP. But concepts like Web Forms, Web Services, or Server Controls gives ASP.NET the power to build real Web applications.

Active Server Pages (ASP)

Microsoft Active Server Pages (ASP) is a server-side scripting technology. ASP is a technology that Microsoft created to ease the development of interactive Web applications. With ASP you can use client-side scripts as well as server-side scripts. Maybe you want to validate user input or access a database. ASP provides solutions for transaction processing and managing session state. Asp is one of the most successful languages used in web development.

Problems with Traditional ASP

There are many problems with ASP if you think of needs for Today's powerful Web applications.

1. Interpreted and Loosely-Typed CodeASP scripting code is usually written in languages such as JScript or VBScript. The script-execution engine that Active Server Pages relies on interprets code line by line, every time the page is called.

2. Mixes layout (HTML) and logic (scripting code)ASP files frequently combine script code with HTML. This results in ASP scripts that are lengthy, difficult to read, and switch frequently between code and HTML. The interspersion of HTML with ASP code is particularly problematic for larger web applications, where content must be kept separate from business logic.

3. Limited Development and Debugging ToolsMicrosoft Visual InterDev, Macromedia Visual UltraDev, and other tools have attempted to increase the productivity of ASP programmers by providing graphical development environments. However, these tools never achieved the ease of use or the level of acceptance achieved by Microsoft Windows application development tools, such as Visual Basic or Microsoft Access.

4. No real state managementSession state is only maintained if the client browser supports cookies. Session state information can only be held by using the ASP Session object. And you have to implement additional code if you, for example, want to identify a user.

5. Update files only when server is downIf your Web application makes use of components, copying new files to your application should only be done when the Web server is stopped.

6. Obscure Configuration SettingsThe configuration information for an ASP web application (such as session state and server timeouts) is stored in the IIS metabase. Because the metabase is stored in a proprietary format, it can only be modified on the server machine with utilities such as the Internet Service Manager. With limited support for programmatically manipulating or extracting these settings, it is often an arduous task to port an ASP application from one server to another.

4 | P a g e

Page 5: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Introducing ASP.NET

ASP.NET was developed in direct response to the problems that developers had with classic ASP. Since ASP is in such wide use, however, Microsoft ensured that ASP scripts execute without modification on a machine with the .NET Framework (the ASP engine, ASP.DLL, is not modified when installing the .NET Framework). Thus, IIS can house both ASP and ASP.NET scripts on the same machine.

Advantages of ASP.NET

1. Separation of Code from HTMLTo make a clean sweep, with ASP.NET you have the ability to completely separate layout and business logic.

2. Support for compiled languagesdeveloper can use VB.NET and access features such as strong typing and object-oriented programming. Using compiled languages also means that ASP.NET pages do not suffer the performance penalties associated with interpreted code

3. Use services provided by the .NET FrameworkThe .NET Framework provides class libraries that can be used by your application. Some of the key classes help you with input/output, access to operating system services, data access, or even debugging. We will go into more detail on some of them in this module.

4. Graphical Development EnvironmentVisual Studio .NET provides a very rich development environment for Webdevelopers. You can drag and drop controls and set properties the way you do in Visual Basic 6. And you have full IntelliSense support, not only for your code, but also for HTML and XML.

5. State managementTo refer to the problems mentioned before, ASP.NET provides solutions for session and application state management. State information can, for example, be kept in memory or stored in a database. It can be shared across Web farms, and state information can be recovered, even if the server fails or the connection breaks down.

6. Update files while the server is running!Components of your application can be updated while the server is online and clients are connected.

7. XML-Based Configuration FilesConfiguration settings in ASP.NET are stored in XML files that you can easily read and edit. You can also easily copy these to another server, along with the other files that comprise your application.

ASP.NET Overview

ASP.NET provides services to allow the creation, deployment, and execution of Web Applications and Web Services

Like ASP, ASP.NET is a server-side technology

5 | P a g e

Page 6: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Web Applications are built using Web Forms. ASP.NET comes with built-in Web Forms controls, which are responsible for generating the user interface.

Web Forms are designed to make building web-based applications as easy as building Visual Basic applications

ASP.net Execution Cycle Now let's see what’s happening on the server side. A request for an .aspx file causes the ASP.NET runtime to parse the file for code that can be compiled. It then generates a page class that instantiates and populates a tree of server control instances. This page class represents the ASP.NET page.

Now an execution sequence is started in which, for example, the ASP.NET page walks its entire list of controls, asking each one to render itself.

The controls paint themselves to the page. This means they make themselves visible by generating HTML output to the browser client.Execution Process of ASP.NETWe need to have a look at what happening to your code in ASP.NET.

Compilation, when page is requested the first time

The first time a page is requested, the code is compiled. Compiling code in .NET means that a compiler in a first step emits Microsoft intermediate language (MSIL) and produces metadata if you compile your source code to managed code. In a following step MSIL has to be converted to native code.Microsoft intermediate language (MSIL)

Microsoft intermediate language is code in an assembly language like style. It is CPU independent and therefore can be efficiently converted to native code.The conversion in turn can be CPU-specific and optimized. The intermediate language provides a hardware abstraction layer.MSIL is executed by the common language runtime.Common language runtime

The common language runtime contains just-in-time (JIT) compilers to convert the MSIL into native code. This is done on the same computer architecture that the code should run on.

The runtime manages the code when it is compiled into MSIL the code is therefore called managed code.

ASP.net Page Life Cycle

When a page request is sent to the Web server, whether through a submission or location change, the page is run through a series of events during its creation and disposal. When we try to build ASP.NET pages and this execution cycle is not taken into account, we can cause a lot of headaches for ourselves. However, when used and manipulated correctly, a page's execution cycle can be an effective and powerful tool. Many developers are realizing that understanding what happens and when it happens is

6 | P a g e

Page 7: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

crucial to effectively writing ASP.NET pages or user controls. So let's examine in detail the ten events of an ASP.NET page, from creation to disposal. We will also see how to tap into these events to implant our own custom code.

I'll set the stage with a simple submission form written in ASP.NET with C#. The page is loaded for the first time and has several server-side Web controls on it. When the Web server receives a request for the page, it will process our Web controls and we will eventually get rendered HTML. The first step in processing our page is object initialization.

1. Object Initialization

A page's controls (and the page itself) are first initialized in their raw form. By declaring your objects within the constructor of your C# code-behind file (see Figure 1), the page knows what types of objects and how many to create. Once you have declared your objects within your constructor, you may then access them from any sub class, method, event, or property. However, if any of your objects are controls specified within your ASPX file, at this point the controls have no attributes or properties. It is dangerous to access them through code, as there is no guarantee of what order the control instances will be created (if they are created at all). The initialization event can be overridden using the OnInit method.

Figure 1 - Controls are initialized based on their declaration.

2. Load Viewstate DataAfter the Init event, controls can be referenced using their IDs only (no DOM is established yet for relative references). At LoadViewState event, the initialized controls receive their first properties: viewstate information that was persisted back to the server on the last submission. The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request. As you can see, this is a giant leap forward from the old ASP 3.0 techniques of maintaining state. This event can be overridden using the LoadViewState method and is commonly used to customize the data received by the control at the time it is populated. Figure 2 shows an example of overriding and setting viewstate at the LoadViewState event.

7 | P a g e

Page 8: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

3. LoadPostData Processes Postback Data

During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. When a page submits a form, the framework will implement the IPostBackDataHandler interface on each control that submitted data. The page then fires the LoadPostData event and parses through the page to find each control that implements this interface and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page. After the LoadPostData event triggers, the RaisePostDataChanged event is free to execute (see below).

4. Object Load

Objects take true form during the Load event. All object are first arranged in the page DOM (called the Control Tree in ASP.NET) and can be referenced easily through code or relative position (crawling the DOM). Objects are then free to retrieve the client-side properties set in the HTML, such as width, value, or visibility. During Load, coded logic, such as arithmetic, setting control properties programmatically, and using the StringBuilder to assemble a string for output, is also executed. This stage is where the majority of work happens. The Load event can be overridden by calling OnLoad as shown in Figure 3.

Figure 3 - The OnLoad event is an ideal location to place logic.

8 | P a g e

Page 9: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

5. Raise Post Back Change Events

As stated earlier, this occurs after all controls that implement the IPostBackDataHandler interface have been updated with the correct postback data. During this operation, each control is flagged with a Boolean on whether its data was actually changed or remains the same since the previous submit. ASP.NET then sweeps through the page looking for flags indicating that any object's data has been updated and fires RaisePostDataChanged. The RaisePostDataChanged event does not fire until all controls are updated and after the Load event has occurred. This ensures data in another control is not manually altered during the RaisePostDataChanged event before it is updated with postback data.

6. Process Client-Side PostBack Event

After the server-side events fire on data that was changed due to postback updates, the object which caused the postback is handled at the RaisePostBackEvent event. The offending object is usually a control that posted the page back to the server due to a state change (with autopostback enabled) or a form submit button that was clicked. There is often code that will execute in this event, as this is an ideal location to handle event-driven logic. The RaisePostBackEvent event fires last in the series of postback events due to the accuracy of the data that is rendered to the browser.

Controls that are changed during postback should not be updated after the executing function is called due to the consistency factor. That is, data that is changed by an anticipated event should always be reflected in the resulting page. The RaisePostBackEvent can be trapped by catching RaisePostBackEvent, as in Figure 4.

Figure 4 - The RaisePostDataChanged and RaisePostBackEvent events are defined by the IPostBackDataHandler interface.

7. Prerender the Objects

The point at which the objects are prerendered is the last time changes to the objects can be saved or persisted to viewstate. This makes the PreRender step a good place to make final modifications, such as changing properties of controls or changing Control Tree structure, without having to worry about ASP.NET making changes to objects based off of database calls or viewstate updates. After the

9 | P a g e

Page 10: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

PreRender phase those changes to objects are locked in and can no longer be saved to the page viewstate. The PreRender step can be overridden using OnPreRender

8. ViewState Saved

The viewstate is saved after all changes to the page objects have occurred. Object state data is persisted in the hidden <input> object and this is also where object state data is prepared to be rendered to HTML. At the SaveViewState event, values can be saved to the ViewState object, but changes to page controls are not. You can override this step by using SaveViewState, as shown in Figure 5.

Figures 5 - Values are set for controls in OnPreRender. During the SaveViewState event, values are set for the ViewState object.

9. Render to HTMLThe Render event commences the building of the page by assembling the HTML for output to the browser. During the Render event, the page calls on the objects to render themselves into HTML. The page then collects the HTML for delivery. When the Render event is overridden, the developer can write custom HTML to the browser that nullifies all the HTML the page has created thus far. The Render method takes an HtmlTextWriter object as a parameter and uses that to output HTML to be streamed to the browser. Changes can still be made at this point, but they are reflected to the client only. The Render event can be overridden, as shown in Figure 6 (below). 10. DisposalAfter the page's HTML is rendered, the objects are disposed of. During the Dispose event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. You can override Dispose, as shown in Figure 6.

10 | P a g e

Page 11: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Figure 6 - The Render event will output custom HTML to the browser through the HtmlTextWriter object.

Conclusion : Each time we request an ASP.NET page, we run through the same process from initialization to disposal. By understanding the inner workings of the ASP.NET page process, writing and debugging our code will be much easier and effective.

Application Life Cycle in General

The following table describes the stages of the ASP.NET application life cycle.

Stage Description

User requests an application resource from the Web server.

The life cycle of an ASP.NET application starts with a request sent by a browser to the Web server (for ASP.NET applications, typically IIS). ASP.NET is an ISAPI extension under the Web server. When a Web server receives a request, it examines the file name extension of the requested file, determines which ISAPI extension should handle the request, and then passes the request to the appropriate ISAPI extension. ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx.

Note

If a file name extension has not been mapped to ASP.NET, then ASP.NET will not receive the request. This is important to understand for applications that use ASP.NET authentication. For example, because .htm files are typically not mapped to ASP.NET, ASP.NET will not perform authentication or authorization checks on requests for .htm files. Therefore, even if a file contains only static content, if you want ASP.NET to check authentication, create the file using a file name extension mapped to ASP.NET, such as .aspx.Note

If you create a custom handler to service a particular file name extension, you must map the extension to ASP.NET in IIS and also register the handler in your application's Web.config file.

ASP.NET receives the first request for the application.

When ASP.NET receives the first request for any resource in an application, a class named ApplicationManager creates an application domain. Application domains provide isolation between applications for global variables and allow each application to be unloaded separately. Within an application domain, an instance of the class named HostingEnvironment is created, which provides access to information about the application such as the name of the folder where the application is stored.

11 | P a g e

Page 12: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

The following diagram illustrates this relationship:

ASP.NET also compiles the top-level items in the application if required, including application code in the App_Code folder. For more information, see "Compilation Life Cycle" later in this topic.

ASP.NET core objects are created for each request.

After the application domain has been created and the HostingEnvironment object instantiated, ASP.NET creates and initializes core objects such as HttpContext, HttpRequest, and HttpResponse. The HttpContext class contains objects that are specific to the current application request, such as the HttpRequest and HttpResponse objects. The HttpRequest object contains information about the current request, including cookies and browser information. The HttpResponse object contains the response that is sent to the client, including all rendered output and cookies.

An HttpApplication object is assigned to the request

After all core application objects have been initialized, the application is started by creating an instance of the HttpApplication class. If the application has a Global.asax file, ASP.NET instead creates an instance of the Global.asax class that is derived from the HttpApplication class and uses the derived class to represent the application.

Note

The first time an ASP.NET page or process is requested in an application, a new instance of HttpApplication is created. However, to maximize performance, HttpApplication instances might be reused for multiple requests.When an instance of HttpApplication is created, any configured modules are also created. For instance, if the application is configured to do so, ASP.NET creates a SessionStateModule module. After all configured modules are created, the HttpApplication class's Init method is called.

The following diagram illustrates this relationship:

12 | P a g e

Page 13: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

The request is processed by the HttpApplication pipeline.

The following events are executed by the HttpApplication class while the request is processed. The events are of particular interest to developers who want to extend the HttpApplication class.

1. Validate the request, which examines the information sent by the browser and determines whether it contains potentially malicious markup. For more information, see ValidateRequest and Script Exploits Overview.

2. Perform URL mapping, if any URLs have been configured in the UrlMappingsSection section of the Web.config file.

3. Raise the BeginRequest event.4. Raise the AuthenticateRequest event.5. Raise the PostAuthenticateRequest event.6. Raise the AuthorizeRequest event.7. Raise the PostAuthorizeRequest event.8. Raise the ResolveRequestCache event.9. Raise the PostResolveRequestCache event.10. Based on the file name extension of the requested resource (mapped in the

application's configuration file), select a class that implements IHttpHandler to process the request. If the request is for an object (page) derived from the Page class and the page needs to be compiled, ASP.NET compiles the page before creating an instance of it.

11. Raise the PostMapRequestHandler event.12. Raise the AcquireRequestState event.13. Raise the PostAcquireRequestState event.14. Raise the PreRequestHandlerExecute event.15. Call the ProcessRequest method (or the asynchronous version BeginProcessRequest)

of the appropriate IHttpHandler class for the request. For example, if the request is for a page, the current page instance handles the request.

16. Raise the PostRequestHandlerExecute event.17. Raise the ReleaseRequestState event.

13 | P a g e

Page 14: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

18. Raise the PostReleaseRequestState event.19. Perform response filtering if the Filter property is defined.20. Raise the UpdateRequestCache event.21. Raise the PostUpdateRequestCache event.22. Raise the EndRequest event.

Application Life Cycle Events and the Global.asax file

During the application life cycle, the application raises events that you can handle and calls particular methods that you can override. To handle application events or methods, you can create a file named Global.asax in the root directory of your application.

If you create a Global.asax file, ASP.NET compiles it into a class derived from the HttpApplication class, and then uses the derived class to represent the application.

An instance of HttpApplication processes only one request at a time. This simplifies application event handling because you do not need to lock non-static members in the application class when you access them. This also allows you to store request-specific data in non-static members of the application class. For example, you can define a property in the Global.asax file and assign it a request-specific value.

ASP.NET automatically binds application events to handlers in the Global.asax file using the naming convention Application_event, such as Application_BeginRequest. This is similar to the way that ASP.NET page methods are automatically bound to events, such as the page's Page_Load event.

The Application_Start and Application_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.

The following table lists some of the events and methods that are used during the application life cycle. There are many more events than those listed, but they are not commonly used.

Event or method DescriptionApplication_Start Called when the first resource (such as a page) in an ASP.NET application is

requested. The Application_Start method is called only one time during the life cycle of an application. You can use this method to perform startup tasks such as loading data into the cache and initializing static values.

You should set only static data during application start. Do not set any instance data because it will be available only to the first instance of the HttpApplication class that is created.

Application_ event Raised at the appropriate time in the application life cycle, as listed in the application life cycle table earlier in this topic.

14 | P a g e

Page 15: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Application_Error can be raised at any phase in the application life cycle.

Application_EndRequest is the only event that is guaranteed to be raised in every request, because a request can be short-circuited. For example, if two modules handle the Application_BeginRequest event and the first one throws an exception, the Application_BeginRequest event will not be called for the second module. However, the Application_EndRequest method is always called to allow the application to clean up resources.

Init Called once for every instance of the HttpApplication class after all modules have been created.

Dispose Called before the application instance is destroyed. You can use this method to manually release any unmanaged resources.

Application_End Called once per lifetime of the application before the application is unloaded.

Compilation Life Cycle

When the first request is made to an application, ASP.NET compiles application items in a specific order. The first items to be compiled are referred to as the top-level items. After the first request, the top-level items are recompiled only if a dependency changes. The following table describes the order in which ASP.NET top-level items are compiled.

Item Description

App_GlobalResourcesThe application's global resources are compiled and a resource assembly is built. Any assemblies in the application's Bin folder are linked to the resource assembly.

App_WebResources Proxy types for Web services are created and compiled. The resulting Web references assembly is linked to the resource assembly if it exists.

Profile properties defined in the Web.config file

If profile properties are defined in the application's Web.config file, an assembly is generated that contains a profile object.

App_CodeSource code files are built and one or more assemblies are created. All code assemblies and the profile assembly are linked to the resources and Web references assemblies if any.

Global.asax The application object is compiled and linked to all of the previously generated assemblies.

Once the application's top level items have been compiled, ASP.NET compiles folders, pages, and other items as needed. The following table describes the order in which ASP.NET folders and items are compiled.

Item Description

15 | P a g e

Page 16: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

App_LocalResources

If the folder containing the requested item contains an App_LocalResources folder, the contents of the local resources folder are compiled and linked to the global resources assembly.

Individual Web pages (.aspx files), user controls (.ascx files), HTTP handlers (.ashx files), and HTTP modules (.asmx files)

Compiled as needed and linked to the local resources assembly and the top-level assemblies.

Themes, master pages, other source filesSkin files for individual themes, master pages, and other source code files referenced by pages are compiled when the referencing page is compiled.

Compiled assemblies are cached on the server and reused on subsequent requests and are preserved across application restarts as long as the source code is unchanged.

Because the application is compiled on the first request, the initial request to an application can take significantly longer than subsequent requests. You can precompile your application to reduce the time required for the first request.

Application Restarts

Modifying the source code of your Web application will cause ASP.NET to recompile source files into assemblies. When you modify the top-level items in your application, all other assemblies in the application that reference the top-level assemblies are recompiled as well.

In addition, modifying, adding, or deleting certain types of files within the application's known folders will cause the application to restart. The following actions will cause an application restart:

Adding, modifying, or deleting assemblies from the application's Bin folder. Adding, modifying, or deleting localization resources from the App_GlobalResources or

App_LocalResources folders. Adding, modifying, or deleting the application's Global.asax file. Adding, modifying, or deleting source code files in the App_Code directory. Adding, modifying, or deleting Profile configuration. Adding, modifying, or deleting Web service references in the App_WebReferences directory. Adding, modifying, or deleting the application's Web.config file.

When an application restart is required, ASP.NET will serve all pending requests from the existing application domain and the old assemblies before restarting the application domain and loading the new assemblies.

HTTP ModulesThe ASP.NET application life cycle is extensible through IHttpModule classes. ASP.NET includes several classes that implement IHttpModule, such as the SessionStateModule class. You can also create your own classes that implement IHttpModule.

If you add modules to your application, the modules themselves can raise events. The application can subscribe to in these events in the Global.asax file by using the convention modulename_eventname.

16 | P a g e

Page 17: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

For example, to handle the Authenticate event raised by a FormsAuthenticationModule object, you can create a handler named FormsAuthentication_Authenticate.

The SessionStateModule class is enabled by default in ASP.NET. All session events are automatically wired up as Session_event, such as Session_Start. The Start event is raised each time a new session is created. For more information, see Session State Overview.

ASP.Net & IIS

IntroductionWhen request come from client to the server a lot of operation is performed before sending response to the client. This is all about how IIS Process the request. Before we start with the actual details, let’s start from the beginning so that each and everyone understand it's details easily.

What is Web Server?

When we run our ASP.NET Web Application from visual studio IDE, VS Integrated ASP.NET Engine is responsible to execute all kind of asp.net requests and responses. The process name is "WebDev.WebServer.Exe" which actually take care of all request and response of an web application which is running from Visual Studio IDE.

Now, the name “Web Server” come into picture when we want to host the application on a centralized location and wanted to access from many locations. Web server is responsible for handle all the requests that are coming from clients, process them and provide the responses.

What is IIS? IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has it's own ASP.NET Process Engine to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and process it and send response back to clients.

17 | P a g e

Page 18: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

How Asp.Net Request Is Processed at IIS :Hope, till now it’s clear to you that what is Web server and IIS is and what is the use of them. Now let’s have a look how they do things internally. Before we move ahead, you have to know about two main concepts 1. Worker Process2. Application Pool

Worker Process: Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system. All the ASP.Net functionality runs under the scope of worker process. When a request comes to the server from a client worker process is responsible to generate the request and response. In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS.

Application Pool: Application pool is the container of worker process. Application pools is used to separate sets of IIS worker processes that share the same configuration. Application pools enables a better security, reliability, and availability for any web application. The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn't not impact other web application as they they are configured into different application pools.

18 | P a g e

Page 19: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Application Pool with multiple worker process is called “Web Garden”.

Now, I have covered all the basic stuff like Web server, Application Pool, Worker process. Now let’s have look how IIS process the request when a new request comes up from client.

If we look into the IIS 6.0 Architecture, we can divided them into Two Layer 1. Kernel Mode2. User Mode

Now, Kernel mode is introduced with IIS 6.0, which contains the HTTP.SYS. So whenever a request comes from Client to Server, it will hit HTTP.SYS First.

Now, HTTP.SYS is Responsible for pass the request to particular Application pool. Now here is one question, How HTTP.SYS comes to know where to send the request? This is not a random pickup. Whenever we creates a new Application Pool, the ID of the Application Pool is being generated and it’s registered with the HTTP.SYS. So whenever HTTP.SYS Received the request from any web application, it checks for the Application Pool and based on the application pool it send the request.

19 | P a g e

Page 20: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

So, this was the first steps of IIS Request Processing.

Till now, Client Requested for some information and request came to the Kernel level of IIS means at HTTP.SYS. HTTP.SYS has been identified the name of the application pool where to send. Now, let’s see how this request moves from HTTP.SYS to Application Pool.

In User Level of IIS, we have Web Admin Services (WAS) which takes the request from HTTP.SYS and pass it to the respective application pool.

When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process “w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS.

Note : Sometimes if we install IIS after installing asp.net, we need to register the extension with IIS using aspnet_regiis command.

20 | P a g e

Page 21: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.

When this methods called, a new instance of HTTPContext is been created. Which is accessible using HTTPContext.Current Properties. This object still remains alive during life time of object request. Using HttpContext.Current we can access some other objects like Request, Response, Session etc.

After that HttpRuntime load an HttpApplication object with the help of HttpApplicationFactory class.. Each and every request should pass through the corresponding HTTPModule to reach to HTTPHandler, this list of module are configured by the HTTPApplication.

Now, the concept comes called “HTTPPipeline”. It is called a pipeline because it contains a set of HttpModules ( For Both Web.config and Machine.config level) that intercept the request on its way to the HttpHandler. HTTPModules are classes that have access to the incoming request. We can also create our own HTTPModule if we need to handle anything during upcoming request and response.

21 | P a g e

Page 22: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

HTTP Handlers are the endpoints in the HTTP pipeline. All request that are passing through the HTTPModule should reached to HTTPHandler. Then HTTP Handler generates the output for the requested resource. So, when we requesting for any aspx web pages, it returns the corresponding HTML output.

All the request now passes from httpModule to respective HTTPHandler then method and the ASP.NET Page life cycle starts. This ends the IIS Request processing and start the ASP.NET Page Lifecycle.

Conclusion : When client request for some information from a web server, request first reaches to HTTP.SYS of IIS. HTTP.SYS then send the request to respective Application Pool. Application Pool then forward the request to worker process to load the ISAPI Extension which will create an HTTPRuntime Object to Process the request via HTTPModule and HTTPHanlder. After that the ASP.NET Page LifeCycle events starts.

22 | P a g e

Page 23: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Control in Web Development

HTML Controls

Basic Tags

<html></html> Creates an HTML document

<head></head> Sets off the title and other information that isn’t displayed on the web page itself

<body></body> Sets off the visible portion of the document

Body Attributes

<body bgcolor="pink"> Sets the background color, using name or hex value

<body text="black"> Sets the text color, using name or hex value

<body link="blue"> Sets the color of links, using name or hex value

<body vlink="#ff0000"> Sets the color of followed links, using name or hex value

<body alink="#00ff00"> Sets the color of links on click

<body ondragstart="return false" onselectstart="return false"> Disallows text selection with the mouse and keyboard

Text Tags

<pre></pre> Creates preformatted text

<hl></hl> Creates the largest headline

<h6></h6> Creates the smallest headline

<b></b> Creates bold text

<i></i> Creates italic text

<tt></tt> Creates teletype, or typewriter-style text

23 | P a g e

Page 24: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

<cite></cite> Creates a citation, usually italic

<em></em> Emphasizes a word (with italic or bold)

<strong></strong> Emphasizes a word (with italic or bold)

<font size="3"></font> Sets size of font, from 1 to 7

<font color="green"></font> Sets font color, using name or hex value

Links

<a href="URL"></a> Creates a hyperlink

<a href="mailto:EMAIL"></a> Creates a mailto link

<a href="URL"><img src="URL"> </a> Creates an image/link

<a name="NAME"></a> Creates a target location within a document

<a href="#NAME"></a> Links to that target location from elsewhere in the document

Formatting

<p></p> Creates a new paragraph

<p align="left"> Aligns a paragraph to the left (default), right, or center.

<br> Inserts a line break

<blockquote></blockquote> Indents text from both sides

<dl></dl> Creates a definition list

<dt> Precedes each definition term

<dd> Precedes each definition

<ol></ol> Creates a numbered list

<ul></ul> Creates a bulleted list

<li></li> Precedes each list item, and adds a number or symbol depending upon the type of list selected

24 | P a g e

Page 25: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

<div align="left"> A generic tag used to format large blocks of HTML, also used for stylesheets

<img src="name"> Adds an image

<img src="name" align="left"> Aligns an image: left, right, center; bottom, top, middle

<img src="name" border="1"> Sets size of border around an image

<hr /> Inserts a horizontal rule

<hr size="3" /> Sets size (height) of rule

<hr width="80%" /> Sets width of rule, in percentage or absolute value

<hr noshade /> Creates a rule without a shadow

Tables

<table></table> Creates a table

<tr></tr> Sets off each row in a table

<td></td> Sets off each cell in a row

<th></th> Sets off the table header (a normal cell with bold, centered text)

Table Attributes

<table border="1"> Sets width of border around table cells

<table cellspacing="1"> Sets amount of space between table cells

<table cellpadding="1"> Sets amount of space between a cell’s border and its contents

<table width="500" or "80%"> Sets width of table, in pixels or as a percentage of document width

<tr align="left"> or <td align="left"> Sets alignment for cell(s) (left, center, or right)

<tr valign="top"> or <td valign="top"> Sets vertical alignment for cell(s) (top, middle, or bottom)

<td colspan="2"> Sets number of columns a cell should span (default=1)

<td rowspan="4"> Sets number of rows a cell should span (default=1)

25 | P a g e

Page 26: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

<td nowrap> Prevents the lines within a cell from being broken to fit

Frames

<frameset></frameset> Replaces the <body> tag in a frames document; can also be nested in other framesets

<frameset rows="value,value"> Defines the rows within a frameset, using number in pixels, or percentage of width

<frameset cols="value,value"> Defines the columns within a frameset, using number in pixels, or percentage of width

<frame> Defines a single frame — or region — within a frameset

<noframes></noframes> Defines what will appear on browsers that don’t support frames

Frames Attributes

<frame src="URL"> Specifies which HTML document should be displayed

<frame name="name"> Names the frame, or region, so it may be targeted by other frames

<frame marginwidth="value"> Defines the left and right margins for the frame; must be equal to or greater than 1

<frame marginheight="value"> Defines the top and bottom margins for the frame; must be equal to or greater than 1

<frame scrolling="value"> Sets whether the frame has a scrollbar; value may equal “yes,” “no,” or “auto.” The default, as in ordinary documents, is auto.

<frame noresize="noresize"> Prevents the user from resizing a frame

Forms

For functional forms, you’ll have to run a script. The HTML just creates the appearance of a form.

<form></form> Creates all forms

<select multiple name="NAME" size=?></select> Creates a scrolling menu. Size sets the number of menu items visible before you need to scroll.

<option> Sets off each menu item

26 | P a g e

Page 27: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

<select name="NAME"></select> Creates a pulldown menu

<option> Sets off each menu item

<textarea name="NAME" cols=40 rows=8></textarea name> Creates a text box area. Columns set the width; rows set the height.

<input type="checkbox" name="NAME"> Creates a checkbox. Text follows tag.

<input type="radio" name="NAME" value="x"> Creates a radio button. Text follows tag

<input type="text" name="NAME" size=20> Creates a one-line text area. Size sets length, in characters.

<input type="submit" value="NAME"> Creates a Submit button

<button type="submit">Submit</button> Creates an actual button that is clicked

<input type="image" border=0 name="NAME" src="name.gif"> Creates a Submit button using an image

<input type="reset"> Creates a Reset button

HTML 5 adds a few (and HTML5 seems to not use some of the ones above as well):

<audio src=url> <button formaction=url> <command icon=url> <embed src=url> <html manifest=url> <input formaction=url> <source src=url> <video poster=url> and <video src=url>

These aren't necessarily simple URLs:

<object archive=url> or <object archive="url1 url2 url3"> <applet archive=url> or <applet archive=url1,url2,url3> <meta http-equiv="refresh" content="seconds; url">

In addition, the style attribute can contain css declarations with one or several urls. For example: <div style="background: url(image.png)">

27 | P a g e

Page 28: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Asp.Net Controls

Server Controls are the tags that are understood by the server. There are basically three types of server controls.

HTML Server Controls - Traditional HTML tags Web Server Controls - New ASP. NET tags Validation Server Controls - For input validation

 

ASP.NET HTML Server Controls

ASP.NET provides a way to work with HTML Server controls on the server side; programming with a set of controls collectively is called HTML Controls.

These controls are grouped together in the Visual Studio Toolbox in the the HTML Control tab. The markup of the controls are similar to the HTML control.

These controls are basically the original HTML controls but enhanced to enable server side processing.

HTML elements in ASP. NET files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control.

Note:

All HTML server controls must be within a <form> tag with the runat="server" attribute. The runat="server" attribute indicates that the form should be processed on the server. It also indicates that the enclosed controls can be accessed by server scripts.

The System.Web.UI.HtmlControls.HtmlControl base class contains all of the common properties. HTML server controls derive from this class.

For example, consider the HTML input control:

The following table describes the HTML server controls:

28 | P a g e

Page 29: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

ASP.NET Web Server Controls

Web server controls are special ASP. NET tags understood by the server. Like HTML server controls, Web server controls are also created on the server and

they require a runat="server" attribute to work. However, Web server controls do not necessarily map to any existing HTML elements

and they may represent more complex elements. Mostly all Web Server controls inherit from a common base class, namely the

WebControl class defined in the System.Web.UI.WebControls namespace.

The syntax for creating a Web server control is:

The following table describes the WEB server controls:

29 | P a g e

Page 30: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

ASP.NET Validation Server Controls

After you create a web form, you should make sure that mandatory fields of the form elements such as login name and password are not left blank; data inserted is correct and is within the specified range. Validation is the method of scrutinizing (observing) that the user has entered the correct values in input fields.

A Validation server control is used to validate the data of an input control. If the data does not pass validation, it will display an error message to the user.

In ASP. NET you can use ASP. NET Validation Controls while creating the form and specify what ASP. NET Validation Controls you want to use and to which server control you want bind this.

Validation Controls are derived from a common base class and share a common set of properties and methods. You just have to drag and drop the ASP. NET Validation Control in the web form and write one line of code to describe its functionality.

This reduces the developer time from writing JavaScript for each type of validation. Moreover, through ASP. NET Validation Controls if any invalid data is entered the browser itself detects the error on the client side and displays the error without requesting the server. This is another advantage because it reduces the server load.

30 | P a g e

Page 31: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Some Server Validation controls are:

The syntax for creating a Validation server control is:

Label <asp:Label ID="lblInfoMessage" runat="server" Text="Label"></asp:Label>

Textbox<asp:TextBox ID="txtusername" runat="server" MaxLength="20" Width="180px" ></asp:TextBox>

<asp:TextBox ID="txtpassword" runat="server" TextMode="Password" MaxLength="15" Width="180px">

Button<asp:Button ID="btnRegister" runat="server" Text="btnsubmit" BackColor="#ecf3f9" style="background-image:url(img/submit.gif); width:74px; height:24px; border:none; background-repeat:no-repeat;" onclick="btnRegister_Click" />

Events of Button

protected void btnRegister_Click(object sender, EventArgs e){

}

Sample ProgramAdd.aspx

31 | P a g e

Page 32: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

<form id="form1" runat="server"> <div> <table> <tr> <td> <asp:Label ID="lblNumber1" Text="Enter Number1" runat="server"></asp:Label> </td> <td> <asp:TextBox ID="txtNumber1" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblNumber2" Text="Enter Number2" runat="server"></asp:Label> </td> <td> <asp:TextBox ID="txtNumber2" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Button ID="btnAdd" Text="ADD" runat="server" onclick="btnAdd_Click" /> </td> <td> <asp:TextBox ID="txtTotal" runat="server" ></asp:TextBox> </td> </tr> </table> </div> </form>

Add.aspx.cs

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {

}

protected void btnAdd_Click(object sender, EventArgs e) { int number1 = 0; int number2 = 0; int total = 0; if (txtNumber1.Text != "") number1 = Convert.ToInt32(txtNumber1.Text.ToString());

if (txtNumber2.Text != "") number2 = Convert.ToInt32(txtNumber2.Text.ToString());

32 | P a g e

Page 33: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

total = number1 + number2;

txtTotal.Text = total.ToString();

} }

Common Properties of ASP.Net ControlsProperty Description

AccessKey Allows you to set a key with which a control can be accessed in the client by pressing the associated letter.

BackColor

ForeColor

Allows you to change the color of the background (BackColor) and text (Fore Color) of the control in the browser.

BorderColorBorderStyleBorderWidthChanges the border of the control in the browser. The similarities with the CSS border properties you saw in the previous chapter are no coincidence. Each of these three ASP.NET properties maps directly to its CSS counterpart.

CssClass Lets you define the HTML class attribute for the control in the browser.

EnabledDetermines whether the user can interact with the control in the browser. For example, with a disabled text box (Enabled=”false”) you cannot change its text.

Font Allows you to define different font-related settings, such as Font-Size, Font-Names, and Font-Bold.

Height

WidthDetermines the height and width of the control in the browser.

TabIndex Sets the HTML tabindex attribute that determines the order in which users can move through the controls in the page by pressing the Tab key.

ToolTipAllows you to set a tooltip for the control in the browser. This tooltip, rendered as a title attribute in the HTML is shown when the user hovers the mouse over the relevant HTML element.

Visible

Determines whether the control is sent to the browser or not. You should really see this as a server-side visibility setting because an invisible control is never sent to the browser at all. This means it’s quite different from the CSS display and visibility properties you saw in the previous chapter that hide the element at the client.

Checkbox

<asp:CheckBox ID="ChkTermsConditn" runat="server" >I have read and understood and agree to the Terms and Conditions.

</asp:CheckBox>

33 | P a g e

Page 34: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

if (ChkTermsConditn.Checked == true){

//Statements

}

Radiobutton

<asp:RadioButton ID="rdbtnmale" text="Male" GroupName="gender" runat="server" Checked="true" /> <br /> <asp:RadioButton ID="rdbtnfemale" Text="Female" GroupName="gender" runat="server" />

string smale;

protected void btnsubmit_Click(object sender, EventArgs e) {

if (rdbtnmale.Checked == true) { smale = rdbtnmale.Text.ToString(); } else { smale = rdbtnfemale.Text.ToString(); } }

LabTo Develop a Student Registration Form along with sql server table and insert the record into sql server table.

DropDownList

<asp:DropDownList ID="ddl_state" runat="server" Height="20px" Width="132px" AutoPostBack="True" onselectedindexchanged="ddl_state_SelectedIndexChanged"></asp:DropDownList>

public void DataBindState() { scon.Open(); DataTable dtstate = new DataTable(); scom = new SqlCommand("select * from State", scon); sda = new SqlDataAdapter(scom); sda.Fill(dtstate);

34 | P a g e

Page 35: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

ddl_state.DataSource = dtstate; ddl_state.DataTextField = "statename"; ddl_state.DataValueField = "stateid"; ddl_state.DataBind(); scon.Close(); }<asp:DropDownList ID="ddl_city" runat="server" Height="20px" Width="132px"></asp:DropDownList>

public void DataBindCity() { scon.Open(); DataTable dtcity = new DataTable(); int State_id = Convert.ToInt32(ddl_state.SelectedValue.ToString());

scom = new SqlCommand("select cityname,cityid from City where stateid=" + State_id, scon); sda = new SqlDataAdapter(scom); sda.Fill(dtcity); ddl_city.DataSource = dtcity; ddl_city.DataTextField = "cityname"; ddl_city.DataValueField = "cityid"; ddl_city.DataBind(); scon.Close(); }

protected void ddl_state_SelectedIndexChanged(object sender, EventArgs e) { DataBindCity(); }

LabTo Develop a Screen to Show country,State,City in DropDown in a screen and Add Country , State and City in the screen

Checkbox List

<asp:CheckBoxList ID="chk_languages" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" Font-Names="Tahoma"> </asp:CheckBoxList>

DataTable dt1 = new DataTable(); scom = new SqlCommand("select * from languages",scon); SqlDataAdapter sda1 = new SqlDataAdapter(scom); sda1.Fill(dt1); chk_languages.DataSource = dt1; chk_languages.DataTextField = "name"; chk_languages.DataValueField = "lid"; chk_languages.DataBind();

35 | P a g e

Page 36: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

FileUpLoad<asp:FileUpload ID="FileResume" runat="server" />

if (FileResume != null && FileResume.FileName != ""){ lblFileName.Text = FileResume.FileName.ToString();FileResume.SaveAs(Server.MapPath(@"~\UploadedFiles\" + FileResume.FileName));

}

HyperLink

<asp:HyperLink NavigateUrl="~/ChildPageDemo.aspx" ID="hykNext" Text="Next" runat="server"></asp:HyperLink>

Master PageDemo.Master

<body> <form id="form1" runat="server"> <div> <table border="1" width="700" height="600" > <tr height="100"> <td ><h1>Master Page - Header</h1></td> </tr> <tr> <td> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

</asp:ContentPlaceHolder> </td> </tr> <tr height="100"> <td><h1>Master Page - Footer</h1></td> </tr>

</table> </div> </form></body>

ChildPageDemo.aspx

<%@ Page Language="C#" MasterPageFile="~/Demo.Master" AutoEventWireup="true" CodeBehind="ChildPageDemo.aspx.cs" Inherits="Demo_Samples.ChildPageDemo" Title="Untitled Page" %><asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"

36 | P a g e

Page 37: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

runat="server"><table ><tr ><td><asp:Label ID="lblEmail" Text="Email Address" runat="server" ></asp:Label></td><td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td></tr><tr ><td colspan="2" ><asp:Button Text="Submit" ID="btnSubmit" runat="server" /></td></tr>

</table></asp:Content>

Menus<asp:Menu ID="mnuTop" Orientation="Horizontal" runat="server">

<Items> <asp:MenuItem Text="Home" ToolTip="Go To Home" NavigateUrl="~/Index.htm"></asp:MenuItem>

<asp:MenuItem Text="About Us" ToolTip="Go To About Us" NavigateUrl="~/About.htm" ></asp:MenuItem>

<asp:MenuItem Text="Contact Us" ToolTip="Go To Contact Us" NavigateUrl="~/ContactUs.htm"></asp:MenuItem>

</Items> </asp:Menu>

Validation Controls in ASP.net

Validation server controls are a series of controls that help you validate the data that the user enters into the other controls that are provided with ASP.NET. They determine whether the form can be processed based upon the rules that you define in the validation server controls.

Understanding the Difference Between Server-Side and Client-Side Validation

After the user enters data into a Web form, clicks the Submit button, and sends the form data to the server as a request, you can perform server-side validation on the data. If the data is incorrect or not valid, you can send back a response stating this.

37 | P a g e

Page 38: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

If, however, when the user clicks the Submit button, a scripting language that is part of the overall HTML page is initiated to check the validity of the data before it is sent to the server, this is client-side validation.

The bad thing about server-side validation is that it requires trips back and forth to the server. This takes a lot of resources and makes for a slower-paced form for the user.

The other option for form validation is to put some client-side JavaScript or VBScript at the top of the ASP page that checks if the information in the fields is correct. This takes care of the problem of making unnecessary trips to the server, but it requires another language to learn and manage. JavaScript is a great language, but takes a lot of time to master, and there are always problems getting your JavaScript code to work on different browsers.

Listing 1: Client-side JavaScript for form validation

<script language="javascript"><!--Function CheckForm(form){ for(var intCtr = 0; intCtr <= (form.elements.length - 5); ++intCtr) { var temp = form.elements[intCtr]; if(temp.type == "text" && temp.value == "") { alert("Please Enter All Information!"); temp.focus(); return false; } } return true;}//--></script>

This sample piece of JavaScript does some validation, but it doesn't check for all the in-formation that you might need on the form you are building. This piece of code determines only whether the user entered anything at all in all five fields within the form. It does not determine whether the user entered an actual e-mail address within the e-mail address text box, whether the user entered a number between two given numbers, or whether the password and the confirm password text boxes match.

.NET Validation Controls

You can also customize validation for your own needs. Then, if there are any errors in the form data, these validation server controls enable you to customize the display of error information on the browser.

Available validation server controls

38 | P a g e

Page 39: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Validation Server Control DescriptionRequiredFieldValidator Ensures that the user does not skip a form entry field

CompareValidatorAllows for comparisons between the user's input and another item using a comparison operator (equals, greater than, less than, and so on)

RangeValidator Checks the user's input based upon a lower- and upper-level range of numbers or characters

RegularExpressionValidatorChecks that the user's entry matches a pattern defined by a regular expression. This is a good control to use to check e-mail addresses and phone numbers

ValidationSummary Displays all the error messages from the validators in one specific spot on the page

Not all button clicks are equal

Normally, in a series of HTML form elements, there is some sort of Button, ImageButton, or LinkButton control on the page that submits the form and causes the validation to initiate.

You may not want each and every button on the ASP.NET page to initiate validation.

For instance, you might have a Cancel or Reset button on the Web page. If the user clicks one of these buttons, you don't want that button click to validate the contents contained in the Web form.

To prevent this, you have to set the CausesValidation property for the control to False.

<asp:Button id="Button1" runat="server" Text="Button" CausesValidation="False"></asp:Button>

The RequiredFieldValidator Control

The RequiredFieldValidator server control makes sure that the user enters something into the field that it is associated with in the form. You need to tie the RequiredFieldValidator to each control that is a required field in the form.

<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>&nbsp; <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Required!" ControlToValidate="TextBox1"></asp:RequiredFieldValidator></p><p><asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button">

39 | P a g e

Page 40: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

</asp:Button> </p> <p> <asp:Label id="Label1" runat="server"></asp:Label></p>

When you click the button, you get a result similar to that shown in Figure 1.

Figure 1: Causing the RequiredFieldValidator server control to fire

ControlToValidate : The value assigned to this control needs to be the value of the id property for the control to which you want to link the RequiredFieldValidator control. You can link only one RequiredFieldValidator server control to any other server control on the page.

ErrorMessage property. This is the text that appears where the RequiredFieldValidator control is located on the ASP.NET page if the TextBox is left empty. Instead of using the ErrorMessage property, you can also use the Text property

<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" Text="Required!" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>

Or you can use the following construct:

<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"> Required! </asp:RequiredFieldValidator>

By default, red text is used for the error messages that are shown by these validation server controls. As with most of the ASP.NET server controls, however, you can change the style of the controls by changing the properties of the control in code or within the designer. For instance, you can apply a more complex style as illustrated here:

40 | P a g e

Page 41: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" BackColor="DarkGray" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" ForeColor="White" Font-Bold="True" Font-Names="Verdana" Font-Size="X-Small">&nbsp;Enter something&nbsp;</asp:RequiredFieldValidator>

Using code similar to the preceding, you can get a more elaborate result, as shown in Figure 2.

Figure 2: A RequiredFieldValidator control with a little more style

Note The RequiredFieldValidation server control works with most HTML form elements except for check boxes. You cannot validate against the CheckBox or CheckBoxList server controls using the RequiredFieldValidator server control.

Instead you need to use the CustomValidator server control. An example of this is shown later in this article.Using the InitialValue Property with a DropDownList Control

A good way of using the InitialValue property is with the DropDownList server control. For instance, a drop-down list might have a default value that is not an empty value (by default, some text appears in it). An example of a drop-down list with the RequiredFieldValidator that uses the InitialValue property is illustrated in Listing 5.

Listing 5: Using the RequiredFieldValidator server control with the Drop-DownList server control

<asp:DropDownList id="DropDownList1" runat="server"> <asp:ListItem Selected="True">Select a profession</asp:ListItem> <asp:ListItem>Programmer</asp:ListItem>

41 | P a g e

Page 42: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

<asp:ListItem>Lawyer</asp:ListItem> <asp:ListItem>Doctor</asp:ListItem> <asp:ListItem>Artist</asp:ListItem></asp:DropDownList> &nbsp;<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please make a selection" ControlToValidate="DropDownList1" InitialValue="Select a profession"></asp:RequiredFieldValidator>

Figure 3: Validation error based upon the DropDownList control

The CompareValidator Control

The CompareValidator server control compares the value entered into the form field to another field, a database value, or other value that you specify. When comparing against data types, you just set the Operator—DataTypeCheck. After that is done, you can set the Type attribute to String, Integer, Double, Date, or Currency in the CompareValidator control to make sure that the user's input into the field is the specified type.

Using the CompareValidator server control, you can make comparisons between different controls within a form on your ASP.NET page. For example, if you want to compare what the user enters in the Password field to the entry in the Confirm Password field to see whether they are the same, you can use the CompareValidator server control.

Listing 6: Using the CompareValidator server control

<%@ Page Language="C#" %><html>

42 | P a g e

Page 43: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

<head></head><body> <form runat="server"> <p> Password<br> <asp:TextBox id="TextBox1" runat="server" TextMode="Password"></asp:TextBox> &nbsp;<asp:CompareValidator id="CompareValidator1" runat="server" ErrorMessage="Passwords do not match!" ControlToValidate="TextBox2" ControlToCompare="TextBox1"></asp:CompareValidator> </p> <p> Confirm Password<br><asp:TextBox id="TextBox2" runat="server" TextMode="Password"></asp:TextBox> </p> <p><asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Login"></asp:Button> </p> <p> <asp:Label id="Label1" runat="server"></asp:Label> </p> </form></body></html>

In this example, the Web form uses two TextBox server controls. One is for the user to enter the password, and the second TextBox control requires the user to enter the password again to ensure they didn't mistype the original. By using the CompareValidator server control, you guarantee that they are equal strings. If they are not equal, the page returns an error message (see Figure 4). If they are equal, your page submits as valid.

Figure 4: In this example, the user mistyped the password and got an error message.

43 | P a g e

Page 44: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Validating Against Constants

You can also use the CompareValidator server control to make sure that the value typed into the form field by a user is valid when compared against a constant, some dynamic value that you retrieve, or that it adheres to a specific data type. Listing 7 shows an example of this.

Listing 7: Checking to make sure value entered is of a specific data type

Age: <asp:TextBox id="TextBox1" runat="server" MaxLength="3"> </asp:TextBox>&nbsp;<asp:CompareValidator id="CompareValidator1" runat="server" ErrorMessage="You must enter a number" ControlToValidate="TextBox1" Type="Integer" Operator="DataTypeCheck"></asp:CompareValidator>

In this example, the user must enter an integer in the text box; otherwise, the CompareValidator server control fires and displays an error message on the page. By giving the Type property of the CompareValidator server control a value of Integer, you ensure that the value entered in the text box conforms to this .NET Framework data type.

You also have the option of not only comparing values against specific data types, but also ensuring that values are valid when compared against certain constants (see Listing 8).

Listing 8: Comparing values against constants for validityAge: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>&nbsp;<asp:CompareValidator id="CompareValidator1" runat="server" Operator="GreaterThan" ValueToCompare="18" ControlToValidate="TextBox1" ErrorMessage="You must be older than 18 to join" Type="Integer"></asp:CompareValidator>

In this case, a few checks are made against any value that the user types in the text box. The first is based on the Type property in the CompareValidator server control. The Type property has the value of Integer, therefore any value placed in the text box needs to conform to this .NET Framework data type. If the user enters a string into the text box, the form submission is invalid.

The next property is the Operator property. This property has a value of GreaterThan, meaning that for the form submission to be valid, the value entered in the text box has to be greater than the value that is assigned to the ValueToCompare property.

For this CompareValidator server control, the ValueToCompare property has a value of 18. This means that the value entered in the text box on the page must be an integer greater than 18. If it does not meet these criteria, the value is considered invalid, and the CompareValidator server control displays an error message in the browser.

44 | P a g e

Page 45: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

In the situation shown in Listing 8, you are not comparing two fields in the form; instead, you are comparing one field against a value that you have specified in code. The Operator property can contain one of the following values:

Equal | NotEqual | GreaterThan | GreaterThanEqual | LessThan | LessThanEqual | DataTypeCheck

The RangeValidator Control

The RangeValidator server control is similar to the CompareValidator server control, but the RangeValidator server control compares what is entered into the form field with two values and makes sure that what was entered by the user is between these two specified values.

Marks: <asp:TextBox ID="txtMarks" runat="server" /> <asp:RangeValidator ID="rvMarks" runat="server" ErrorMessage="Value is out of range" ControlToValidate="txtMarks" Type="Integer" MinimumValue="0" MaximumValue="100" />

For instance, imagine that you have a text box where you want end users to enter their ages

Listing 9: Using the RangeValidator server control to work with a range of numbers

Age: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> &nbsp;<asp:RangeValidator id="RangeValidator1" runat="server" ControlToValidate="TextBox1" Type="Integer" ErrorMessage="You must be between 30 and 40" MaximumValue="40" MinimumValue="30"></asp:RangeValidator>

In this case, the user should enter a value between 30 and 40 in the text box. If some number is entered that is outside of this range, the RangeValidator server control fires an error message and considers the form submission invalid.

The Type property enables you to make comparisons against many different .NET Framework types, such as String, Integer, Double, Date, and Currency. These choices enable you to do a number of range comparisons. You can also use the Date value for the Type property to make sure that the entry is between specific date ranges.

45 | P a g e

Page 46: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Listing 10: Comparing an entry to a range of charactersFor example, if the user is entering her last name, and you want only people with last names starting with M and P to proceed, you can easily do this by using the RangeValidator server control, as illustrated in Listing 10.Last name: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> &nbsp;<asp:RangeValidator id="RangeValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Your last name needs to be between M and P" MaximumValue="Q" MinimumValue="M"></asp:RangeValidator>

In the example in Listing 10, the value is being checked against a range that is specified by using the MaximumValue and MinimumValue properties. In this example, that the Type property is not specified. In this case, it doesn't need to be specified because the default value of the Type property is String.

Age:<asp:TextBox id="TextBox4" runat="server"></asp:TextBox> &nbsp;<asp:RangeValidator id="RangeValidator1" runat="server" ControlToValidate="TextBox4" Type="Integer" ErrorMessage="You must be between 30 and 40" MaximumValue="40" MinimumValue="30"></asp:RangeValidator> <br />

Last name:<asp:TextBox id="TextBox5" runat="server"></asp:TextBox> &nbsp;<asp:RangeValidator id="RangeValidator2" runat="server" ControlToValidate="TextBox5" ErrorMessage="Your last name needs to be between M and P" MaximumValue="Q" MinimumValue="M"></asp:RangeValidator>

The RegularExpressionValidator Control

The RegularExpressionValidator server control is a validation control that enables you to check the user's input based on a pattern defined by a regular expression. In the past, these kinds of validations took a considerable amount of JavaScript coding. The RegularExpressionValidator control with ASP.NET saves coding time.

46 | P a g e

Page 47: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Figure 5: The Regular Expression Editor

For an example of using the RegularExpressionValidator server control to make sure that a value entered in a text box is an e-mail address, look at Listing 11.

Listing 11: Validating an e-mail address

Email: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> &nbsp;<asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="You must enter an email address" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>

In this example, notice that you place the Internet e-mail address regular expression in your ValidationExpression property. The great thing is that it is pretty simple, and it takes hardly any coding. Figure 6 shows the error message that results if a user enters an incorrect e-mail address in the text box.

47 | P a g e

Page 48: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Figure 6: Validating whether an e-mail address is entered in a text box

Note The e-mail address is checked only to see whether it is in the correct format. The e-mail address is not checked in to ensure that it is an actual e-mail address.

A great place on the Internet to find free regular expressions is the RegEx Library at RegExLib.com.

Using Images for Your Error Messages

One interesting way of showing your error messages when using validation controls is to use images along with text for identifying errors on your ASP.NET pages. This secret is not limited to the RegularExpressionValidator server control, but can be used with all the validation server controls.

To use an image instead of text for your error messages, you create something similar to the code in Listing 13.

Listing 13: Using images for your validation messages

Email: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> &nbsp;<asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage='<img src="error.gif">' ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>

To use an image instead of text for your error messages, you use an HTML string that points to the image that you want to display for the value of the ErrorMessage property (see Figure 7).

48 | P a g e

Page 49: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Figure 7: An image is displayed when the incorrect e-mail address is entered.

The CustomValidator Control

The CustomValidator server control enables you to develop your own custom server-side or client-side validations. At times, you may want to compare the user's input to a value in a database, or to determine whether his input conforms to some arithmetic validation that you are looking for (for instance, if the number is even or odd). You can do all this and more by using this type of validation control.

Client-side Validation

One of the cool things about using the validation controls, in general, is that they allow for client-side validation of certain HTML server controls. As I said, you can create your own JavaScript functions that provide you with a higher level of validation capabilities.

Listing 14 illustrates how to use JavaScript and the CustomValidator server control to expand upon the default validation capabilities that are provided to you with the .NET Framework.

Visual C# .NET

<%@ Page Language="C#" %><script runat="server">

void Button1_Click(Object sender, EventArgs e) { Label1.Text = "VALID NUMBER!"; }

</script><html><head> <script language="JavaScript">

49 | P a g e

Page 50: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

function validateNumber(oSrc, args) { args.IsValid = (args.Value % 5 == 0); } </script></head><body> <form runat="server"> <p> Number: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> &nbsp;<asp:CustomValidator id="CustomValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Number must be divisible by 5" ClientValidationFunction="validateNumber"></asp:CustomValidator> </p> <p> <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button> </p> <p> <asp:Label id="Label1" runat="server"></asp:Label> </p> </form></body></html>

The important part of the CustomValidator server control here is the ClientValidationFunction property. The value of this property must be the client-side JavaScript function that is in the page—in this case, the validateNumber function. By simply using this with the ClientValidationFunction property, you have tied the validation process to the custom client-side function that you created, as illustrated in Figure 8.

Figure 8: Performing a custom client-side validation using the CustomValidator server control

50 | P a g e

Page 51: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

You set the args.IsValid property to either True or False in the JavaScript function. The args.Value property is the value from the user that is retrieved from the control that the CustomValidator server control is tied to.

Using the ClientValidationFunction property enables you to incorporate your own JavaScript functions into ASP.NET controls so that they behave like the other validation controls.

Server-side Validation

The other way of performing validation on Web forms using the CustomValidator server control is to use server-side validation. This is just as easy as the client-side validation.

Server-side validation of your Web forms enables you to create rather elaborate validation capabilities. Listing 15 shows you a not-too-elaborate example of server-side checking. Here the code determines whether the number entered in the text box on the ASP.NET page is even.

Visual C# .NET

<%@ Page Language="C#" %><script runat="server">

void Button1_Click(Object sender, EventArgs e) { if (Page.IsValid) { Label1.Text = "VALID ENTRY!"; } }

void ValidateNumber(object source, ServerValidateEventArgs args) { try { int num = int.Parse(args.Value); args.IsValid = ((num%5) == 0); } catch(Exception ex) { args.IsValid = false; } }

</script><html><head></head><body> <form runat="server"> <p> Number: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> &nbsp;

51 | P a g e

Page 52: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

<asp:CustomValidator id="CustomValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Number must be even" OnServerValidate="ValidateNumber"></asp:CustomValidator> </p> <p> <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button> </p> <p> <asp:Label id="Label1" runat="server"></asp:Label> </p> </form></body></html>Performing custom server-side validation with the CustomValidator server controls requires that you use the OnServerValidate property instead of the ClientValidationFunction property. The ClientValidationFunction is used with the CustomValidator server control when working with client-side validation.

In this case, you need to give the OnServerValidate property a value that is equal to the name of the server-side function that you would write in one of the .NET-compliant languages.

Making Validation More Secure

If you are going to use the CustomValidator server control for client-side validation, you should also consider re-evaluating the user's input using a server-side validation function.

It is not too hard for some people to post a form back to your server and bypass or fool the client-side validation. If you re-evaluate the input on the server, you can stop this from occurring, making your ASP.NET applications more secure.

Using the CustomValidator server control to validate the Checkbox server control

If you have been working through the examples so far in this article, note that there wasn't a validation server control in place that was able to validate the CheckBox server control. Don't be too worried. You can use the CustomValidator server control to work through this control. You can use it any time that a validation server control on your page is not using the ControlToValidate property. For an example of this, see Listing 16.

<%@ Page Language="C#" %><script runat="server">

void CustomValidator1_ServerValidate(Object source, ServerValidateEventArgs args) { args.IsValid = (CheckBox1.Checked == true); }

void Button1_Click(Object sender, EventArgs e) { if (Page.IsValid) {

52 | P a g e

Page 53: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Label1.Text = "Thank you for your donation!"; } else { Label1.Text = ""; } }

</script><html><head></head><body> <form runat="server"> <p> Check checkbox if you want to donate $10 </p> <p> <asp:CheckBox id="CheckBox1" runat="server" Text="Donate $10"></asp:CheckBox> &nbsp; <asp:CustomValidator id="CustomValidator1" runat="server" ErrorMessage="Please donate $10" OnServerValidate="CustomValidator1_ServerValidate"> </asp:CustomValidator> </p> <p> <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Submit"></asp:Button> </p> <p> <asp:Label id="Label1" runat="server"></asp:Label> </p> </form></body></html>

Note that a CheckBox server control appears on the page. Also notice that there isn't a validation server control on the page that has this CheckBox server control tied to it via any property settings. Instead, a CustomValidator server control on the page references a server-side function called CustomValidator1_ServerValidate.

Within this server-side function, validation performed in the code checks whether the CheckBox server control's Checked property has a value of True (meaning that it is checked). If the value of this property is True, the CustomValidator server control is passed a True value—meaning that the input passed the test.

The CustomValidator server control enables you to do almost any type of validations that you can think of. This is a great control to use if you do any database validations on the input that is entered into a form by a user. This control can also apply any complicated logic that you want to include in the validation process.

53 | P a g e

Page 54: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

The ValidationSummary Control

The ValidationSummary server control works with all the validation server controls on the page. It takes all the error messages that the other validation controls send back to the page and puts them all in one spot (that you specify) on the page. These error messages can be displayed in a list, bulleted list, or paragraph.

Showing a Bulleted List of Errors

You can use the ValidationSummary server control in a number of ways, but the example in Listing 17 shows you how to use it in a simple manner. For this example, two text boxes on the page are associated with a RequiredFieldValidator control. When an error is triggered, not only does it display the error next to the text box itself, it also displays it in a summary at the bottom of the ASP.NET page.

Listing 17: Having a summary of errors appear on the screen

<p>First name <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> &nbsp; <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="You must enter your first name" ControlToValidate="TextBox1"></asp:RequiredFieldValidator></p><p>Last name <asp:TextBox id="TextBox2" runat="server"></asp:TextBox> &nbsp; <asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="You must enter your last name" ControlToValidate="TextBox2"></asp:RequiredFieldValidator></p><p> <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Submit"></asp:Button></p><p> <asp:ValidationSummary id="ValidationSummary1" runat="server" HeaderText="You received the following errors:"> </asp:ValidationSummary></p><p> <asp:Label id="Label1" runat="server"></asp:Label></p>

Using this kind of construct, when the validation server control is triggered, error messages similar to the ones shown in Figure 9 appear on the screen.

54 | P a g e

Page 55: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Figure 9: Validation errors shown using the ValidationSummary server control

By default, the ValidationSummary server control shows the errors in a bulleted list on the page using red text. You have the option to completely alter how output displays in the browser.

To change how the error messages are displayed, you can change the value of the DisplayMode property of the ValidationSummary control. The possible values of this control can be set to the following:

BulletList List SingleParagraph

If you use the BulletList value for the DisplayMode property, it appears as shown in Figure 11. If you use List, it appears without bullets. If you use SingleParagraph, the errors appear in a text area all on one line in a single paragraph.

Showing a Dialog Box Containing Error Notifications

One flexible feature of the ValidationSummary server control is that you can easily show the ASP.NET page's errors in a pop-up dialog box. You have the option of showing the summary in the browser and the dialog box together, or just in the dialog box.

55 | P a g e

Page 56: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

The property that controls whether the message appears in the browser is the ShowSummary property. To turn off the display of validation errors in the browser, set the value of the ShowSummary property to False. To show validation errors in a dialog box, set the ValidationSummary control's ShowMessageBox property to True (see Listing 18).

Listing 18: Showing errors in a dialog box

<asp:ValidationSummary id="ValidationSummary1" runat="server" ShowMessageBox="True" ShowSummary="False"></asp:ValidationSummary>

This code produces results similar to those in Figure 10.

Figure 10: A dialog box showing the page's validation errors

Understanding the Difference Between the Error Message and Text Properties

In the examples shown so far using the ValidationSummary server control, the error messages were next to the items that were being validated (the RequiredFieldValidator server controls) and were displayed within the ValidationSummary server control. One ideal way of presenting this validation-error information is to have an asterisk (*) appear next to the HTML form fields in question, while the error messages stating what is wrong with the input appear in the list of errors shown within the ValidationSummary control.

To accomplish this, you use the specific validation controls—not the ValidationSummary server control itself. For instance, if there is a RequiredFieldValidator server control validating a text box, you construct this validation control as shown in Listing 19.

56 | P a g e

Page 57: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Listing 19: Showing text differently than it is displayed in the ValidationSummary server control

<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="You must enter your first name" ControlToValidate="TextBox1">*</asp:RequiredFieldValidator>Or:<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="You must enter your first name" ControlToValidate="TextBox1" Text="*"></asp:RequiredFieldValidator>

By constructing the page's validation server controls, as shown here, using different values for the ErrorMessage and Text properties, you get a result similar to that shown in Figure 11.

Figure 11: Using different text for the validation error messages

When both the ErrorMessage and Text properties are used for the validation controls, the value of the ErrorMessage property is displayed in the ValidationSummary server control's listing of validation errors, and the value assigned to the Text property is displayed in the validation control itself.

Validation ExpressionsField Expression Format

SamplesDescription

57 | P a g e

Page 58: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

Name ^[a-zA-Z''-'\s]{1,40}$ John DoeO'Dell

Validates a name. Allows up to 40 uppercase and lowercase characters and a few special characters that are common to some names. You can modify this list.

Social Security Number

^\d{3}-\d{2}-\d{4}$ 111-11-1111 Validates the format, type, and length of the supplied input field. The input must consist of 3 numeric characters followed by a dash, then 2 numeric characters followed by a dash, and then 4 numeric characters.

Phone Number

^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$

(425) 555-0123425-555-0123425 555 01231-425-555-0123

Validates a U.S. phone number. It must consist of 3 numeric characters, optionally enclosed in parentheses, followed by a set of 3 numeric characters and then a set of 4 numeric characters.

E-mail ^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$

[email protected]

Validates an e-mail address.

<asp:RegularExpressionValidator ID="RegularExpressionValidator2"runat="server" ErrorMessage="Please Enter Valid Email ID"ValidationGroup="vgSubmit" ControlToValidate="txtEmail"CssClass="requiredFieldValidateStyle" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> </asp:RegularExpressionValidator>

URL ^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0- http:// Validates a URL

58 | P a g e

Page 59: ASP.NET - enosislearning.comenosislearning.com/Tutorials/Net/1.0 Enosis_ASP.net...  · Web viewThe life cycle of an ASP.NET application starts with a request sent by a browser to

9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$

www.microsoft.com

ZIP Code

^(\d{5}-\d{4}|\d{5}|\d{9})$|^([a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d)$

12345 Validates a U.S. ZIP Code. The code must consist of 5 or 9 numeric characters.

Password

(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$

Validates a strong password. It must be between 8 and 10 characters, contain at least one digit and one alphabetic character, and must not contain special characters.

Non- negative integer

^\d+$ 0986

Validates that the field contains an integer greater than zero.

Currency (non- negative)

^\d+(\.\d\d)?$ 1.00 Validates a positive currency amount. If there is a decimal point, it requires 2 numeric characters after the decimal point. For example, 3.00 is valid but 3.1 is not.

Currency (positive or negative)

^(-)?\d+(\.\d\d)?$ 1.20 Validates for a positive or negative currency amount. If there is a decimal point, it requires 2 numeric characters after the decimal point.

59 | P a g e