Chapter 1 Introducing ASP.NET

Web applications have revolutionized the way business is conducted. These applications enable organizations to share and access information from anywhere and at anytime. This has majorly moved the focus of application development from desktop applications to Web applications. One of the most popular server-side technologies used today for developing Web applications is ASP.NET.

This chapter introduces the basics of Web development. It also discusses the architecture, functioning, and features of ASP.NET. In addition, it explains how to develop ASP.NET applications. Objectives

In this chapter, you will learn to:

Identify the basics of Web development

Explore ASP.NET

Develop ASP.NET applications Introducing Web Development

Among all technologies, the Internet has been the fastest growing technology. Ever since its inception, the Internet has evolved exponentially. In the recent years, it has changed the way business is conducted.

Prior to the evolution of the Internet, organizations were unable to create awareness about themselves because the communication media were limited. Moreover, the organizations could deliver only limited information by using the existing communication media such as television and radio. However, with the inception of the Internet, organizations found a new medium through which they could reach a larger range of people irrespective of their geographical locations. Therefore, organizations increasingly became dependent on the Internet for sharing and accessing information. This resulted in changing the focus of application development from desktop applications to Web applications.

Web applications are programs that are executed on a Web server and accessed from a Web browser. These applications enable organizations to share and access information on the Internet and corporate intranets. This information can be accessed from anywhere and at any time. In addition, Web applications can support online commercial transactions popularly known as e-commerce. An online store accessed through a Web browser is an example of a Web application.

A Web application consists of Web pages. Web pages can be of the following types:  Static Web Page: A Web page that consists of only Hyper Text Markup Language (HTML) is a static Web page. A static Web page does not respond dynamically to the actions performed by a user.  Dynamic Web Page: A Web page that responds dynamically to the actions performed by a user is a dynamic Web page and an application that consists of dynamic Web pages is a dynamic Web application. Such an application can be created by using server-side scripts, client-side scripts, or both in addition to HTML pages. Server-Side Scripting

With the increase in the usage of the Internet as the information medium, organizations are creating dynamic Web applications. Dynamic Web applications enable a user to:

 Retrieve data from a database that may not reside on the computer where the Web server is located.  Submit data from HTML forms.  Get information based on the input.

To incorporate these features in a Web application, you need to implement server-side scripting. Server-side scripting provides users with dynamic content that is based on the information stored at a remote location, such as a back-end database. Server-side scripting includes code written in server-side scripting languages, such as Active Server Pages (ASP) and Java Server Pages (JSP). A server-side script is executed on the Web server.

When a browser requests for information on a website that is created by using server-side technology, the Web server to which the request is sent, first processes the script and then sends the results back to the browser. For example, if a Web page includes a server-side script to display the current time of the system on which the website is hosted, the script will be processed at the server and the current system time will be sent back to the browser.

The following figure shows the working of server-side scripts.

Working of Server-Side Scripts Client-Side Scripting

Client-side scripting enables you to develop Web pages that can dynamically respond to user input without having to interact with a Web server. Suppose, you have a Web application that requires users to enter the user name and password before displaying the home page. You need to ensure that a user does not leave the user name and password fields blank. To check whether a user has left the user name and password fields blank, you can write client-side scripts.

In addition to providing dynamic content, a client-side script helps reduce network traffic because it does not need to interact with a Web server to provide dynamic response to the user input. Client-side scripting also speeds up the response time of a Web application. This happens because a Web server is not overloaded with the job of processing the client-side script for every client. Scripting languages, such as VBScript and JavaScript, are used to write client-side scripts.

The following figure shows the working of client-side scripts.

Working of Client-Side Scripts

Limitations of Client-Side Scripting

In spite of the all the advantages, client-side scripting has some major limitations. These limitations are:

 Browser support: Client-side scripting is not supported equally by all browsers and operating systems.  Isolation: Client-side scripts cannot access server-side resources. It is difficult and requires a lot of coding to access a file or interact with a database on the server by using client-side scripts.  Security: Client-side scripts are visible to the end users. Therefore, they can be tampered by malicious users.  Thin clients: Web-enabled devices such as mobile phones, palmtop computers, and Personal Digital Assistants (PDAs) can communicate with Web servers. These devices act as thin clients that can use Web applications containing server-side scripting. However, these devices do not support client-side scripting such as JavaScript or VBScript.

Note

In spite of all the limitations, client-side scripting is still in use. ASP.NET allows you to use client-side scripting in addition to the server-side scripting to create rich and responsive Web applications. Exploring ASP.NET

ASP.NET is a server-side technology that enables programmers to create dynamic Web applications. It has a number of advanced features such as simplicity, security, and scalability that help you develop robust Web applications. These advanced features of ASP.NET are based on the .NET Framework. ASP.NET in the .NET Framework

ASP.NET is built on the Microsoft .NET Framework. Microsoft introduced the .NET Framework to help developers create globally distributed software with Internet functionality and interoperability.

The following figure displays the elements of an ASP.NET application and how the elements fit in the broader context of the .NET Framework.

Elements of an ASP.NET Application in the .NET Framework

The preceding figure indicates that an ASP.NET application has the following elements:

 Web Form Pages: Enable you to include user interfaces, such as Text box control, List box control, and the application logic of Web applications.  Configuration Files: Enable you to store the configuration settings of an ASP.NET application.  XML Web Service Files: Define a Web service that can be called by an ASPX file over the Internet or from a local network.

Web forms and the state management feature of ASP.NET constitute the ASP.NET Page Framework. There are also a number of runtime services available in ASP.NET. The ASP.NET runtime services include view state, session state, and application state management, Web security, and the caching mechanism of ASP.NET applications. The runtime services of ASP.NET interact with .NET Framework base classes, which in turn, interact with the Common Language Runtime (CLR) to provide a robust Web-based development environment. Working of an ASP.NET Application

After creating an ASP.NET application, the ASP.NET files need to be stored on a Web server such as Internet Information Services (IIS) server, which is the Web server for the Windows platform. The Web server processes the ASP.NET files and then executes the scripts. Finally, the results are sent to the Web browser that requested the ASP.NET file.

The following figure depicts how a Web server processes a request for an ASP.NET file.

Processing of a Request for an ASP.NET File

The steps involved in the execution of an ASP.NET file are:

1. A Web browser sends a request for an ASP.NET file to a Web server by using a Uniform Resource Locator (URL). 2. The Web server, such as IIS, receives the request and retrieves the appropriate ASP.NET file from the disk or memory. 3. The Web server forwards the ASP.NET file to the ASP.NET script engine for processing. 4. The ASP.NET script engine reads the file and executes any server-side script it encounters. 5. The processed ASP.NET file is generated as an HTML page. 6. The Web server then sends the HTML page to the client. 7. The Web browser interprets the output and displays it.

A Web server generates and sends only the HTML output to the client. As a result, it helps to hide the code of the ASP.NET file from the users who access an ASP.NET Web page.

Note

ASP.NET script engine is the engine that processes the server-side scripts contained in an ASP.NET application. After processing the scripts, the engine renders the result as an HTML document and sends it back to the browser. Features of ASP.NET

In addition to hiding the code of the ASP.NET file from the users, ASP.NET has the following advanced features that help develop robust Web applications:

 Compiled code: The code written in ASP.NET is compiled and not interpreted. This makes ASP.NET applications faster to execute than other server-side scripts, such as the scripts written in a previous version of ASP that are interpreted.  Power and flexibility: ASP.NET applications are based on CLR. As a result, the power and flexibility of the .NET platform is available to ASP.NET applications. ASP.NET applications enable you to ensure that the .NET Framework class , messaging, and data access solutions are seamlessly accessible on the Web. ASP.NET is also language-independent. As a result, you can choose any .NET language to develop your application.  Simplicity: ASP.NET enables you to build user interfaces that separate application logic from the presentation content. In addition, CLR simplifies application development by using managed code services, such as automatic reference counting and garbage collection. Therefore, ASP.NET makes it easy to perform common tasks ranging from form submission and client authentication to website configuration and deployment.  Manageability: ASP.NET enables you to manage Web applications by storing the configuration information in an Extensible Markup Language (XML) file. You can open the XML file and modify it.  Scalability: ASP.NET has been designed with scalability in mind. It has features that help improve performance in a multiprocessor environment.  Security: ASP.NET provides a number of options for implementing security and restricting user access to a Web application. All these options are configured within the configuration file.  Extensibility: ASP.NET provides a number of options to create an extensible Web application. For example, you can create custom controls and extend the default Hypertext Transfer Protocol (HTTP) pipeline. The path through which the data flows from the client to the server is called the HTTP pipeline. It is a technique in which multiple HTTP requests are written out to a single socket without waiting for the corresponding responses. It improves the page loading time. Developing ASP.NET Applications

You can create ASP.NET applications by using any text editor. However, this will take a substantial amount of time because you will have to create the applications by creating all the Web page classes and coding the Web page controls manually. In addition to being time- consuming, this process increases the possibility of inducing errors that could otherwise be avoided by using a design tool. A design and productivity tool, such as Visual Studio, provides various features that enable the developers to quickly create robust ASP.NET applications. Some of the Visual Studio IDE features are:

 Integrated error checking: Visual Studio can detect various problems such as data type conversion errors, missing namespaces or classes, and undefined variables. When you type code, Visual Studio detects and underlines these problems.  The Web form designer: Visual Studio provides the Web form designer that enables you to create a Web page by simply dragging the ASP.NET controls to the appropriate location and configuring their properties. The actual Web page markup is created automatically.  An integrated Web server: Web applications need to be hosted on a Web server such as IIS to be accessible for the users. Therefore, you need to install IIS on the development computer to test the applications. However, if you are creating a Web application by using Visual Studio, you need not install IIS on the computer. This is because Visual Studio has an integrated development Web server that enables you to run a Web application directly from the design environment.  Developer productivity enhancements: Visual Studio provides features such as automatic statement completion and color-coded syntax that makes coding quick and efficient. In addition, Visual Studio has an integrated debugger that allows you to watch code execution, pause your program at any point, and inspect the contents of any variable. This helps in debugging the code quickly and efficiently.  Complete extensibility: Visual Studio allows you to use macros, change project templates, and even add your own custom add-ins. This provides you to extend the existing functionality of the existing environment. Creating an ASP.NET Web Application

You can use ASP.NET to create websites and Web services. A website is the user interface of your application. Generally, a website represents a web application front-end, with screens, Cascading Style sheets (CSS), and User Interface (UI) components. A Web service enables you to remotely access certain functions at the server side. It enables the exchange of data in a client-to-server or a server-to-server environment over the Web by using the Simple Object Access Protocol (SOAP). A Web service does not have a user interface.

Anatomy of an ASP.NET Application

ASP.NET applications are generally divided into multiple Web pages. Every Web page in an ASP.NET application shares a common set of resources and configuration settings. These resources and configuration settings cannot be shared by the Web pages from any other ASP.NET application, even if they are on the same Web server.

Every ASP.NET application is executed inside a separate application domain. These application domains ensure that even if a Web application causes a fatal error, it does not affect other applications that are currently running on the same computer. Application domains also restrict a Web page in one application from accessing the in-memory information of another application. Each Web application is a separate entity that has its own set of data. It can be described as a combination of files, pages, handlers, modules, and executable code that can be invoked from a virtual directory on a Web server.

The following figure shows a Web server that is hosting four Web applications.

A Web Server Hosting Four Web Applications

Note

A virtual directory is a directory that is exposed to the public on a Web server. Directories Used in ASP.NET Web Applications

An ASP.NET application uses some specialized directories. The following table lists these directories with their descriptions.

Directory Description Bin Stores all the compiled .NET components (DLLs) that an ASP.NET Web application uses. For example, if you create a custom component, you need to place the component in this directory. Once placed in the Bin directory, the component can be used by any ASP.NET application. App_Code Stores source code files that are dynamically compiled to be used in the Web application. It is similar to the Bin directory except for one difference. It contains source code files whereas the Bin directory contains compiled assemblies. App_Browsers Stores browser definition files. Browser definition files are XML files that define a browser with its properties, capabilities, and features. This information is used by ASP.NET server controls to determine the browser that has requested the page and render the appropriate markup for that browser. App_GlobalResources Stores global resources that are accessible to every page in the Web application. It is used for localization purposes where you want a website to display content in more than one language. App_LocalResources Stores .resx files that are accessible to a specific page only. App_WebReferences Stores references to Web services that are used by the Web application. App_Data Stores data such as database files and XML files that are used by the application. It is not mandatory to store data files in this directory. App_Themes Stores the themes that are used in the Web application.

Directories Used in an ASP.NET Application Some of the subdirectories given in the preceding table are created in specific applications. For example, the App_Themes directory is created when you use themes in your application.

Files Used in ASP.NET Web Applications

The ASP.NET Web applications can include different types of files. The following table lists some of the important file types with their descriptions.

File Name Description Ends with .aspx These are ASP.NET Web pages that contain the user interface and, optionally, the underlying application code. Users request or navigate directly to one of these pages to start a Web application. Ends with .ascx These are ASP.NET user controls. These controls are similar to Web pages, except that the user cannot access these files directly. Instead, they must be hosted inside an ASP.NET Web page. User controls allow you to develop a small piece of user interface and reuse it in as many Web forms as you want without repeating code. Ends with .asmx These are ASP.NET Web services. Web services are collections of methods that can be called over the Internet. Web services work differently than Web pages. However, they still share the same application resources, configuration settings, and memory. web.config This is the XML-based configuration file for ASP.NET applications. It includes settings for customizing features such as security, state management, and memory management. Global.asax This is the global application file. You can use this file to define global variables (variables that can be accessed from any Web page in the Web application). It is mostly used for defining the overall application events related to the Application & Session object. Ends with .cs These are code-behind files that contain C# code. These files allow you to separate the application logic from the user interface of a Web page. Ends with .ashx These are default HTTP handlers for all Web handlers that do not have a user interface and that include the @ WebHandler directive.

Files Used in an ASP.NET Application

Configuration Files Used in ASP.NET Web Applications

ASP.NET uses a hierarchy of configuration files to keep application configuration settings separate from the application code. A configuration file is an XML file that contains configuration settings for an application and has a .config extension.

It provides the following benefits:

 Provides control and flexibility over the way you run applications.  Eliminates the need to recompile the application every time a setting changes.  Controls access to protected resources, and the location of remote applications and objects by defining configuration settings.

To understand the benefits of configuration files, consider an example. Suppose, your Web application includes a number of forms that are required to connect to an SQL Server database. You have written the code to create the connection on each of these forms. However, if the location of the database is modified, you will have to update the code for connecting to the database in each form. A better option is to store the details of the connection string in a configuration file for the Web application and refer to the connection string from within the code. As a result of this, even if the database location is changed, only the connection string in the configuration file needs to be updated.

ASP.NET allows you to easily edit the configuration data before, or after an application is deployed on the server. The files in the configuration hierarchy allow you to make configuration settings at different levels.

The following table lists the levels, the corresponding configuration files, and their description.

Configuration Files with Their Levels and Descriptions

The two files included in the hierarchy of configuration files are machine.config and web.config. The machine.config file always resides at the root of the configuration hierarchy and contains the global and default settings for all .NET Framework applications on the server. The web.config file can reside at multiple levels in the hierarchy. In case two versions of the same configuration setting exist at different hierarchal levels, local settings will take precedence over global settings. ASP.NET Web Page Code Model

A Web page is made up of the following two components:

 The visual portion: Refers to the static HTML and ASP.NET server controls that define the layout of a Web page.  The programming logic: Refers to the code that is required to interact with the Web page.

ASP.NET provides two models for managing the visual elements and code:

 Single-file page model  Code-behind page model The Single-File Page Model

In the single-file page model, HTML markup of the page and its programming code are in the same physical .aspx file. The programming code is contained in a

CatchException.aspx

ID="dgrdProducts"

Runat="Server" />

In the preceding example, if an error occurs within the try block, statements in the catch block are executed and detailed information about the error is displayed. The Exception object used in the catch block represents a generic exception. The catch block can also be used to capture particular exceptions such as InvalidArgumentException or IndexOutOfRangeException. This is required if specific information on the cause of error is needed.

You can include the finally block in a try-catch block for cleaning up the resources. The finally block always executes, irrespective of whether or not an exception has occurred. For example, you can use the finally block to close a database connection, as shown in the following code snippet: try

{

DgrdProducts.DataSource=mycommand.ExecuteReader();

DgrdProducts.DataBind();

} catch(Exception objException)

{

Response.Write("Could Not Execute Statement");

} finally

{

// closing the connection to the database mycon.Close();

}

In the preceding code snippet, the finally block closes the database connection even if no exception is caught. Using the Page_Error Subroutine

It is not always possible to anticipate and handle all the errors that may occur on a page. Many unexpected errors can occur while the application is running in a real-world environment. To handle such errors, you should include the Page_Error subroutine in the .cs file for the page. This subroutine executes in case an unhandled exception occurs on a page. For example, you can use the Page_Error subroutine to display an error message, as shown in the following code snippet: void Page_Error (Object sender , EventArgs e) {

Response.Write( "Sorry, an error was encountered:" );

Response.Write( "

" );

Response.Write( Server.GetLastError().Message);

Server.ClearError();

}

In the preceding code snippet, the GetLastError() method of the Server object returns the previous exception that had occurred in the page. The ClearError() method is used to clear the error message. Clearing an error means that it has been handled. Once you have cleared the error, it is not passed to any higher level error handler such as the Application_Error event.

Application-Level Error Handling

Application-level error handling enables you to handle errors on ASP.NET pages, irrespective of where the errors occur in the application. If an error is not handled at the page level, it is passed to the application-level error handler.

Some errors, such as leaving a required field blank, are common on Web pages. Instead of writing error handler code for the common errors on every Web page, you can use the application-level error handling code to handle these errors.

You can implement application-level error handling either by using the element in the web.config file or by using the Application_Error subroutine in the global.asax file.

Using the Element

When a user accesses an ASP.NET Web application from a Web browser and an error occurs, the default error message is displayed to the user. However, it is not a good programming practice to display the default error message to the user. You can use the element of the web.config file to control the details of the error information made available to the users of ASP.NET applications. By using the element, you can either completely hide the error information from the users or display customized error messages. You can also redirect users to an appropriate error page in case an unhandled error occurs.

Note

The element will work when you start the application without debugging support.

Consider the following example in the web.config file:

In the preceding example, the following two attributes of the element have been set:

 mode: Specifies the mode for handling custom errors. The mode attribute can be set to any of the following values: o Off: Disables the display of custom error messages. The default error message is displayed for both local and remote users in case of an error. o On: Enables the display of custom error messages. The user-defined custom error messages are displayed instead of the default error message for both local and remote users. o RemoteOnly: Enables the display of custom error messages for remote users only. The local users are shown the default error message only. RemoteOnly is the default value of the mode attribute.

Note

Local users are the developers who are working on the same computer on which the Web application is deployed. Remote users are those users who are accessing the Web application from a computer other than the one on which the website is deployed.  defaultRedirect: Specifies the URL of the customized error page that should be displayed in case of an error. In the preceding example, the defaultRedirect attribute is set to the Web form, Error.aspx, specifying that in the case of an unhandled run-time error, the browser should be redirected to the Web form, Error.aspx.

The preceding example displays a single error page for all types of errors. However, it is possible to display different error pages for different types of errors by including elements within the customErrors section. Consider the following example:

In the preceding example, if an error with the status code 404 occurs, the user will be redirected to the error page, PageNotFound.aspx. If an error with the status code 408 occurs, the user will be redirected to the error page, SessionTimedOut.aspx. However, if an error with any other status code occurs, the user will be redirected to the default error page, Error.aspx.

Using the Application_Error Subroutine

Application-level errors can also be handled in the event handler for the Application.Error event that occurs whenever an unhandled error occurs in an application. The event handler for this event is written in the Global.asax file. You can use this event handler to capture the errors for logging or notification.

This event handler is similar to the Page_Error event handler. The only difference is that it operates at the application level.

Consider the following code snippet: protected void Application_Error(Object sender, EventArgs e)

{

Response.Redirect("ErrorPage.aspx");

} In the preceding code snippet, the Application_Error event handler redirects the user to the ErrorPage.aspx page in case an error occurs anywhere in the Web application. Logging Errors

It is possible that certain unexpected errors occur in a Web application while it is running in a real-world environment. It would be easy to resolve such errors if a log of these errors is maintained. ASP.NET enables you to log unhandled errors in an event log, database, or some other file. These event logs, databases, or files can be used by the administrator to learn about the errors that are occurring in a Web application. You can log information about all the errors whether they occur at the page-level or at the application-level.

To log errors occurring in an application, you need to create a log for the application in the event log. Whenever an unhandled error occurs in a Web application, the Application_Error event handler, written in the Global.asax file, is executed. Therefore, the event logging code can be written in the Application_Error event handler.

A log can be created by using the EventLog class of the .NET Framework. For using this class, you need to import the System.Diagnostics namespace.

The following table describes the various properties of the EventLog class.

Property Description

Entries Retrieves the contents from an event log.

Log Specifies the name of the log from where the log information is to be read or written.

Source Specifies the name by which the application needs to be registered in the event log. The name specified as the Source property should be unique in an event log. A single event log can contain content from multiple sources.

Properties of the EventLog Class

The following table describes the various methods of the EventLog class.

Method Description

Exists Determines whether the log to which the information is to be written or read exists on the specified computer. If the computer is not specified, the existence of the log is checked on the local computer.

SourceExists Determines whether a particular source name already exists on the specified computer. If the computer is not specified, the existence of the event source is checked on the local computer.

CreateEventSource Establishes an application as a valid event source for adding information to a log.

WriteEntry Writes information to an event log.

Methods of the EventLog Class

Debugging Web Applications

Debugging is the process of finding and fixing errors in an application. An application may contain syntax errors, logical errors, and run-time errors. The syntax errors are resolved during the compilation of the Web application. However, logical errors and run-time errors cannot be identified during compilation. Such errors require you to debug the code while it is running.

There are various tools available that help you debug your Web application. One such tool is Visual Debugger. It is available in Visual Studio IDE. These tools enable you to step line-by- line through the statements in an application to ensure that the execution path and the data are correct. Before using these tools, you need to configure your Web application for debugging. Configuring Web Applications for Debugging

To enable debugging in an ASP.NET Web application, you must configure the application to compile into a debug build. A debug build includes the information that the debugger needs to debug the code. You can configure a Web application to compile into a debug build by setting the debug attribute in the element of the web.config file to true, as shown in the following markup:

However, if you want to debug only a single page in your Web application, you can add the debug attribute and set its value to true in the @ Page directive of the page that you wish to debug, as shown in the following markup:

<%@ Page debug="true" %>

Application execution becomes slow when debugging is turned on. For this reason, debugging has to be turned off before the deployment of the Web application. To disable the debug mode, set the debug attribute to false in the element of the web.config file, as shown in the following markup:

Features of Debugging

Debugging allows you to run your code line by line to monitor the program execution. You can check the state of the application objects such as variables and database table values to ensure that the application is running properly. A debugger includes the following features that help you debug Web applications:

 Breakpoints: Breakpoints are places in the code where the debugger stops the execution of the Web application. This allows you to view the current state of data in your Web application. You can step through each line of code when executing the Web application.  Stepping: Once the execution of the Web application has been stopped at a breakpoint, you can execute the code line by line, which is known as stepping through the code.  Data Viewing: This feature allows you to view and track data while the Web application is running. It also allows you to modify data while the execution of the Web application is stopped at a breakpoint. You can then continue to run the application with the modified data.

Debugging enables you to observe and change values of variables and objects in your application code. You can get a close look at what your code does by using the debugger.

Summary

In this chapter, you learned that:

 The errors can be handled at the following two levels: o Page Level o Application Level  The page-level error can be handled either by using the try-catch block or by using the Page_Error subroutine.  Application-level error handling enables you to handle errors on ASP.NET pages, irrespective of where they occur in the application.  The application-level error can be handled either by using the element in the web.config file or by using the Application_Error subroutine in the Global.asax file.  ASP.NET enables you to log unhandled errors in an event log, database, or some other file.  An event log can be created by using the EventLog class of the .NET Framework.  Debugging is the process of finding and fixing errors in an application.  There are various tools available that help you debug your Web application. One such tool is Visual Debugger, available in Visual Studio IDE.  The features of a debugger that help you debug Web applications are: o Breakpoints o Stepping o Data Viewing  The aspnet_wp.exe process is attached to the debugger to debug a running page.

Reference Reading

Handling and Logging Errors

Reference Reading: Books Reference Reading: URLs

Beginning ASP.NET 3.5 http://wiki.asp.net/page.aspx/383/custom-error-logging/ in VB 9.0: From Novice to Professional by Matthew MacDonald

Debugging Web Applications eference Reference Reading: URLs Reading: Books

Beginning http://www.informit.com/articles/article.aspx?p=29419 ASP.NET 3.5 in VB 9.0: From Novice to Professional by Matthew MacDonald

Chapter 9 Enhancing Web Applications by Using Web Parts

Being a Web developer, you need to develop websites that appeal users. Users today want to do much more than just viewing the content on the website. They want to personalize Web pages according to their interest and preferences. You can implement personalization on your websites by implementing Web parts. Users can use these Web parts to personalize Web pages.

In addition to using Web parts, you can enhance a Web application by including commonly- used features such as information about astrology, latest news updates, cricket scores, temperature of the day, or weather forecast. These features are common and are provided on the Internet through Web services. You can easily include these features on your website by consuming existing Web services.

This chapter discusses Web parts and their implementation. In addition, it discusses how to consume Web services for providing various features in a Web application. Objectives

In this chapter, you will learn to:

Implement Web parts in a Web application

Consume Web services in a Web application Implementing Web Parts in a Web Application

Today, a website may contain a wide variety of information regarding various domains, such as entertainment, astrology, business, sports, and technology. However, users may be interested in viewing only the information of their interest. Therefore, websites such as MSN.com organize their data into discrete units. Each unit represents a standalone part of the website and contains information about a specific domain. These units support a degree of personalization. Users can rearrange or hide these units to suit their individual working styles. These units can be developed by using ASP.NET and are known as Web parts.

A Web part is a modular unit that can contain any type of Web-based information. This information could be a picture, static text, or database information. A Web part enables a user to create a personalized user interface and enables you to present information in a better way. It also enables you make your websites interactive. Advantages of Using Web Parts

Web parts allow the information displayed on a website to be broken down into manageable parts. Users can rearrange, move, or close the Web parts to suit their preferences. Users can also save their preferences for future browser sessions.

The advantages of using Web parts on a website are:

 Web parts enable users to personalize the content of a Web page. Users can move or hide Web parts to customize the Web page. They can even add new Web parts to change the layout of the page.  Web parts can be assigned role-based access, thereby, determining which Web part can be shared by all users or which should be hidden for certain roles. This helps in providing customized content based on security.  Web parts can be connected to each other. One of the connected Web parts is defined as a provider and the other as a consumer. Consider the example of a Web parts page that contains two Web parts, one displays a chart and another displays the stock market data. These Web parts can be connected in such a way that the chart Web part displays the chart for the stock market data present in the other Web part. In this example, the Web part providing the stock market data is the provider and the Web part displaying the chart is the consumer. Web Part Modes

Personalization is one of the main advantages of using Web parts. You can implement personalization by allowing a user to view a Web page in several display modes.

Display modes allow users to modify or personalize the Web page. Users can edit the Web part controls, change the layout of the Web page, and add new Web part controls by using different types of display modes. The different types of display modes available are:  Browse: This is the default mode. This mode allows users to view Web parts on the Web page. It also allows users to minimize or close the Web part. If you close a Web part, it cannot be restored from the Browse mode. However, you can restore it in another mode called the Catalog mode. The following figure shows a Web part in the Browse mode.

A Web Part in the Browse Mode

 Edit: This mode allows users to edit Web parts on the Web page at runtime. Users can set the title, color, or custom properties of the Web parts.  Design: This mode allows users to rearrange the order of Web parts on the Web page by dragging and dropping them.  Catalog: This mode allows users to add new Web parts on the Web page. It also allows users to rearrange or delete the existing Web parts from the Web page.  Connect: This mode allows users to connect two Web part controls on a Web page.

Note

A Web page can be displayed in only one display mode at a time. Web Parts Control Set

ASP.NET provides you with the Web parts control set that are designed to implement Web parts on your websites. A Web parts control set consists of a group of Web parts that work together to enable users to create Web parts pages. A Web page that is composed of Web parts is known as a Web parts page. A Web parts page is divided into zones that provide the structure for placing Web parts. You can place Web parts in any of these zones according to your requirements.

The following table describes some of the Web part controls available in ASP.NET.

Control Description WebPartManager Manages all the Web part controls on a page. Each Web parts page contains exactly one WebPartManager control. CatalogZone Contains CatalogPart controls and is used to create a catalog of Web part controls from which a user can select a Web part control to add to a page. EditorZone Contains EditorPart controls and is used to enable a user to edit and personalize Web part controls on a page. WebPartZone Contains the overall layout for the Web Part controls that compose the main user interface of a page. ConnectionsZone Contains Connection controls. CatalogPart Contains a list of available Web part controls that a user can add to a page. Connection Creates a connection between two Web part controls on a page. EditorPart Serves as the base class for specialized controls that provide the functionality to edit Web parts.

Some of the Web Part Controls Available in ASP.NET

To implement Web parts on your website, you first need to add a WebPartManager control and one or more WebPartZone controls to the Web page. The WebPartManager control is used to manage all the Web part controls on the Web page. The WebPartZone control serves as a container for the Web part controls. After adding these controls, you need to add the controls on your Web pages. These controls can be the existing Web server controls or Web user controls.

Once you have created a Web parts page, you can allow users to change the appearance of the user interface elements on the Web page. This can be done by changing the display mode of the Web parts page.

To enable a user to switch between the various modes, you can include a drop-down list on the Web page that allows a user to select the desired mode. After including the drop-down list on the Web page, you can type the following code snippet in the SelectedIndexChanged event of the DropDownList control:

WebPartManager wpm =

WebPartManager.GetCurrentWebPartManager(Page); string selectedMode = DropDownList1.SelectedValue;

WebPartDisplayMode mode = wpm.SupportedDisplayModes[selectedMode]; if (mode != null) {

wpm.DisplayMode = mode;

}

The preceding code snippet, enables a user to change the mode of the Web parts present on the Web page by selecting the edit mode from the DropDownList control.

Connecting Web Parts

There are situations where you need to connect sets of data from different data sources. For example, a Web parts page contains two Web parts, one that contains details of senior managers of a department and the other that displays their photographs, one at a time. You can connect these Web parts in such a way that when you select the name of a manager in the first Web part, the other Web part displays the photograph of the selected manager.

In the preceding example, the Web part containing the details of senior managers is the provider and the Web part that displays the photograph of the selected senior manager is the consumer.

Web part connections are based on a pull model, where the consumer pulls data from the provider. To create a connection, the provider control defines a communication contract in the form of an interface, indicating the data it can provide. The consumer control knows about this contract and retrieves the data through the connection. The interface can contain properties, events, or methods that the consumer control can use once the connection is established.

To participate in a connection, a Web part needs to define a connection point. A connection point contains the details necessary for a server control to connect to another control. These details include information such as the type of the control itself, the type of data the control recognizes, an ID for the connection point object, and whether the control can form multiple connections. Connection points are of two types, provider connection points and consumer connection points.

To create connected Web parts, you need to perform the following tasks:

1. Create the provider Web part as a custom control that derives from the WebPart class and implements an interface that defines the communication contract. The provider Web part defines a connection point in the form of a method to which the ConnectionProvider attribute has been applied. 2. Create the consumer Web part as a custom control that derives from the WebPart class and defines a connection point in the form of a method to which the ConnectionConsumer attribute has been applied. 3. Add the Web parts to the Toolbox. 4. Add the Web part controls from the Toolbox to a Web parts page and assign an ID and title to each of the two controls. 5. Add the connection information to the WebPartManager control by opening the Web parts page in the Source view and adding a element inside the element, as shown in the following example:

ProviderConnectionPointID="Color" ConsumerID="Consumer1"

ConsumerConnectionPointID="Color" />

Consuming Web Services in a Web Application

There are certain things that most websites require. For example, almost all websites provide the searching functionality on their home pages. One way to provide this functionality on your website is to write your own code. The other way is to use an existing code, and this can be done by using Web services.

Web services are the application components that can be used by other Web applications. You can create a Web service and publish it on a Web server, thereby, making it available for other Web applications to use. Invoking Web Services

A Web service is a self-describing Web component that exposes its functionality to the consumers through open standards such as XML and Simple Object Access Protocol (SOAP). It is a widely used method for implementing Service-Oriented Architecture (SOA).

Note

SOA is software architecture, which is essentially a collection of services communicating with each other. It was developed for enabling the development of loosely-coupled distributed applications.

Note

Coupling refers to the interrelatedness and interdependency between two or more components of a Web application. In loosely-coupled distributed applications, it is possible to change one component without affecting other components.

Web services allow integration of applications developed in different languages and running on different platforms. This integration and interoperability in Web services is made possible with the use of XML. Web services communicate by using a standard protocol called SOAP. SOAP defines a standard way of passing the XML-encoded data.

Developing ASP.NET Web services starts by creating an .asmx file and hosting it on a Web server, such as IIS. Once hosted or published on the server, a Web service can be consumed by any client. The client can be a Web application, desktop application, console application, or another Web service based on .NET or other platforms such as Java.

The client, who has to consume a Web service, locates the service by adding a Web reference. This adds a proxy class on the client side, which exposes the methods, parameters, and return types of the methods contained in the Web service. After adding the proxy class, the client application creates an instance of the proxy class and accesses the methods provided by the Web service through the instance.

The client requests are then handled by the proxy class. It transforms the method calls of the client into the SOAP message format, which can be transmitted over HTTP to the server. After processing the request, the response is also sent as a SOAP message to the proxy. The proxy then converts this SOAP message into method return value, which is returned to the client.

Invoking WCF Services

In distributed computing, Web services along with various other technologies, such as COM+, .NET Remoting, Message Queues, and Web Service Enhancement (WSE) were used to provide a wide range of functionality. Every technology is a discreet set of services fulfilling a specific requirement of a distributed development. This restricts the developers to make a choice of one of these technologies.

If a developer decides to use more than one technology, a lot of code needs to be written and unification becomes tedious. In addition, developers need to learn different technologies to cater to the different needs of distributed application development. For example, to provide security to the Web services, WSE support needs to be separately added with the Web service. Similarly, if there is a requirement to host a Web service on TCP and HTTP, separate coding needs to be defined for both.

To overcome the complexity in the integration of applications developed by using different technologies, Windows Communication Foundation (WCF) was introduced. WCF unifies features of such discreet technologies under one single framework. It provides a unified programming model used to build a secure, reliable, and robust Web service.

WCF aims at providing encoding, hosting, messaging patterns, networking, security, and interoperability in a single infrastructure. This helps in simplifying the development of distributed applications.

The following figure shows the WCF architecture.

The WCF Architecture

The following set of is unified in the WCF architecture:

 ASP.NET Web Services (ASMX): It provides support and interoperability with Web services running on non-Windows platforms.  WSE: It provides end-to-end standards-based security for Web services.  System.Messaging: It is a namespace in the .NET Framework that provides managed APIs to Microsoft Message Queues (MSMQ), enabling developers to build asynchronous reliable distributed applications.  Enterprise Services: It provides managed APIs to COM+. COM+ provides component-based programming for functionality such as transactions.  Remoting: It exposes the Common Language Runtime (CLR) type system remotely and provides location transparency for objects. Remoting is designed for tightly coupled .NET-to-.NET application communication. It provides seamless and simple development experience for applications on the local network and the Internet.

Note

In tightly coupled applications, the components are interconnected with each other such that any change in one component will lead to changes in other components as well.

Note

A WCF Service is a program that exposes a collection of Endpoints. An Endpoint is used for communicating with other services and applications. An Endpoint has an Address, a Binding, and a Contract. An Endpoint address is the address where the service listens. The Endpoint's Binding specifies how the Endpoint communicates with other services and applications. The Endpoint's Contract specifies what the Endpoint communicates. A WCF Endpoint can be configured by using the element.

The design goals for building WCF services are:

 Unification: WCF increases productivity by bringing together various technologies such as COM+ and .NET Enterprise services, Message Queues, .NET Remoting, ASP.NET Web Services, and WSE for building distributed applications by using a unified programming model.  Interoperability: WCF increases the interoperability options with .NET-to-.NET applications by providing built-in support of .NET Remoting. It allows basic communication with other applications running on other platforms.  Service orientation: WCF provides a highly productive programming model for building distributed systems that involve developing loosely-coupled services. These services can be independently managed, updated, and deployed.

Summary

In this chapter, you learned that:  A Web part is a modular unit that can contain any type of Web-based information.  The advantages of using Web parts on a website are: o Web parts enable users to personalize the content of a Web page. o Web parts can be assigned role-based access, thereby determining which Web parts can be shared by all users or which should be hidden for certain roles. o Web parts can be connected to each other.  The different types of display modes of a Web part are: o Browse mode o Edit mode o Design mode o Catalog mode o Connect mode  A Web page that is composed of Web parts is known as a Web parts page.  A Web parts page is divided into zones that provide the structure for placing Web parts.  A Web service is a self-describing Web component that exposes its functionality to the consumers through open standards such as XML and Simple Object Access Protocol (SOAP).  Windows Communication Foundation (WCF) aims at providing encoding, hosting, messaging patterns, networking, security, and interoperability in a single infrastructure.

Reference Reading

Implementing Web Parts in a Web Application

Refer Reference Reading: URLs ence Read ing: Book s

Pro http://www.hotscripts.com/Detailed/79303.html ASP. NET http://books.google.co.in/books?q=Implementing+Web+Parts+in+a+Web+Applicat 3.5 in ions+in+ASP.NET+3.5&source=in&sa=X&oi=book_group&resnum=11&ct=title& C# cad=bottom-3results 2008 by Matt hew Mac Dona ld, Mari o Szpus zta

Consuming Web Services in a Web Application

Referenc Reference Reading: URLs e Reading: Books

Beginnin http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web- g services/ ASP.NET 3.5: In http://www.codedigest.com/Articles/ASPNET/52_ASPNET_35_AJAX_and_WebS C# and ervices__.aspx VB by Imar Spaanjaa rs

Chapter 10 Creating Rich Internet Applications Using AJAX

In a traditional Web application, when a user submits any data, it is transferred synchronously to the Web server. This means that the user cannot interact with the application till the data transfer activity is completed. Moreover, these applications always reload the complete Web page even when a single component of a Web page is to be modified. This makes the Web applications slow and less interactive. These limitations can be overcome by using Asynchronous JavaScript and XML (AJAX).

This chapter provides an overview of AJAX. It further discusses the various AJAX server controls provided by ASP.NET. In addition, it discusses the client life-cycle events and explains how to consume Web services in AJAX-enabled applications. Objectives

In this chapter, you will learn to:

Explain the AJAX framework

Identify the ASP.NET AJAX server controls

Identify the ASP.NET AJAX client life-cycle events

Consume Web services in AJAX-enabled applications Explaining the AJAX Framework

In traditional Web applications, the client and the server interact synchronously. This means that the processing of a Web application happens sequentially, one after the other. When the client requests a page for the first time, the server sends the full page containing HTML and Cascading Style Sheet (CSS) code at once. The client enters or updates the information on the page and submits it to the server. The server then processes the information, rebuilds the page with the updated information, and sends the full page back to the client. This leads to the following drawbacks:

 The user interaction with the application is interrupted every time a postback is made by the server.  The user has to wait during each postback.  The full page is rendered and transferred to the client after each postback, which is time consuming and traffic intensive.

To overcome these drawbacks, a technology called AJAX is implemented in Web applications. By implementing AJAX in Web applications, the interaction between the client and the server becomes asynchronous. This allows users to interact with the Web application while waiting for a response from the server. In addition to this, AJAX implementation enables partial updates in Web applications. This means that instead of sending the entire page, only the portion that needs to be updated is sent to the server. Understanding AJAX

AJAX is a Web development technique that is used to create dynamically interactive applications. It enables Web applications to retrieve data from the server, asynchronously in the background, without interfering with the display and behavior of the existing page. To understand the concept of AJAX, you need to understand the relevance of the following terms:

 Asynchronous communication: Asynchronous communication is the ability of an application to send multiple requests and receive responses from the server simultaneously. This enables the users to work continuously on the application without being affected by the responses received from the server.  JavaScript: JavaScript is the scripting language that is used to generate client-side scripts. JavaScript forms an integral part of the AJAX-enabled Web applications because these applications process most of the requests on the client side, unless there is a need to connect to the Web server. The client-side processing of data is handled by using JavaScript object support in AJAX. The XMLHttpRequest object is one of the primary objects used by JavaScript because it enables asynchronous communication between the client and the server.  XML: XML is the standard used for transferring data between applications. XML forms the base for manipulating the data received from the server and presenting of the data in the Web application.

To understand the behavior of a Web application that implements AJAX, you need to understand the role of AJAX in a Web application and how it helps the server to quickly respond to the client. Working of an AJAX-Enabled Web Application

When AJAX is implemented in an application, a new layer, the AJAX engine, is added to the communication model. The AJAX engine resides at the client side and consists of three components: HTML, CSS code, and some JavaScript files.

In AJAX-enabled Web applications, the page is loaded for the first time when it is requested by a user. After that whenever a user requests data from the server, the requests are sent as JavaScript calls to the AJAX engine. The AJAX engine serves as a mediator that sends only small page bits that are to be updated to the server as XML and subsequently processes server response to update the relevant page elements without reloading the entire page.

The following figure illustrates the complete life cycle of an AJAX-enabled Web page.

Life Cycle of an AJAX-Enabled Web Page Advantages and Limitations of AJAX-Enabled Web Applications

AJAX-enabled Web applications provide various advantages over the Web applications that are completely server-based. AJAX-enabled Web applications offer:

 Quick response to a user’s request. This is due to partial-page updates feature that refreshes only those parts of a Web page that have changed or updated. In addition, partial-page updates feature enables an application to use less bandwidth because only the those parts of a Web page that have changed or updated are sent to the server.  Asynchronous communication that allows a user to interact with the rest of the Web page while the application is processing the changed or updated parts of the Web page.  Auto-generated proxy classes that are used to call Web service methods from client script such as JavaScript.  Support for the widely used Web browsers such as Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari.

AJAX-enabled Web applications also have a few limitations. Some of them are:

 Browser Integration: The AJAX-enabled Web application does not register the dynamically-created Web page in the Web browser’s history engine. This restricts a user to view the previous look of the page when he or she triggers the back button of the Web browser. In addition, a user is not able to bookmark a particular state of the Web application.  Dependency on JavaScript: The AJAX-enabled Web applications are based on JavaScript. JavaScript may be interpreted differently by different Web browsers or versions of a particular Web browser.

You can create AJAX-enabled Web applications by using the .NET Framework. The .NET Framework enables you to create rich and intuitive websites by providing support for AJAX features. It provides a set of extensions to ASP.NET for implementing AJAX functionality. This set of extensions is known as ASP.NET AJAX. To create AJAX-enabled Web applications by using the .NET Framework, you need to understand the ASP.NET AJAX architecture. Architecture of ASP.NET AJAX

The ASP.NET AJAX Web applications consist of client-side and server-side scripts. Therefore, these applications use both, the client-side and the server-side functionality. The client-side and the server-side functionality are provided by the two components of the ASP.NET AJAX architecture, client-script libraries and server components. These components together provide a strong development framework for developing AJAX-enabled applications.

The following figure displays the ASP.NET AJAX architecture.

The ASP.NET AJAX Architecture

The preceding figure shows that the ASP.NET AJAX architecture consists of the following components:

 Client-based Microsoft AJAX library  Server-based AJAX features for ASP.NET

Client-Based Microsoft AJAX Library

The ASP.NET AJAX client architecture provides features that enable you to create rich, intuitive, responsive, and interactive Web applications. This architecture includes the ASP.NET AJAX library. This library includes:

 Components  Browser compatibility  Networking  Core services

Components

The client components enable a Web application to render dynamic behavior to the Web browser without requiring a postback to the Web server. There are various client components such as non-visual objects and controls. Non-visual objects, such as a timer object, encapsulate the code that needs to be repeated after a fixed interval.

Browser Compatibility

The browser compatibility feature provides compatibility for client scripts with major Web browsers, such as Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari. This feature makes your Web application browser-independent.

Networking

The ASP.NET AJAX client architecture provides the networking layer between the client and the server. This layer is used to handle the communication of scripts with the Web services and the application services. It is also used to handle asynchronous calls to the methods or services at the remote locations.

The networking layer automatically handles partial-page updates for the UpdatePanel control in your Web application. It also allows Web applications to access the server-based forms authentication, role information, and profile information in a client script. The Web applications that are not created by using ASP.NET can also use the networking layer if they have access to the Microsoft AJAX library.

Core Services

The ASP.NET AJAX client architecture provides various core services, such as JavaScript base class extensions, support for JavaScript libraries, debugging, error handling, and globalization. The JavaScript libraries are either embedded in the assemblies or provided as standalone JavaScript files with the .js extension.

The core services also include the Sys.Debug class to handle debugging in your Web application. In addition to the Sys.Debug class, the core services also include the Error object for handling errors in your Web application. The Error object provides support for the release mode and the debug mode of the Web application.

Note

In the debug mode, the debug information is generated, which is used for rectifying the errors in the code. It is used at the time of development of an application. In the release mode, the debug information is not generated. It is used at the time of deployment of an application because it is much faster than the debug mode.

Server-Based AJAX Features for ASP.NET

The ASP.NET AJAX server architecture provides the functionality for the following server- based AJAX features:

 Script support  Web services  Application services  Server controls

Script Support

AJAX features in an ASP.NET application can be implemented with the support of client scripts. These client scripts are sent from the Web server to the Web browser when the application is requested for the first time. These client scripts provide the following features:

 Partial-page rendering: Enables you to update portions of the page by using an asynchronous postback.  The Microsoft AJAX library: Provides a set of JavaScript extensions that provide namespaces, inheritance, interfaces, enumerations, and reflection.

You can also create your own custom client scripts for the AJAX-enabled Web applications. The custom client scripts can be saved as static files or can be embedded in an assembly with .js extension.

Web Services

An AJAX-enabled Web application can call ASP.NET Web services (.asmx) and WCF services (.svc) by using client scripts. An AJAX-enabled Web application can call the Web services without a postback. When a user requests for a Web page for the first time, the proxy class is automatically generated by the server and downloaded to the browser at the page-load time. This proxy class can be used to call the corresponding Web service methods.

Application Services

The application services are the predefined Web services that are based on certain features provided by ASP.NET such as forms authentication, roles, and user profiles. The ASP.NET forms authentication is performed to verify credentials, such as login id and password, of the users. The ASP.NET roles are used to group multiple users under one role, such as grouping all the heads of each department in an administrator role. The profile of a user consists of the information such as background and foreground colors of the application that is set when the user logs on to the application.

The application services can be called by various clients, such as a client script in an AJAX- enabled Web page, a WCF-compatible client, or a Windows application.

Server Controls

The ASP.NET AJAX server controls consist of server-side script as well as client-side script. This allows a Web application to provide rich client behavior. A Web page that consists of AJAX server controls sends supporting client script to a Web browser while it is rendered to a user to provide AJAX functionality on the Web page. The AJAX functionality include partial-refreshing of the Web page, asynchronous communication between the Web browser and the Web server, and faster response to the user. Identifying the ASP.NET AJAX Server Controls

ASP.NET offers various AJAX server controls that implement AJAX functionality in a Web application. Some of the controls offered by ASP.NET are:

 ScriptManager control  ScriptManagerProxy control  UpdatePanel control  UpdateProgress control  Timer control The ScriptManager Control

The ScriptManager control can be used to manage the client script for AJAX-enabled Web applications. The ScriptManager control provides:

 The custom scripts that you need to send to the Web browser to enable asynchronous communication with the Web service and partial-page refreshes.  The JavaScript classes that are used to access the ASP.NET application services for forms authentication, roles, and user profiles.  The JavaScript proxy classes that are used to call Web service methods from the client script.

The ScriptManager control can be added to a Web page by using the following markup:

The preceding markup adds a ScriptManager server control with a unique ID ScriptManager1 to the Web page. The following table describes some properties of the ScriptManager control.

Property Description

AsyncPostBackErrorMessage Sends error message to the client when an unhandled server exception occurs during an asynchronous postback.

AsyncPostBackTimeout Gets or sets a value that indicates the period of time, in seconds, before asynchronous postbacks are timed out.

EnablePageMethods Gets or sets a value that indicates whether static page methods on an ASP.NET page can be called from a client script. The default value is false.

EnablePartialRendering Gets or sets a value that enables partial rendering of a page, which in turn, enables you to update regions of the page individually by using the UpdatePanel server controls.

Properties of the ScriptManager Control The ScriptManagerProxy Control

The ScriptManager control is used to manage the client script for AJAX-enabled Web applications. The ScriptManager control provides features such as partial page updates. However, there is a limitation in using the ScriptManager control. You can add only one instance of the ScriptManager control to a Web page. A Web page can include the control either directly or indirectly inside a nested component such as a user control or a content page for a master page. This means that if a master page has a ScriptManager control, you cannot add a ScriptManager control to the content page, which is using the master page.

This limitation can be overcome by using the ScriptManagerProxy Control. This means that if a page that already contains a ScriptManager control needs another ScriptManager control for a nested or parent component, the component can include a ScriptManagerProxy control. The ScriptManagerProxy control enables you to add scripts and services that are specific to nested components.

The following table describes some properties of the ScriptManagerProxy control.

Property Description Scripts Gets a ScriptReferenceCollection object that contains a ScriptReference object for each script file that is explicitly registered with the ScriptManagerProxy control.

Services Gets a ScriptReferenceCollection object that contains a ScriptReference object for each service that is explicitly registered with the ScriptManagerProxy control.

Properties of the ScriptManagerProxy Control The UpdatePanel Control

The UpdatePanel server control is a container control that helps you create highly interactive and responsive Web applications. The UpdatePanel control is used with the ScriptManager control to enable partial-page rendering.

You can add more than one UpdatePanel controls to a Web page. The UpdatePanel control can contain other Web server controls such as Label and TextBox controls. When the Web page with multiple UpdatePanel controls is rendered for the first time, the content for the controls present in the UpdatePanel controls is sent to the Web browser. For subsequent page postbacks, the controls present in the UpdatePanel controls update independently.

For example, in your AJAX-enabled Web application, you have used three UpdatePanel controls. In each UpdatePanel control, you have placed one GridView control. When the Web page is loaded for the first time, the data for all the GridView controls is rendered by the Web server. On subsequent partial-page refreshes, the data in the GridView controls is updated independently when the user interacts with them.

You can use the UpdatePanel control on Master pages, content pages, and in the GridView or Repeater controls.

You can add an UpdatePanel controls to a Web page by using the following markup:

The preceding markup adds an UpdatePanel server control with a unique ID UpdatePanel1 to the Web page.

The following table describes some properties of the UpdatePanel control.

Property Description

ChildrenAsTriggers Gets or sets a value that indicates whether postbacks from immediate child controls of an UpdatePanel control update the panel's content. The default value is false.

Triggers Gets a collection of all the triggers that are applied on the UpdatePanel control such as AsyncPostBackTrigger and PostBackTrigger objects.

UpdateMode Gets or sets a value that indicates when an UpdatePanel control's content is updated.

RenderMode Gets or sets a value that indicates whether an UpdatePanel control's content is enclosed in an HTML

or element.

Properties of the UpdatePanel Control The UpdateProgress Control

The UpdateProgress control is used to provide information on the status of the partial-page updates in the UpdatePanel controls. If the partial-page update is slow, you can use the UpdateProgress control to provide a message about the status of the update. For example, you can use the UpdateProgress control in situations where the client application has requested for voluminous data that will take a substantial amount of time to load, such as retrieving more than 500 records in a single request or request for a heavy video file from the server.

The UpdateProgress control can be customized. You can modify the default content and the layout of the UpdateProgress control.

The UpdateProgress control can be added to a Web page by using the following markup:

The preceding markup adds an UpdateProgress server control with a unique ID UpdateProgress1 to the Web page.

The following table describes some properties of the UpdateProgress control.

Property Description

AssociatedUpdatePanelID Gets or sets the ID of the UpdatePanel control for which the UpdateProgress control displays the status of update.

DisplayAfter Gets or sets the value (in milliseconds) before the UpdateProgress control is displayed. The default value is 500 milliseconds.

DynamicLayout Gets or sets a value that determines whether the progress template is rendered dynamically.

Properties of the UpdateProgress Control The Timer Control

The Timer control is used with the UpdatePanel control to perform partial-page updates at a predefined time interval. The Timer control can also be used to post the entire Web page at a predefined time interval.

You can use the Timer control in your Web application to perform the following tasks:

 Periodical updates of one or more UpdatePanel controls without refreshing the entire Web page.  Execution of the code at the server each time the Timer control causes a postback. When the tick event of the Timer control is raised, it causes a postback and the code written under the tick event handler is executed. For example, a part of a website that displays the score of a cricket match is updated after every one minute. The code for updating the score can be written under the tick event handler of a timer control so that it executes after the set time interval.  Synchronous postback of the entire Web page to the Web server at predefined time intervals.

The Timer control embeds a JavaScript component into the Web page. The JavaScript component initiates the postback from the Web browser to the Web server, every time the predefined time interval has lapsed. When the postback is initiated, the Timer control raises the Tick event on the server. To handle the Tick event, you can add an event handler that performs certain predefined actions in response to the event.

You can place multiple Timer controls on a Web page. You can associate each Timer control with a different UpdatePanel control. However, you can also place one Timer control on the Web page and associate it with all the UpdatePanel controls.

You can add a Timer control to a Web page by using the following markup:

The preceding code adds a Timer server control with a unique ID Timer1 to the Web page. The following table describes some properties of the Timer control.

Property Description

Enabled Gets or sets a value that indicates whether the Timer control initiates a postback to the server after the number of milliseconds specified in the Interval property has elapsed.

Interval Gets or sets the number of milliseconds to wait before initiating a postback to the server. The default value is 60,000 milliseconds.

Properties of the Timer Control

AJAX server controls raise some events when a client interacts with them. These events describe how an AJAX-enabled Web application is loaded when requested for the first time or how it behaves when a user sends a request to the Web server. To understand the events raised by an AJAX-enabled Web application, you need to understand the client life-cycle events of ASP.NET AJAX.

Identifying the ASP.NET AJAX Client Life- Cycle Events

AJAX-enabled Web applications mainly consist of a client-side script that is processed by the Web browser. When a user interacts with an ASP.NET AJAX-enabled application, it raises some client events. These events are handled at the client side and are called client life-cycle events.

The client events enable you to customize both synchronous and asynchronous (partial-page updates) postbacks. These events also help you manage custom script components during the lifetime of the Web page on the browser.

Client events are raised by the classes present in the Microsoft AJAX Library. The two main Microsoft AJAX Library classes that raise events are Application and PageRequestManager. These classes are automatically instantiated when an event is raised on a Web page that contains AJAX server controls. These classes provide APIs that enable you to bind the events to the controls and provide handlers for those events. For example, when an UpdatePanel control is added to a Web page, the events of the PageRequestManager class are raised. These events can be used to cancel postback or to provide preference to one postback over the other. These events can also be used to animate the UpdatePanel control when the content in the control is refreshed. Client Events of the Application Class

The Application class of Microsoft AJAX Library is instantiated when a Web page displayed on the Web browser contains a ScriptManger control. It inherits the Sys.Component class.

The following table lists the client events of the Application class that are raised in AJAX- enabled Web pages.

Event Description

Sys.Application.init Is raised after all scripts have been loaded on the Web browser. You can use this event to add your custom component to the Web page. This event is raised only when the page is rendered for the first time.

Sys.Application.load Is raised after all scripts have been loaded on the Web browser and all the objects in the application are initialized. This event is raised for all postbacks to the server, including the asynchronous postbacks.

Sys.Application.unload Is raised before all objects are disposed and before the window.unload event of the Web browser window occurs.

Sys.Component. propertyChanged Is raised when a property of a component changes. To raise this event, you need to call the Sys.Component.raisePropertyChange method in a set accessor.

Sys.Component.disposing Is raised when the Application instance is disposed.

Client Events of the Application Class Client Events of the PageRequestManager Class

To enable a Web page to perform partial-page update, you need to add a ScriptManager control and an UpdatePanel control. When such a page is displayed on the Web browser, an instance of the PageRequestManager class is automatically instantiated on the browser. This class raises client events that are specific to asynchronous postbacks (partial-page update).

The following table lists the client events of the PageRequestManager class that are raised in the AJAX-enabled Web pages.

Event Description

Sys.WebForms.PageRequestManagerintializeRequest Is raised before an asynchronous request starts. You can use this event to cancel a postback.

Sys.WebForms.PageRequestManagerbeginRequest Is raised before an asynchronous postback starts and till the postback is sent to the server. If a postback is already processing, the other postback is stopped by using the abortPostBack method. This event can be used to begin an animation on the page to indicate that the request is in process.

Sys.WebForms.PageRequestManagerpageLoading Is raised after the response from the server to an asynchronous postback is received by the Web browser, but before any content on the page is updated or displayed. This event can be used to provide a custom transition effect for updated content.

Sys.WebForms.PageRequestManagerpageLoaded Is raised after all content on the page is refreshed, as a result of either a synchronous or an asynchronous postback. This event can be used to manage a custom transition effect for updated content. Sys.WebForms.PageRequestManagerendRequest Is raised after the response for an asynchronous postback is processed and the page is updated, or during the processing of the response if there is an error. If an error occurs, the page is not updated. This event is used to provide customized error notification to users or to log errors.

Client Events of the PageRequestManager Class Consuming Web Services in AJAX-Enabled Applications

In AJAX-enabled Web applications, the Web service is called by using client-side scripts. To enable client scripts to communicate asynchronously with the server, ASP.NET AJAX provides the asynchronous communication layer. This layer enables a client application to call Web services by using JavaScript. The asynchronous communication layer acts as an intermediary layer between the browser and the server. It uses the XMLHTTP object to communicate asynchronously. The Asynchronous Communication Layer

The ASP.NET AJAX architecture provides an asynchronous communication layer that enables a Web browser to call the Web service methods by using JavaScript. JavaScript can use the APIs that are exposed by the asynchronous communication layer. These APIs use the asynchronous behavior provided by the browser’s XMLHTTP object.

The asynchronous communication layer offers the following features:

 It enables the JavaScript code to perform asynchronous calls to the server.  It can invoke methods in Web services that are implemented as .asmx or .svc files. It makes Web service interactions easier by generating JavaScript proxies for Web services that can be accessed from the client script.  It can invoke ASP.NET static page methods like a Web service method.  It supports a variety of serialization formats such as JavaScript Object Notation (JSON), string data, and XML data for passing data between the browser and the server.  It provides extensibility for client executors that are used by the proxy objects.

Note

An executor is a component that functions as an interface between a client Web request and the network or other media. You can write your own executor that plugs into the asynchronous communication layer. JSON Support in Consuming Web Services

To call a Web service by using JavaScript, a Web browser interacts with a Web server through asynchronous communication layer. While communicating, the asynchronous communication layer exchanges data between the Web browser and the Web server. This data is exchanged in a format named as JSON.

JSON is a standard and default format used for serialization by the asynchronous communication layer. It makes the interaction between the client and the server easy by eliminating the need for the client script to construct request.

Data that is formatted in the JSON format is lightweight and easy to be parsed by implementing JavaScript. JSON is the ideal format for data exchange for AJAX-enabled Web applications. It can also be used to exchange or store structured information as text. A JSON object provides two methods, JSON.parse and JSON.stringify. The JSON.parse method is used to serialize objects and arrays into JSON text format and the JSON.stringify method is used to convert JSON text format to in-memory objects. Creating and Registering Client Scripts

An AJAX-enabled Web application calls a Web service by using client script. There might be a possibility that the built-in client scripts in an AJAX-enabled Web application does not provide the functionality that you want when calling a Web service. To implement such functionality, you need to create a custom client scripts and integrate it with an AJAX- enabled ASP.NET application. A custom client script can be created and integrated with an AJAX-enabled ASP.NET application as:

 Inline script  External java script file  Script embedded as a resource in an assembly

Inline Script

An inline script can be created as a script block in a Web page. A script block is defined in a Web page as an HTML markup. The following code snippet shows how you can define a script block in a Web page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Untitled Page

onclick="HelloWorld()" />

In the preceding code snippet, a script block is defined that consists of a function, HelloWorld. When a user clicks the Hello button on the Web page, the HelloWorld function is called and an alert box showing the Hello World! Message is displayed.

An inline script is not registered in an AJAX-enabled ASP.NET application because the script block is defined in a Web page only.

External Java Script File You can also add a reference of an external java script file in an AJAX-enabled ASP.NET application. To add the reference, you need to add the java script file in your Web application. After adding the java script file, you need to set the src attribute of the script element of the Web page to the name of the java script file.

The following code snippet is written in a java script file, JScript.js: function HelloWorld()

{

alert(’Hello World!’);

}

In the preceding code snippet, a function HelloWorld is created and an alert message, Hello World!, is defined.

The highlighted part of the following code snippet shows how you can set the src attribute of the script element of the Web page to a java script file:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Untitled Page

onclick="HelloWorld()" />

In the preceding markup, a java script file, JScript.js is specified in the src attribute of the script element of the Web page. When a user clicks the Hello button, the function HelloWorld defined in the java script file is called and an alert message box showing the message, Hello World!, is displayed.

Script Embedded as a Resource in an Assembly

You can also add a custom client script in a web page by using the ScriptManager control. Such a client script consists of a java script file that is embedded as resources in an assembly. The java script that is embedded in an assembly acts as a Web resource. For example, you are creating a custom control that consists of a java script file. This file can be embedded as a Web resource in the assembly of the custom control.

To access such a java script file, an HTTPhandler WebResource.axd is used by the ASP.NET application. This handler retrieves assembly resources and serves them to a Web browser. To access the assembly resources using a ScriptManager control, you need to add the reference of the assembly and the java script file as shown in the following markup:

Name="ClassLibrary.JScript1.js" />

In the preceding markup, a ScriptManager control is defined. A reference of the assembly and the java script file is added in the scripts tag of the ScriptManager control.

Most client-side code is added at design time. However, it can also be generated and added in the Web page at run time by using the System.Web.UI.ClientScriptManager class. Consider the following code snippet: protected void Page_Load(object sender, EventArgs e)

{

string str="return confirm(’Do you want to submit the

page?’)";

ClientScript.RegisterOnSubmitStatement(this.GetType(),"ABC", str);

}

To manage, register, and add a script to a Web page, you need an object of the ClientScriptManager class. In the preceding code snippet, the ClientScript property of the Page object has been used to obtain a ClientScriptManager object. The RegisterOnSubmitStatement method registers an OnSubmit statement with the Page object.

In RegisterOnSubmitStatement (Type type, String key, String script) method:

 The type parameter defines the type of the control that is registering the OnSubmit statement.  The key parameter defines a key that uniquely identifies the script statement.  The script parameter defines the script literal for the OnSubmit statement.

Note

A custom client script can also be used to add AJAX functionality into a server control. To provide AJAX functionality in a server control, you need to embed the JavaScript file as a resource in the assembly that is created when the server control is precompiled.

Summary

In this chapter, you learned that:

 AJAX is a Web development technique that is used to create dynamically interactive applications.  AJAX enables Web applications to retrieve data from the server, asynchronously in the background, without interfering with the display and behavior of the existing page.  AJAX includes the following terms: o Asynchronous communication o JavaScript o XML  The advantages offered by AJAX-enabled Web applications are: o They provide quick response to a user’s request. o They allow users to interact with the rest of the Web page while the application is processing the changed or updated parts of the Web page. o They provide auto-generated proxy classes that are used to call Web service methods from client script such as JavaScript. o They provide support for the widely used Web browsers such as Microsoft Internet Explorer, Mozilla Firefox, and Apple.  The limitations of AJAX-enabled Web applications are: o Browser Integration o Dependency on JavaScript  The ASP.NET AJAX architecture consists of the following components: o Client-based Microsoft AJAX library o Server-based AJAX features for ASP.NET  Some of the AJAX server controls offered by ASP.NET are: o ScriptManager control o ScriptManagerProxy control o UpdatePanel control o UpdateProgress control o Timer control  Client events are raised when a user interacts with an ASP.NET AJAX-enabled application.  Client events are raised by the classes present in the Microsoft AJAX Library.  The two main Microsoft AJAX Library classes that raise events are: o Application o PageRequestManager  The ASP.NET AJAX architecture provides an asynchronous communication layer that enables a Web browser to call the Web service methods by using JavaScript.  JSON is a standard and default format used for serialization by the asynchronous communication layer.  A custom client script can be created and integrated with an AJAX-enabled ASP.NET application as: o Inline script o External java script file o Script embedded as a resource in an assembly

Reference Reading

Explaining the AJAX Frameworkn Reference Reference Reading: URLs Reading: Books

ASP.NET http://blogs.sun.com/enterprisetechtips/entry/building_an_ajax_enabled_we

AJAX b Programmer’ s Reference: With ASP.NET 2.0 Or ASP.NET 3.5 by Shahram Khosravi

Identifying the ASP.NET AJAX Server Controls

Reference Reference Reading: URLs Reading: Books

Pro ASP. http://www.asp.net/AJAX/Documentation/Live/overview/PartialPageRendering

Net 3. 5 Overview.aspx Server Controls and AJAX Compone nts by Rob Cameron, Dale Michalk

Identifying the ASP.NET AJAX Client Life-Cycle Events

Reference Reference Reading: URLs Reading: Books

Pro http://www.asp.net/AJAX/Documentation/Live/overview/PartialPageRenderingO ASP.NET verview.aspx 3.5 in C# 2008 by http://www.dcs-media.com/desdev/dotNet/aspnet-ajax-client-life-cycle- Matthew events.aspx MacDona ld Chapter 11 Implementing Internationalization and Accessibility

An organization that does business in the global marketplace must design applications to accommodate users from a wide variety of cultures. Users in different parts of the world use different languages and different formatting standards for numbers, currency, and dates. Therefore, you need to enable your Web applications to represent information in the users’ native language and formats. This functionality can be provided by implementing internationalization.

Web applications may also be accessed by users with disabilities. These users may not be able to interact with the user interface properly because of their disabilities. A Web application should be designed in such a way that it is easily accessible to such users. This can be achieved by implementing accessibility features.

This chapter discusses how to implement internationalization and accessibility features in a Web application to make the application accessible to everyone. Objectives

In this chapter, you will learn to:

Implement internationalization

Implement accessibility Implementing Internationalization

Web applications are accessed by people from different countries, cultures, and regions. These people may want the information on the websites to be in their native language and formats. This would make it easy for them to understand the content given on the site. To enable the people from different countries, cultures, and regions to access your Web application, you need to implement internationalization in the application. The process of making an application ready for international users is called internationalization.

Consider the scenario of an organization that has a chain of hotels in various countries. The organization is maintaining the information about the hotels through a website. This website is accessed by people from various countries.

The website has a limitation. The information provided by the website is in English and the currency is set to United States Dollar (USD). This poses problems for the non-English speaking people because they are unable to understand the information given on the website. As a result, people from the countries where the currency is other than USD have to calculate the fares according to their currency. These problems are affecting the popularity of the website.

To accommodate users from different countries and enable them to use the website efficiently, the organization decides to implement internationalization in the application. Implementing internationalization on the website would enable people from various countries to have the information on the website in their native language and formats. This would help users to easily understand the information given on the website.

To target the wide range of audience and to enable them to browse through your website, your Web application must be designed to accommodate users from various countries and cultures. This can be done by implementing internationalization in the application.

International applications should be customizable according to the preferences of users belonging to different nations, cultures, or regions. User preferences refer to the language, currency, and formats. To make an international application customizable, you need to understand the following phases that are involved in developing an internationalized application:

 Globalization: Globalization is the process of designing and developing a Web application in such a way that it is culture-neutral and language-neutral. In this phase, the executable code is separated from the data specific to a locale.  Localizability: Localizability is an intermediate process that ensures that a globalized Web application is ready for implementing localization. The purpose of this step is to test whether the application's executable code is independent of the culture and language-specific data. This means that the culture and language-specific details should not be hard-coded into the application code.  Localization: Localization is the process of customizing the globalized Web application to a specific locale and culture. In this phase, various resources, such as images and text, for the designated locale are created. For example, to localize an application for French users, all text messages should be translated to French.

Note

Locale is a combination of a language and a country. It includes information about the formats used for representing time and date, symbols, and conventions used for representing currency, and the character encoding scheme being used. Factors Related to Creating International Applications

Application developers need to attend to locale considerations when they develop international applications because negligence of these considerations can lead to issues. The factors that need to be considered while designing an internationalized application are:

 Language issues  Formatting issues  String-related issues  User-interface issues

Language Issues

Languages around the world differ in display, alphabets, grammar, and syntactical rules. For example, some languages such as Arabic are written from right-to-left, whereas other languages are written from left-to-right. Some languages include uppercase and lowercase characters, whereas others do not even have the concept of uppercase and lowercase. Languages differ in the number of characters, storage requirements, keyboard layouts, and code representations. This diversity makes it difficult to share data between cultures. It is even more difficult to create a multilingual user interface.

Formatting Issues

Formatting is the main source of differences in applications designed for multiple languages or cultures. Formatting differences may arise in the addresses, currency, dates, numerals, telephone numbers, time, and units of measure of various languages.

String-Related Issues

When developing international applications, programmers must consider issues related to strings. When strings are translated from one language to another, the translated strings may be longer than the original strings. In strings, the order of alphabets varies in different languages. This causes major problems in sorting and comparison of strings. Issues also arise when strings are concatenated because these strings may convey different meanings in different languages.

User-Interface Issues

Various user interfaces are associated with the design of an international application. The size of user interface elements should be larger than that required for accommodating English strings. This is because strings in other languages are usually longer than strings in the English language. When messages grow in size as a result of translation to another language, they should be allowed to wrap to subsequent lines. You should also ensure that all the access-key and shortcut-key combinations are available on international keyboards. This is because every language has a different , and some characters do not exist on all keyboards. Creating International Applications

The structure of an application that is created with internationalization in mind is divided into the following two blocks:

 Data block: Contains user-interface resources, such as the text on Label controls that are to be translated into various languages. This block is locale-specific, and each locale will have one data block.  Code block: Contains the application code or the executable part of an application that is applicable to all cultures/locales. This block will remain same for all locales. The separation of culture/locale specific and culture/locale independent parts allows a user to dynamically switch the user interface to a localized version.

The data block of a Web application consists of a set of resource files. Each application has a default resource file that contains the resources in the default language/culture. For each additional language/culture that your website needs to support, you need to create a separate resource file, called a localized resource file.

Information is stored in resource files as a set of key/value pairs. For example, if you want to display a welcome message on a Web page, you can create a key named WelcomeText. The resource files for each language/culture can then specify a different value to the key depending on the language/culture.

The .NET Framework represents different cultures across the world by using a culture code. A culture code consists of two parts, a two-letter language code and an optional two-letter country/region code.

The general format of the culture code is:

-

The following table lists some culture codes and their descriptions.

Culture Code Description En Specifies English language, no region en-CA Specifies English language, Canada fr-FR Specifies French language, France De Specifies German language, no region Zh-CN Specifies Chinese language, China region de-DE Specifies German language, Germany region

Culture code snippets that only specify a language are called neutral cultures, whereas culture code snippets that specify a language as well as a region are called specific cultures.

To implement globalization in an application, you need to include the System.Gloablization namespace in your application. The System.Gloablization namespace provides classes that define culture-related information, such as the language, country, calendars, and formats. Two important classes included in the System.Gloablization namespace are:

 CultureInfo  RegionInfo

The CultureInfo Class The CultureInfo class provides information about a specific culture. The information includes details such as the name of the culture, the formatting styles used, and the calendar used.

The following table lists some of the commonly used properties of the CultureInfo class.

Property Description

CurrentCulture Returns an instance of the CultureInfo class that represents the culture for the current thread.

CurrentUICulture Returns an instance of the CultureInfo class that represents the current culture used by the Resource Manager to look for culture- specific resources at run time. Name Returns the name of the culture in the - format. IsNeutralCulture Returns a Boolean value indicating whether the culture represented by the CultureInfo object is a neutral culture.

NumberFormat Gets or sets a NumberFormatInfo object that defines the appropriate format of displaying numbers, currency, and percentage.

Properties of the CultureInfo Class

The following table lists some of the commonly used methods of the CultureInfo class.

Method Description

CreateSpecificCulture Creates a CultureInfo object that represents the specific culture that is associated with the specified name. GetCultureInfo Returns a read-only instance of a culture. GetCultures Gets a list of supported cultures filtered by the specified type. GetFormat Returns an object that represents the format of a specified type. For example, this method will return an object representing the format of the date when the specified type is date/time.

Methods of the CultureInfo Class You can set two culture values for an ASP.NET application, the Culture and UICulture properties. These values determine the types of resources loaded for an application and the formatting options for various fields like currency, numbers, and dates. The resources loaded are determined by the UICulture property and the formatting options are determined by the Culture property.

You can set the Culture and UICulture properties for all pages on a website by using the globalization section of the web.config file, as shown in the following example:

You can set the Culture and UICulture properties for individual pages by using the @Page directive of the page, as shown in the following example:

<%@ Page UICulture=”fr” Culture=”fr-FR”>

If you want to set the UICulture and Culture values to the first language specified in the current browser settings, you need to set the UICulture and Culture values to auto.

However, you should not rely exclusively on the browser settings to determine the UI culture for a page because users frequently use browsers that are not set to their preferences. Therefore, you must provide users a method to explicitly select a language/culture for their page.

You can set the UICulture and Culture values for a page programmatically by overriding the InitializeCulture method and using any of the following methods in the overridden method:

 Set the UICulture and Culture properties of the page to the desired values.  Set the CurrentUICulture and CurrentCulture properties of the current thread to the desired UI culture and culture, respectively.

Consider the following example that demonstrates how to use both the methods: protected override void InitializeCulture()

{

if (Request.Form["ListBox1"] != null)

{

String language = Request.Form["ListBox1"];

UICulture = language;

Culture = language;

Thread.CurrentThread.CurrentCulture =

CultureInfo.CreateSpecificCulture(language); Thread.CurrentThread.CurrentUICulture = new

CultureInfo(language);

}

base.InitializeCulture();

}

The code given in the preceding example allows users to select their preferred language from a drop-down list and sets the UICulture and Culture properties accordingly.

The RegionInfo Class

The RegionInfo class contains information about a country/region. The following table lists some properties of the RegionInfo class.

Property Description CurrencySymbol Gets the currency symbol for the country/region.

CurrentRegion Gets a RegionInfo object that represent the county/region used by the current thread. IsMetric Gets a value that indicates whether the country/region uses the metric system for measurement.

The following table lists some methods of the RegionInfo class.

Method Description Equals Determines whether the specified object is the same instance as the current RegionInfo object. GetType Gets the type of the current instance.

Implementing Culture-Specific Formatting The resource files allow you to specify the text appearing on a website in different languages. However, if you want to change the format of date, time, or currency values depending on the current culture, you need to specifically write code for implementing the same.

Suppose you want to use different formats for displaying a date on a Label control, depending upon the current culture. Dates can be displayed in various formats. Each format has a format character associated with it.

The following table lists some date formats, and their corresponding format characters.

Date Formats

The preceding table specifies the pattern of date/time in the en-US culture. Other cultures may have slightly different patterns for each date format.

The following code snippet demonstrates how to use a different format for displaying a date depending on the current culture: protected void Page_Load(object sender, EventArgs e)

{

DateTime dt = DateTime.Now;

CultureInfo USCulture = new CultureInfo("en-US");

CultureInfo FrenchCulture = new CultureInfo("fr-FR");

if (CultureInfo.CurrentCulture.Equals (FrenchCulture))

Label2.Text = dt.ToString("d", FrenchCulture); else

Label2.Text = dt.ToString("d", USCulture);

}

In the preceding code snippet, the ToString() method of the DateTime object is used to convert the date to the Short Date format, as specified by the first parameter of the ToString() method. The second parameter specifies the culture to be used for the short date format.

At run time, if the user’s browser settings specify French (France) as the preferred language, the date will be displayed in the format, dd/MM/yyyy. However, if the preferred language is set to any other value, the date will be displayed in the US format, MM/dd/yyyy. Implementing Accessibility

When you develop a Web application, you want the application to be used by as many users as possible. Your Web application may be used by users with some disabilities. These users may not be able to interact with your Web application properly because of their disabilities. As a Web developer, you need to take care of all such issues and design the Web application in such a way that it can be accessed easily by most of the users. This can be done by implementing accessibility.

Accessibility refers to the degree of ease with which an application can be used by a variety of people. Implementing accessibility in a Web application helps people having disabilities as well as enables other users to interact with the application more efficiently. ASP.NET provides some guidelines that you should consider while designing your Web application to achieve high accessibility. Fundamentals of Designing an Accessible Application

Creating an application that complies with all accessibility guidelines is not feasible because it requires a substantial amount of time and money. Therefore, you need to select the suitable accessibility features that would be implemented in an application. The selection of features should depend upon the profile of the users accessing the application. For example, if you are creating an application for retired people, most of the users will be over 60 years of age. These users may be suffering from old age ailments such as diminished vision. Therefore, your application should have accessibility features such as appropriate font size and background color to enable the users to easily interact with the application.

The features of a Web application that are used frequently should have a high degree of accessibility. For example, on an online shopping site, shopping cart feature is a frequently- used feature. Therefore, a developer should strictly follow the accessibility guidelines while designing this feature. The principles that should be followed while implementing accessibility support in an application are:

 Flexible user interface: Flexibility of a user interface refers to its capability to change its presentation to adapt to changing user preferences.  Flexible input and output features: Flexible input features refer to numerous ways in which a user can interact with an application. All features should be accessible through keyboard with the same degree of ease as while using mouse. Three-click rule should always be followed, which states that all functionality should be accessible in a maximum of three clicks. Flexible output features refer to the numerous ways in which a user can retrieve information from an application. It is a good accessibility practice to keep a wide range of output options such as text, images, sound, and graphics.  Simple and Intuitive: The user interface should be simple and easy to understand, regardless of a user's experience, knowledge, language skills, or current concentration level. Any unnecessary complexity should be eliminated. Each object on the screen should be assigned a unique and descriptive label to assist users who cannot see its context on the screen.

The application should interact with other applications in a standard manner. For example, the application should provide a standard mechanism for importing data from and exporting data to other applications. Accessibility Design Guidelines for the Web

Accessibility makes an application user friendly. There are instances when people are not able to access information just because of bad accessibility design, such as small font size of the text given in an application or improper navigational structure. Some guidelines for implementing accessibility in an application are:

 Standardize font styles: While deciding the font style, you should keep in mind that users having diminished eyesight may also access your website. Therefore, you need to select the font style and the color for the background and foreground such that the text is easily readable. Some of the important guidelines for designing a website that can be used by the users having diminished eyesight are: o Font size should be greater than 12 points. However, the font size may differ depending upon the font style. o Text should not be italicized. o Important points should be in bold. o Decorative fonts should be avoided. o Text color and background color should be selected in such a way that the text can be easily read.  Support keyboard navigation: Keyboard navigation in an application can be provided by using the TAB key. The TAB key navigation direction should be from top to bottom and left to right. The navigation order while using the TAB key should be correct. All navigation links should have tool tip that explains the use of the link. All controls should be assigned keyboard shortcuts. ASP.NET provides the following properties that are set for the controls used in a Web page so as to enable a user to navigate properly by using the Tab key: o TabIndex: You can specify the TabIndex property of a control to set tab order for proper navigation. o DefaultButton: You can specify default button for a form or a panel by setting its DefaultButton property. The DefaultButton property specifies that a user can cause a postback by pressing the ENTER button in an input control in the form such as a text box. o AccessKey: Keyboard shortcuts can be assigned to each control by using the AccessKey property of the control. o ToolTip: Tool tips can be displayed for each control by using the ToolTip property of the control. o AssociatedControlID: You can associate a Label control to another control by setting the AssociatedControlID property of the Label control to the ID of the relevant control. You can then use the properties of the Label control to set some properties of the associated control. For example, you can use the Text and AccessKey properties of the Label control to provide the caption and short-cut key for the associated control.  Standardize the use of images: When you use images in the form of buttons, links, or image maps in your application, you should provide a meaningful text for the images to enable user to understand its functionality. ASP.NET allows you to do this by setting the following properties of controls: o AlternateText property: You can specify the AlternateText property of the image to provide a meaningful text to the image. o GenerateEmptyAlternateText: You can specify the GenerateEmptyAlternateText property to true if the image does not provide any functionality or does not convey information relevant to the context of the Web page and is used for enhancing the UI of a Web page.

In addition, controls such a TreeView and Menu controls display images or links. For example, the TreeView control displays images for the expand and the collapse button for each node in the TreeView control. The TreeView control generates alternate text for these images based on the text of the node. By default, the alternate text for the image of the expand button that has the text as Start is rendered as Expand Start on a Web page. You can also specify your own alternate text by setting the ExpandImageToolTip and CollapseImageToolTip properties for the TreeView control.

 Standardize the use of tables on a Web page: You use tables in your Web application to place each control in a well-organized and structured manner. While creating a table, you should specify the caption to help assistive technologies such as screen readers to identify the purpose of the table by setting its caption property.  Minimize the use of style sheets: The layout of a form should not be affected when it is displayed in a browser that does not support style sheets. For this, you need to provide an alternate page that does not make use of style sheets for every page that uses a style sheet.  Use controls properly: While using controls at the time of designing an application, you should consider the following points: o Do not use ActiveX controls as some browsers may not support them. If you are using an ActiveX control on a Web page, it should have an alternate page that does not contain the ActiveX control. o Use either LABEL or TITLE tags to specify the name of each control.

Note

An ActiveX control can be automatically downloaded and executed by a Web browser. ActiveX is a set of rules for how applications should share information. Programmers can develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and Java. Assistive Technologies Used for Accessibility of the Web

People with disabilities use various assistive technologies for accessing a Web application. These assistive technologies are the products used by them to access a Web application in an easy way. You should develop a Web application that should support these technologies so as to enable the maximum number of users to access your Web application. Some assistive technologies used by people with disabilities are:

 Braille and Refreshable Braille: Braille is a system using six to eight raised dots in various patterns to represent letters and numbers that can be read by the fingertips. Braille system is used by blind people. Braille consists of an 8-dot version that has been developed to allow all ASCII characters to be represented on a Web browser. Refreshable Braille offers mechanical display where the dots are raised and lowered dynamically that allows a Braille character to be displayed on a Web browser. Refreshable Braille displays can be incorporated into portable Braille devices with the capabilities of small computers, which can also be used as interfaces to devices, such as information kiosks.  Scanning Software: Scanning software is adaptive software used by individuals with some physical or cognitive disabilities that highlights or announces selection choices such as menu items, links, or phrases one at a time. A user selects a desired item by hitting a switch when the desired item is highlighted or announced.  Screen Magnifiers: Screen magnifier is software used primarily by individuals with low vision that magnifies a portion of the screen that allows them to easily view a Web application on a Web browser. Screen magnifiers make presentations larger, and reduce the area of the document that can be viewed by removing surrounding context. Some screen magnifiers offer two views of the screen, one magnified and one default size for navigation.  Screen Readers: Screen reader is software that is used by individuals who are blind or who have dyslexia. It interprets what is displayed on a screen and directs it either to speech synthesis for audio output or to refreshable Braille for tactile output. Some screen readers use the document tree such as the parsed document code as their input. In addition, the screen readers use linearization process for interpreting the text in each column of each row of a table on your Web page. It reads all the text in the first cell of row one, the second cell, the third, and so on until it runs out of cells. It then moves on to the second row.  Speech Recognition: Speech recognition is used by people with physical disabilities or temporary injuries to hands and forearms. It is used by them as an input method in a voice browser that allows voice-driven navigation. Applications that have full keyboard support can be used with speech recognition.  Visual Notifier: Visual notifier is an alternative feature of some operating systems that allows hearing impaired users to receive a visual alert of a warning or error message that might otherwise be issued by sound. Summary

In this chapter, you learned that:

 The process of making an application ready for international users is called internationalization.  The phases that are involved in developing an internationalized application are: o Globalization o Localizability o Localization  The factors that need to be considered while designing an internationalized application are: o Language issues o Formatting issues o String-related issues o User-interface issues  The two blocks that make a structure of an internationalized application are: o Data block o Code block  The System.Gloablization namespace provides classes that define culture-related information, such as the language, country, calendars, and formats.  The two important classes included in the System.Gloablization namespace are: o CultureInfo o RegionInfo  The principles that should be followed while implementing accessibility support in an application are: o Flexible user interface o Flexible input and output features o Simple and Intuitive  The guidelines to implement accessibility in an application are: o Standardize font styles o Support keyboard navigation o Standardize the use of images o Standardize the use of tables o Minimize the use of style sheets o Use controls properly

Reference Reading

Implementing Internationalization

Reference Reading: Reference Reading: URLs Books

Ethical and Social Issues http://wiki.asp.net/page.aspx/55/internationalization/ in Professional Education by Celeste M. Brody, James Wallace

Managing Across Cultures by Susan C. Schneider, Jean-Louis Barsoux

Implementing Accessibility

Referen Reference Reading: URLs ce Reading : Books

Pro http://www.globalknowledge.com/training/course.asp?pageid=9&courseid=1134

ASP.NE 5&catid=184&country=United+States T 3.5 in C# 2008 by Matthe w MacDo nald, Mario Szpuszta

Chapter 12 Securing Web Applications

Organizations use Web applications to share and access important data. As the Internet is a majorly-used medium for sharing and accessing data, this data needs to be secured from unauthorized users. Therefore, security has become one of the major aspects in developing a Web application. ASP.NET provides a security model that enables developers to address security-related issues in Web applications.

This chapter discusses about identifying the ASP.NET security process. In addition, it explains how to configure ASP.NET Web applications for security. Objectives

In this chapter, you will learn to:

Identify the ASP.NET security process

Configure an ASP.NET Web application for security Identifying the ASP.NET Security Process

Most of the websites restrict access to some of its content. This is necessary to provide different levels of access to different types of users. For example, on an online shopping website, the product catalog is accessible to all the users accessing the website. However, certain portions of the website such as status of customer's order or customer's payment details should only be accessible to users with certain credentials, such as employees.

Controlling access to the content in a Web application helps you protect your application from various security threats, such as tampering with data files and stealing passwords. The ASP.NET security model allows you to deal with these security threats to help secure your Web applications. Introducing the ASP.NET Security Model

The ASP.NET security model allows you to implement security in your Web applications. It provides restricted levels of access to secure website information from unauthorized access. It also helps in maintaining data integrity and confidentiality. The following figure displays the architecture of the ASP.NET security model.

IIS and ASP.NET Interaction

The preceding figure indicates that ASP.NET security works in conjunction with Internet Information Services (IIS) to implement security in a Web application. The following steps describe the working of the ASP.NET security model:

1. IIS receives a request from a Web client. 2. It attempts to authenticate the user. If the user is authenticated, the request is checked. If the request is for a non ASP.NET Web page, the request is directly passed to the operating system. The operating system performs its own security checks to verify that the authenticated user is allowed to access the specified file and directory. However, if the request is for an ASP.NET Web page, it is passed to ASP.NET with additional information about the authenticated user. ASP.NET uses its own security services, depending on the settings in the web.config file and the page that was requested. 3. If ASP.NET authenticates the user, it allows requests to the specified Web page. Your code can perform additional security checks such as manually asking for another password by using the .NET Framework. 4. When the ASP.NET code requests resources, the operating system performs its own security checks to verify that the authenticated user is allowed access to the specified file and directory. 5. If access is granted, the requested resource is returned through IIS.

All Web users communicate with ASP.NET applications through IIS. Therefore, to implement security in your Web applications, you need to first configure IIS. Configuring IIS for Implementing Security Whenever a user requests for a Web application, the request is received by IIS. After receiving the request, IIS tries to authenticate the user who has requested for the application by using a specific type of authentication. The type of authentication depends on how the security for Web applications is configured on IIS. Therefore, you first need to configure security on IIS to authenticate users before they are permitted access to a Web application.

IIS provides the following different types of authentications to control access to your Web application:

 Anonymous: In anonymous authentication, IIS uses a default logon name and password to request for resources from a Web application. Therefore, this type of authentication mechanism does not require the user to provide a user ID or password to browse through a Web application.  Basic: In basic authentication, users access resources only after specifying a valid user ID and password. However, in this type, the user’s password is transmitted over the Internet in the form of plain text. It makes the method vulnerable to a sniffing attack. This method should be used in conjunction with Secure Socket Layer/Transport Layer Security (SSL/TLS). If a website is configured to use SSL/TLS and basic authentication, all data including username and password are encrypted before they are transmitted.  Digest: In digest authentication, the user password is transmitted as a hash value rather than as plain text. This authentication is similar to the basic authentication mechanism, but it is more secure. The major drawback of this method is that it is supported by very few browsers and Web servers. For example, digest authentication is only supported by IIS 5.0 and later versions.  Integrated Windows: In this type, IIS does not prompt the user to pass credentials. Instead, it extracts the user credentials from the operating system by retrieving the account information used by the user to log on to the machine. The user is granted access only if the current account under which the user has logged on is a valid account on the server.

Note

A sniffing attack is a security threat in which an attacker gains access to the network communication. The attacker can extract the message transmitted over a network. This increases the risk of private information being misused.

You can configure the preceding authentication types in IIS for a Web application by using the Internet Services Manager. Configuring an ASP.NET Application for Security The initial check for user authentication is done by IIS. After the user is authenticated, IIS sends the Web request to ASP.NET to perform a second level checking. ASP.NET uses its own security mechanism to authenticate the user.

ASP.NET first authenticates the user by using the authentication settings defined in the web.config file of the application. If the user is authenticated, it checks whether the user has the right to access the requested resource of the Web application. All this requires you to configure the security settings in the web.config file of the Web application. These security settings include configuring authentication, authorization, and impersonation for accessing resources in your application. Configuring Authentication

Authentication is the process of validating the identity of a user before granting access to a restricted resource. When ASP.NET receives a Web request from IIS, it tries to authenticate the user. This authentication is based on the settings defined in the web.config file of the Web application. These settings enable ASP.NET to determine which user is authenticated to access the Web application.

Authentication in a Web application can be configured by using the element in the web.config file. The element specifies the authentication type that is used by an application to authenticate the user. The authentication type can be specified by using the mode attribute of the element. The mode attribute can have the following values:

 Windows: This mode specifies that the authentication is performed by IIS by using Basic, Digest, or Integrated Windows authentication.  Forms: This mode specifies that the user will be authenticated by using form-based authentication method. This method displays a logon form to verify the user’s credentials.  Passport: This mode specifies that the user will be authenticated by using Microsoft Passport authentication method. Passport authentication relies on cookie-based authentication and single signing authentication service provided by Microsoft.  None: This mode specifies that no authentication mechanism is set and that any anonymous user can access the Web application.

Implementing Windows Authentication

If you choose windows as the authentication mode for your Web application, IIS takes care of the authentication process. In this mode, ASP.NET uses the user credentials authenticated by IIS for security checks.

To configure an ASP.NET Web application for Windows authentication, you need to change the mode attribute of the element to Windows, as shown in the following markup:

This type of authentication is best suited to an intranet environment where a set of known users are already logged on to a network. For example, if you are creating a Web application that is to be used within an organization, you can use the Windows authentication mode to authenticate the users. This is because the existing users already have their accounts in the database of the Web server. A Web application that implements Windows authentication rejects a user’s request that is not an authenticated user or has an invalid user name or password.

Implementing Forms Authentication

When you implement Forms authentication to a Web page, you have to create an HTML- based Web page for collecting user’s credentials and then authenticate the user. When a user enters his or her credentials and gets authenticated to view a Web page, ASP.NET generates a cookie that is served as an authentication token to the user. The browser uses this cookie for the future requests made by the user, allowing the application to validate the requests. This cookie can be encrypted by a private key located on the Web server to identify that the request is sent by the same user.

To authenticate users by using Forms authentication, you need to create and store the user credentials in a data source. You can create and manage users in ASP.NET by using the membership management service. The membership management service is used to authenticate the users who require access to Web pages. This service provides an API suite and some server controls such as CreateUserWizard to manage users in an ASP.NET Web application.

To configure an ASP.NET Web application for forms authentication, you first need to change the mode attribute of the element to Forms, as shown in the following markup:

If a user tries to access a restricted page without first logging on, the user should be redirected to the logon page. You are required to specify the settings to redirect anonymous users to the logon page. These settings are specified by using the element in the web.config file. The element has the following four attributes:

 name: It specifies the HTTP cookie that will be used for authentication. .ASPXAUTH is the default value of this attribute.  loginUrl: It specifies the URL to which the user requests are redirected for logon when no valid authentication cookie is found. The default value is default.aspx.  protection: It specifies the type of protection that a Web application uses to protect the HTTP cookie. The valid values of this attribute are All, None, Encryption, and Validation. The default value of this attribute is All.  timeout: It specifies the life span of the cookie that is used for authentication. After the time specified in the timeout attribute, the cookie expires. The value of the timeout attribute is specified in minutes.  path: It specifies the path of the cookie.

Note

When a user visits your website without logging in or providing his/her credentials, the user is called anonymous user.

The following markup shows a web.config file that is configured for forms authentication:

name=".AuthenticationCookie"

loginUrl="~/mylogin.aspx"

timeout="5"/>

In the preceding markup, the name of the HTTP cookie is AuthenticationCookie and URL to which the user will be directed for logon is mylogin.aspx. The life span of the cookie is 5 minutes.

After configuring the Web application for forms authentication, you are required to add users to the ASP.NET membership management service. You can add users by using the following methods:

 Using the element in the web.config file  Using the Membership API

When you add users to the membership management service by using either of the preceding methods, the user information is stored in the ASPNETDB.MDF file. The user information stored in the ASPNETDB.MDF file is made available to the membership management service by the membership provider.

The membership provider specifies the type of database that will be used to store the membership information. The default provider uses a Microsoft SQL Server database, ASPNETDB. You can also choose to use Active Directory or specify a custom provider to store membership information.

Note

In addition to the preceding methods, Visual Studio provides the following methods to add users to the ASP.NET membership management service:

 Using the CreateUserWizard Server Control provided by ASP.NET  Using the ASP.NET Website Administration Tool (WAT)

Adding Users by Using the Element

The element is defined within the tag in the web.config file. It contains the tag to specify the user credentials, as shown in the following markup:

name=".AuthenticationCookie"

loginUrl="/login.aspx"

protection="All"

timeout="60"

path="/">

In the preceding markup, two username/password pairs John/P@ssw0rd and Tom/123_P@ss are stored in the web.config file. The passwordFormat attribute of the tag is used to specify the format in which the password is stored in the web.config file. The passwordFormat attribute is set to Clear which means the password is stored as plain text. Other options available with passwordFormat attribute are MD5 and SHA both of which are encryption algorithms.

After specifying the user credentials, you are now required to create the login form. You can create the login form either manually or by using the login controls provided by ASP.NET. If you use login controls, you are not required to write any code to validate users, the users are validated automatically by using the credentials stored in the membership management service. However, if you create the login form manually, you are required to perform the validation programmatically. ASP.NET provides you with the FormsAuthentication class that helps you validate the users programmatically.

The FormsAuthentication class is defined in the System.Web.Security namespace and is used to implement form authentication when the configuration file is used to store user credentials. The following table lists some commonly used methods of the FormsAuthentication class.

Method Description

Authenticate Validates the user credentials passed to it and returns a boolean value indicating whether the authentication process was successful or not.

RedirectFromLoginPage Redirects an authenticated user back to the specified URL.

SignOut Removes the authentication cookies created on the computer of an authenticated user.

Methods of the FormsAuthentication Class

Consider a scenario wherein you have created a login form manually. To validate the user credentials, you need to write code as shown in the following example: protected void Button1_Click(object sender, EventArgs e)

{

if (FormsAuthentication.Authenticate(UserName.Text, Password.Text))

{

Response.Write("Welcome " + UserName.Text);

} else

{

Response.Write("Sorry! Login failed");

}

}

In the preceding example, the user name and the password are authenticated by using the Authenticate function of the FormsAuthentication class. If the user is authenticated, the message Welcome is displayed on the Web form. However, if the user is not authenticated, the message Sorry! Login failed is displayed on the Web form.

Adding Users by Using the Membership API

When adding users by using the element in the web.config file, you need to add all the users at design time. In addition, if you want to modify or delete a user, you need to manually remove or modify the users in the web.config file. However, if you want to add, modify, or delete users at run time, you need to use the Membership class. To implement the Membership class, you need to use the System.Web.Security namespace. The Membership class has various static methods that allow you to manage users at run time. The following table lists some useful static methods.

Method Description

CreateUser Adds a new user to the database.

DeleteUser Deletes an existing user from the database. To delete a user, you need to specify the user name.

GetUser Gets information from the data source for the membership users associated with the unique identifier .

GetAllUsers Gets a collection that represents all the users in the database.

UpdateUser Updates information for a specific user.

ValidateUser Validates the supplied user name and password.

Static Methods of the Membership Class

Consider the following example: protected void AddUser_Click(object sender, EventArgs e)

{

MembershipCreateStatus result;

try

{

MembershipUser newUser =

Membership.CreateUser(UserName.Text,

Password.Text, Email.Text, passwordQuestion.Text,

passwordAnswer.Text, true, out result);

if (result==MembershipCreateStatus.Success)

{

Response.Write("User Successfully Created");

ShowAllUsers();

}

else

{

Response.Write("Sorry cannot create the user");

}

}

catch (Exception err)

{

Response.Write(err.Message);

}

}

public void ShowAllUsers()

{

GridView1.DataSource = Membership.GetAllUsers();

GridView1.DataBind();

}

In the preceding example, the code within the AddUser_Click event handler is written to create a user. If the user gets created successfully, the method ShowAllUsers is invoked. This method is used to retrieve all the users and display them in the GridView control. However, if any exception is thrown by the code, the error message is displayed on the Web form.

Once created, you can change the user details by using the methods of the Membership class. For example, you have created a user with the name user1. Now, you want to change the password for the user. For this, you need to write the following code snippet:

MembershipUser currentUser = Membership.GetUser("user1"); if (currentUser.ChangePassword("OldPassword", "NewPassword"))

{

Label1.Text = "Your password is successfully changed";

} else

{

Label1.Text = "Your password could not be changed";

}

Note

When you modify user details such as the e-mail address, you need to use the UpdateUser method of the Membership class after modifying the details. The UpdateUser method takes the MembershipUser class object as an argument.

You can customize the membership settings, if required, by configuring the membership provider.

Configuring Membership Provider

You can configure the membership provider to customize the membership settings, such as specify the database for storing the user credentials and change the default password policy. To configure the membership provider, you need to add the element to the web.config file. All the custom settings are defined inside the element as shown in the following example:

name="CustomMembershipProvider"

type="System.Web.Security.SqlMembershipProvider"

connectionStringName="MySqlServer"

enablePasswordRetrieval="true"

enablePasswordReset="true"

requiresQuestionAndAnswer="true"

minRequiredPasswordLength="5"

minRequiredNonalphanumericCharacters="0"

passwordFormat="Hashed"/>

In the preceding example, the membership provider is configured. The element in the preceding example contains the following attributes:

 Name: Specifies a name for the membership provider. It is mandatory.  type: Specifies the type of membership provider. It is mandatory.  connectionStringName: Specifies the name of the connection string setting. The name must correspond to the connection string defined in the section. It is mandatory.  enablePasswordRetrieval: Determines whether a password can be retrieved in case the user forgets it.  enablePasswordReset: Determines whether a password can be reset.  requiresQuestionAndAnswer: Determines whether the membership security answer will be required when requesting or resetting the password. It is optional.  minRequiredPasswordLength: Specifies the minimum length of a password.  minRequiredNonalphanumericCharacters: Specifies minimum number of nonalphanumeric characters that the password should contain. It is optional.  passwordFormat: Specifies the way passwords are stored in the database. The values that this attribute can hold are Clear, Encypted, and Hashed. Configuring Authorization

Authorization is the process of verifying whether an authenticated user has the privilege to access a requested resource. After creating users that can access your Web application by using the membership management service, you need to specify authorization rules for the users.

You need to grant different permissions to different users to provide accessibility to the Web pages on your website. For example, on an online shopping website, the users are able to view the product catalog. They cannot make changes to the products being displayed on the website. However, the administrator of the website can add or remove any product from the website. This requires providing different levels of permission to different users of the website.

Maintaining a different set of settings for each user is a complex task. Therefore, the users are assembled into groups called roles and the permissions are defined on these roles. In ASP.Net, you can provide authorization by using the role management service. The role management service enables you to create roles, assign users to each role, and then restrict user access based on these roles.

To use role-based authorization in your Web application, you need to enable it by using the element in the web.config file, as shown in the following markup:

...

...

In the preceding markup, setting the value of the enabled attribute to true will enable role- based authorization for the Web application.

Creating and Assigning Roles

After you have enabled the role management service, you need to create roles, such as Users, Administrator, and Guest. You can then assign users to one or more roles.

ASP.NET provides you with the Roles class to help you create roles. The Roles class contains a number of methods that help you modify role information. The following table lists the various methods of the Roles class and their description.

Methos Description

CreateRole Adds a new role to the data source.

DeleteCookie Deletes the cookie where role names are cached.

DeleteRole Removes a role from the data source.

FindUsersInRole Gets a list of users in a specified role where the user name contains the specified user name to match.

GetRolesForUser Gets a list of the roles that has been assigned to a user.

Methods of the Role Class

You can create roles by using the CreateRole method as shown in the following code snippet:

Roles.CreateRole(“Admin”);

In the preceding code snippet, the role Admin is created.

You can add a user to a role by using the AddUserToRole method as shown in the following code snippet:

Roles.AddUserToRole(“Peter”, “Admin”);

In the preceding code snippet, the user Peter is added to the Admin role. You can get a list of all the users in a particular role. For this you need to write the code as shown in the following example: protected void Button1_Click(object sender, EventArgs e)

{

MembershipUserCollection users = Membership.GetAllUsers();

foreach (MembershipUser MyUser in users)

{

if (Roles.IsUserInRole(MyUser.UserName, "Manager"))

{

Label1.Text += MyUser.UserName + "
";

}

}

}

In the preceding example, all the users are retrieved and the names of those users who have assigned the Manager role are displayed on the label control.

Restricting User Access

Once you have created and assigned users to roles, you can restrict the access of users. You can specify the list of users who are allowed to access a website in the element. The element is specified in the web.config file. The element includes two child elements, and . You can specify the list of users who are allowed to access the website in the element and the list of users who should not be allowed to access the website in the element.

Some attributes of the and elements are:

 users: It enables you to assign a list of users to be granted or denied access. The symbol ? is used to denote anonymous users and the symbol * is used to denote all users.  roles: It enables you to assign a list of roles to be granted or denied access.

A Web application contains certain Web pages that can be accessed only by specific users. For example, there are certain Web pages that should be accessed only by the administrator. For restricting access to such Web pages, these Web pages need to be stored in a separate subdirectory. After storing the Web pages in the subdirectory, you need to add a Web.config file to that subdirectory. Then, you need to use the following markup in the web.config file to restrict users having roles other than Admin to access the Web pages:

The preceding markup specifies that the users who have been assigned to the Admin role are allowed to access the Web pages stored in the subdirectory. All users having roles other than the Admin role are denied access on these Web pages. Configuring Impersonation

When a user requests an ASP.NET application, the request goes to IIS. IIS authenticates the user and forwards the request to ASP.NET. If ASP.NET impersonation is disabled, irrespective of the user who has logged on, the ASP.NET application will be executed by using a fixed machine-specific account. In Windows XP, this account is automatically created by ASP.NET and is named as ASPNET.

The ASPNET account has permissions such as code compilation and viewing information in any database or files in your application that you would not want to grant to a user. For example, if a user visits the current account page, you need to make sure that the user is able to view the information only for his\her account. To allow users to access the ASP.NET application according to the permissions granted to them, you need to use impersonation.

Impersonation is the process of executing code under the authenticated user identity and not under the ASPNET account. When a user tries to access a Web application, the first step is to check whether impersonation is enabled for the application.

Impersonation involves the following steps:

1. When a request from a remote client is received, IIS carries out authentication. If the client is authenticated, it passes the request to the ASP.NET application. 2. The application impersonates the client and uses the authentication given by IIS to access the restricted resources. 3. If authorized to access resources, the ASP.NET application returns the requested resources to the client through IIS.

By default, impersonation is disabled in ASP.NET and unless overridden, all applications inherit this setting. When impersonation is disabled, the account used for executing ASP.NET resources is controlled by the element in the machine.config file. However, you can enable impersonation in an ASP.NET application by adding the following markup in the section of the web.config file:

In the preceding markup, impersonation is enabled for the Web application. Therefore, the application uses the user credentials authenticated by IIS to provide access to the requested resources.

You can also enable your Web application to run under a specific user’s identity. For this, you need to specify the user credentials for that specific user in the web.config file, as shown in the following markup:

In the preceding markup, impersonation defines a single specific user account, user1. Therefore, no matter which user accesses the application, all the Web requests will be granted access according to the permissions of the user1 account.

Summary

In this chapter, you learned that:

 The ASP.NET security model provides restricted levels of access to secure website information from unauthorized access.  IIS provides the following different types of authentication to control access to your Web application: o Anonymous o Basic o Digest o Integrated Windows  Authentication is the process of validating the identity of a user before granting access to a restricted resource.  Authentication in a Web application can be configured by using the element in the web.config file.  Authorization is the process of verifying whether an authenticated user has the privilege to access a requested resource.  Impersonation is the process of executing code under the authenticated user identity and not under the ASPNET account.

Reference Reading

Identifying the ASP.NET Security Process Reference Reading: Books Reference Reading: URLs

Pro ASP.NET 3.5 in C# http://msdn.microsoft.com/en-us/magazine/cc301387.aspx 2008 by Matthew http://www.springerlink.com/content/q6w220jt19065733/ MacDonald, Mario Szpuszta

Chapter 13 Deploying an ASP.NET Application

After creating a Web application, you need to make it available to the users to enable them to access the application through the Internet. To make a Web application available to the users, you need to deploy it on a Web server.

This chapter explains how to configure a Web server for deploying a Web application. In addition, it discusses about how to deploy a Web application. Objectives

In this chapter, you will learn to:

Configure a Web server for deployment

Deploy a Web application Configuring a Web Server for Deployment

Web servers accept requests from Web browsers and respond accordingly. To enable a Web server to respond to a browser, you need to configure it. The configuration of a Web server involves performing the following tasks:

1. Creating a virtual directory 2. Defining Web application URLs 3. Registering ASP.NET file mappings The Virtual Directory

During the development phase, a Web application is saved in a folder on the computer on which it is developed. However, once the application is developed, it needs to be deployed on a Web server. When you deploy the application on a Web server such as IIS, you need to create a directory on the Web server that contains all the components such as the Web pages, images, user controls, and data source files of your application. This directory is known as a virtual directory.

A virtual directory is created so that the user does not get direct access to the Web application folder residing on the host computer. This helps in maintaining the security of the Web application and the host computer because a remote user or a client cannot manipulate any data.

A virtual directory exposes the components of a Web application to the remote clients and allows them to access your Web application through Web browsers. When a client requests a Web page in a virtual directory, the Web server searches the page in the corresponding physical directory that exists on the host computer. After locating the page, the server sends it back to the client.

For example, your Web application exists in a directory named D:\MusicMania on the host computer. To allow remote users to access the application through their browsers, you need to deploy it on a Web server as a virtual directory. The virtual directory can either have the same name as the name of the Web application or a different name. When the user requests a page in a virtual directory, for example, http://172.23.3.203/MusicMania/AboutUs.aspx, the Web server searches for the file in the corresponding physical directory, D:\MusicMania\ AboutUs.aspx and renders it to the user.

Configuring Application Pools

After creating the virtual directory, you can configure the application pool for your application. An Application pool can contain one or more applications and allows you to configure the level of isolation between different Web applications. For example, if you want to isolate your Web applications running on the same computer, you need to create a separate application pool for every Web application and place the applications in the corresponding application pool. When the applications are placed in separate application pools, errors in one application pool will not affect the applications running in other application pools.

You can configure application pools for your Web applications by using the IIS manager. For this, you need to right-click the virtual directory that is created for the Web application and select the Properties option. You can set the isolation for your application by selecting the appropriate option from the Application Protection drop-down list, as shown in the following figure.

The Virtual Directory Properties Dialog Box

The Properties dialog box provides the following application protection options:

 Low (IIS Process): The applications that are configured to run under this application protection run in Inetinfo.exe. The Inetinfo.exe hosts IIS core processes. Therefore, if the application fails, it might stop the functioning of the Web server.  Medium (Pooled): The applications that are configured to run under this application protection share an instance of dllhost.exe and do not run in Inetinfo.exe. If the applications fail, the Web server does not get affected. However, other application running under this application protection share may get affected. It is the default option.  High (Isolated): The applications that are configured to run under this application protection are isolated from both the Inetinfo.exe and dllhost.exe. Therefore, if the application fails, it will not affect any other application or the Web server. Web Application URLs

Users access a Web application by using an easy-to-remember address in the address bar of a Web browser. This easy-to-remember address is known as the Uniform Resource Locator (URL). A URL is the location of a file on the Web. It is unique for every application. To access a Web application, users type the URL for that application in the address bar of a Web browser. The Web browser sends this request to the Web server. The Web server searches for the application mapped to that URL and sends it back to the browser.

Consider a scenario where an airline company sells airline tickets through their Web application. The passengers can book their tickets, check the booking status, and see the flight schedules through the airline website. Users can access the website by using the following URL: http://172.23.3.203/MyWebApp/default.aspx

In the preceding URL, 172.23.3.203 is the IP address of the Web server and MyWebApp is the virtual directory residing on the Web server. To access the Web application through its IP address, users need to remember the IP address. However, it is difficult to remember IP addresses. Therefore, instead of using an IP address, Web applications are accessed by using a unique name known as the domain name. For example, the airlines’ Web application can be accessed by using the domain name, as specified in the following URL: http://www.MyFlight.com/MyWebApp/default.aspx

In the preceding statement, www.MyFlight.com is the domain name for the airline website.

Note

IP address is a unique 32-bit number and is typically written as four numbers in the range of 0 to 255 separated by periods (as in 172.23.3.203).

Note

A domain name is the address that is used by users to access a Web application. A domain name is registered by companies so that it can be used by its users to access the company’s website. Registering ASP.NET File Mappings

When multiple versions of .NET Framework are installed on the same computer, each version installs an ASP.NET Internet Server Application Programming Interface (ISAPI) extension version associated with it. This extension version determines which version of the Common Language Runtime (CLR) will be used by a particular Web application. A Web application can be configured to use any version of the .NET Framework that is installed on the computer. To configure a Web application to use a particular version, you need to register a script map in the Internet Information Services (IIS). A script map is a path to the ASP.NET ISAPI version used by the application. It associates a file extension and HTTP verb with the appropriate ISAPI for script handling.

When a user requests for a particular Web page, the script map for the application directs IIS to forward the requested file to the ASP.NET ISAPI for processing. Therefore, when you need to use a particular version of the .NET Framework, you need to update the script maps so that they direct the request for a Web page to the appropriate version of the ASP.NET ISAPI.

To update the script map, you need to use the ASP.NET registration tool called aspnet_regiis.exe, as shown in the following figure.

Note

The aspnet_regiis command can be used with several options. You can check all the available options by typing aspnet_regiis/? at the command prompt. Deploying a Web Application

In today’s scenario, the Internet is the best and the most used medium for getting information on any topic. The information, available on the Internet, is contained in different Web applications. To enable users to access the information contained in Web applications, these applications need to be installed on a Web server. The process of installing a Web application on a Web server is known as deployment.

The most basic technique for deployment is to copy the application components to the hard drive of the Web server. In this technique, the various application components are deployed to the Web server in their un-compiled form. This type of deployment has the following issues:

 The application is deployed even if it contains compilation errors.  The source code of the application is exposed.  The application loads slowly initially because it is compiled when it is accessed for the first time.

These problems can be resolved by precompiling an application before deploying it to a Web server. Precompiling a Web Application

Precompiling a Web application involves compilation of the source code into DLL assemblies before deployment. Precompiling a Web application provides the following advantages:

 It provides faster response time because the Web application does not need to be compiled the first time it is accessed.  It helps in identifying the bugs that can occur when a Web page is requested. These bugs are rectified at the time of compiling the Web application. Then, the compiled and error-free Web application is deployed on to the server and is rendered to a user.  It hides and secures the source code of a Web application from the users accessing the application.

You can precompile a Web application by using the aspnet_compiler.exe command-line tool. This tool compiles source files such as Web pages, user controls, resources, and utility classes into assemblies and creates output in the form of an executable version of the application. The compiler removes all source and markup from the output. The output consists of the compiled files of each of the .aspx file with the .compiled extension. These compiled files contain pointers to the appropriate assembly for that page. Assemblies are the .dll files that contain the compiled version of .aspx.cs file.

Note

All source code on an ASP.NET Web form is dynamically compiled into intermediate language. When the intermediate language code is executed on a machine it gets compiled just-in-time (JIT) into native machine code and then executes.

To compile a website, you need to execute the aspnet_complier command, as shown in the following figure.

Using the aspnet_compiler Tool

In the preceding example, the path, E:\MyWebSite specifies the physical directory containing the source code, and the path, E:\TargetSite specifies the location where the compiled project needs to be saved.

The following table lists some options that can be used with aspnet_compiler.exe tool.

Option Description -v Specifies the virtual path of the application to be compiled. For example, if the application is hosted in the virtual directory, MyWebApp, the virtual path can be specified as /MyWebApp. If the application to be compiled is not stored in a virtual path, the -v parameter can specify / as the virtual directory. -p Specifies the physical path of the application to be compiled. -u Specifies that aspnet_compiler.exe should create a precompiled application that allows subsequent updates of contents such as .aspx pages.

If this option is omitted, the resulting application contains only compiled files and cannot be updated on the deployment server. You can update the application only by changing the source markup files and recompiling. -c Specifies that the application to be compiled should be fully rebuilt. Components that have already been compiled are compiled again. If this option is omitted, the tool builds only those parts of the application that have been modified since compilation was last performed.

Options Used with aspnet_compiler.exe Managing ASP.NET Precompiled Output for Deployment

The compilation tool of ASP.NET, aspnet_compiler.exe, compiles the source files and creates separate assemblies for each source file. These assemblies are then combined and managed by using the ASP.NET merge tool, aspnet_merge.exe. The ASP.NET merge tool merges all the assemblies produced by the compilation tool to create a single assembly for the entire application. The merged assembly helps in making the deployment process fairly simple.

The ASP.NET merge tool can be used to combine:

 All assemblies on a precompiled website into a single assembly.  All Web user interface content assemblies into a single assembly.  All Web user interface content assemblies into an assembly for each folder on the website.

When you use the aspnet_merge tool, without any options, and only specify the target folder name, as shown in the following figure, output assemblies are created for each Web user interface content folder.

Using the aspnet_merge Tool Without Specifying any Option

To create a single assembly that combines all Web user interface content assemblies, you need to use the -w switch with the aspnet_merge tool and specify a name for the merged assembly, as shown in the following figure.

Using the aspnet_merge Tool with the -w Switch To create a single assembly that combines all assemblies on a precompiled website, you need to use the -o switch with the aspnet_merge tool and specify a name for the merged assembly, as shown in the following figure.

Using the aspnet_merge Tool with the -o Switch

Summary

In this chapter, you learned that:

 The configuration of a Web server involves performing the following tasks: o Creating a virtual directory o Defining Web application URLs o Registering ASP.NET file mappings  A virtual directory is created so that the user does not get direct access to the Web application folder residing on the host computer.  A virtual directory exposes the components of a Web application to the remote clients and allows them to access your Web application through Web browsers.  An Application pool can contain one or more applications and allows you to configure the level of isolation between different Web applications.  A URL is the location of a file on the Web. It is unique for every application.  Precompilation involves compilation of the source code of the Web application into DLL assemblies before deployment. Precompiling a Web application provides the following advantages: o It provides faster response time because the Web application does not need to be compiled the first time it is accessed. o It helps in identifying the bugs that can occur when a Web page is requested. These bugs are rectified at the time of compiling the Web application. Then, the compiled and error-free Web application is deployed on to the server and is rendered to a user. o It hides and secures the source code of a Web application from the users accessing the application.  The compilation tool of ASP.NET, aspnet_compiler.exe, compiles the source files and creates separate assemblies for each source file.

Reference Reading

Configuring a Web Server for Deployment

Reference Reading: Reference Reading: URLs Books

Beginning ASP.NET 3.5: http://msdn.microsoft.com/en-us/library/aa244279(VS.60).aspx In C# and VB by Imar Spaanjaars

Deploying a Web Application

Reference Reading: Reference Reading: URLs Books

ASP.NET 3.5 For http://e-docs.bea.com/wls/docs81/webapp/deployment.html Dummies by Ken Cox http://www.beansoftware.com/ASP.NET-Tutorials/Deploy- ASP.NET.aspx

Chapter 14 Tracing and Monitoring Web Applications

After you have deployed a Web application, you need to make sure that it is running properly. The errors occurring while the application is running need to be diagnosed and fixed. You also need to ensure that there are not any performance related issues with your Web application.

ASP.NET provides you with the tracing and health monitoring features that can be used to troubleshoot and diagnose problems with your Web application. By using these features, you can constantly monitor the application while it is running for any issues that could affect its performance.

This chapter discusses how to implement tracing in Web applications. In addition, it discusses how to monitor the health and performance of Web applications. Objectives

In this chapter, you will learn to:

Implement tracing in Web applications

Monitor Web applications Implementing Tracing in Web Applications

As a developer, you are focused on creating a Web application that runs smoothly after its deployment. Once an application is deployed, you need to ensure that the application is working properly and is not giving unexpected results. For this, you need to keep track of the execution of your Web application. This will enable you to track any errors or performance- related issues in your application.

ASP.NET provides you with the tracing feature that enables you to track the program execution, thereby ensuring that your Web application runs properly. You can use this feature to view diagnostic information about a particular Web page. This information includes the execution time of page methods, the time spent rendering page controls, and the contents of various collections, such as the query string, HTTP header, and session state.

In addition to the standard diagnostic information, tracing can also be used to display custom tracing information about the execution of an application. Tracing information can also be written to an event log or a text file by using trace listeners. Implementing Tracing Tracing can be implemented at any of the following levels:

 Page Level  Application Level

Page-Level Tracing

Page-level tracing is used to generate diagnostic information at the end of page rendering. This diagnostic information includes all the information about the requests made to the page and their responses. This information is used to diagnose problems on the page. For example, suppose the processing of your Web page is taking too long. You can use the trace information to check which of the Web page methods or events are taking too long to execute. Once you are able to determine the reason for delayed processing of your Web page, you can easily resolve the problem.

To enable page-level tracing, you need to perform the following steps:

1. Include the following directive at the top of the page: <%@ Page Trace="True" %> 2. Include the TraceMode attribute in the @ Page directive to specify the sort order for your trace messages. You can sort the trace messages either by time or category. For example, you can sort the trace messages on the basis of category, as shown in the following code snippet: <%@ Page Language="C#" Trace="True" TraceMode="SortByCategory" %>

If you enable tracing on a Web page of your Web application, the tracing information is displayed at the end of the Web page, as shown in the following figure.

The Tracing Information of a Web Page

The following information is displayed when page-level tracing is enabled:

 Request Details: It displays some basic information, such as current session ID, the time when the request for the Web page was made, the request and response encodings, the request type, and the return status code.  Trace Information: It displays performance-related information about the Web page life-cycle events. The events are displayed under the Message column. The Category column displays the category of the message. The From First(s) column displays the running time from the instant when the page request started. The From Last(s) column shows the elapsed time since the previous event. You can use this information to determine which of the Web page events are taking too long to execute.  Control Tree: It displays information about each control on the Web page, such as the size of the rendered controls. You can use this information to be aware of the number of bytes that each control on the Web page uses. This will help you keep a check on the overall weight of the Web page.  Session State: It displays information about all the session variables, their types, and values.  Application State: It displays information about all the application variables, their types, and values.  Request Cookies Collection: It displays information about all the cookies that were sent by the Web browser with the request for this Web page.  Response Cookies Collection: It displays information about all the cookies that were returned by the Web server with the response.  Headers Collection: It displays information about all the headers that are sent to the Web server as part of the request from the Web browser. It includes information about the browser making the request, the types of content it supports, and the language it uses.  Response Headers Collection: It displays information about all the headers that are sent to the client as part of a response from the Web server. It includes details such as the version of ASP.NET and the type of content being sent (text/html for Web pages).  Form Collection: It displays the list of values that are posted back to the Web server. It includes all the values that are submitted by Web controls, such as hidden field values, the text in a textbox, and the current selection in a list box.  Querystring Collection: It displays the list of values included in the query string. You can also view this information in the Web page URL. However, if the query string contains a lot of information, it is easier to review the individual items in the trace display.  Server Variables: It displays all the server variables and their values at the time of Web page request.

Application-Level Tracing

When you enable tracing at the page-level, the tracing information is displayed at the end of the Web page. As a result, every visitor to the website will see the tracing output at the bottom of the Web page. This is not a good approach to display Web pages on a website. To view the tracing output for all the Web pages on the website, you need to enable tracing for every Web page if you are using page-level tracing. These limitations can be overcome by enabling tracing for the entire Web application.

Application-level tracing is used to trace information for every Web page in a Web application. A special page named trace.axd is used to view this trace information. This page should ideally be accessible to the website administrator only. To use the trace.axd page, you have to first enable application-level tracing within the Web.config file for your application. You can use the following attributes of the element to change the tracing settings of your website:

 enabled: Indicates whether tracing is enabled for the application. The default value is false.  requestLimit: Stores tracing information for a maximum number of HTTP requests. The default value is 10.  pageOutput: Indicates whether trace information is displayed at the bottom of every page in the application. The default value is false.  traceMode: Indicates the order in which trace messages are displayed. The possible values are SortByTime and SortByCategory. The default value is SortByTime.  localOnly: Indicates whether the tracing information should be displayed only on the local computer (computer on which the Web application is hosted) and not on remote computers. The default value is true, which means that remote clients cannot see the tracing information.  mostRecent: Stores only the most recent trace messages if set to true. When the maximum limit specified by the requestLimit attribute is reached, the information for the oldest request is discarded every time a new request is received. If the mostRecent attribute is set to false, which is the default value, ASP.NET stops collecting new trace messages when the maximum number of requests has been received.

For example, you can make the necessary settings to enable application-level tracing in the web.config file, as shown in the following code snippet:

enabled="true"

requestLimit="100"

pageOutput="false"

traceMode="SortByTime"

localOnly="true"

mostRecent="false" />

In the preceding code snippet, the trace information will be displayed for the first 100 Web requests as specified by the requestLimit and mostRecent attributes. The trace information will be sorted by time as specified by the traceMode attribute. It is only available to the local clients as specified by the localOnly attribute.

You can open the trace.axd page in the Web browser just by replacing the page name in the URL with trace.axd, as shown in the following figure.

The Trace.axd Page

The preceding figure shows that three requests have been made to this application and the right side of the header indicates "Remaining: 97". The page displays tracing information for only three requests. Therefore, there are 97 more requests remaining before tracing stops for this application. After all the 100 requests have been made to the application, tracing data is not displayed for further requests. You need to click the "clear current trace" hyperlink on the trace.axd page to start displaying tracing data for further requests. You can click the View Details link to see the detailed information for any request. This detailed information is similar to the information that you see for a Web page when you implement page-level tracing.

Application-level tracing gathers and processes the trace information for each page in the application. If you need to disable tracing for a particular page, you have to set the Trace attribute of the @Page directive to false. The trace settings made at the application-level are overridden by the page-level settings. Writing Trace Information When a Web application is in the development stage, you often use several Response.Write statements in the program code to display debugging information. This information is used to troubleshoot the application. However, these statements need to be removed once your application is ready for deployment because the messages displayed using Response.Write statements are required for debugging and should not be displayed to an end user.

Tracing resolves this problem by allowing you to insert debugging code within an application such that the debugging code does not need to be removed at the time of deployment. This is because you can disable tracing to prevent the debug information from being displayed as trace information.

The Trace property of the Page class returns a Trace object, which can be used to write custom trace statements. The Trace object is an instance of the TraceContext class. The Trace object provides a set of methods and properties that help you trace the execution of your application.

The properties of the Trace object are:

 IsEnabled: Denotes whether tracing is enabled for the current request  TraceMode: Sets the trace modes such as sortByCategory or sortByTime

Some of the methods of the Trace object are:

 Warn: Displays the trace information in red color  Write: Displays the trace information in black color

You can use the Trace object to write custom trace statements when tracing is enabled for a page or an application. You can use the Write and Warn methods of the TraceContext class to write trace statements to the trace log. The only difference between these two methods is that the Warn method displays the statements in red while the Write method displays the statements in black color. The Write and Warn methods are overloaded methods and have three versions. These three versions differ in the number of arguments passed to them. The syntax of the overloaded methods of the Write and Warn methods are: public void [Warn | Write](String message) public void [Warn | Write](String category, String message) public void [Warn | Write](String category, String message, Exception errorInfo)

The arguments used in the preceding versions of the Write and Warn methods are:

 message: This argument refers to the message displayed in the Trace Information section.  category: This argument refers to an arbitrary string that is basically used to group similar kinds of messages. It helps sort and display the messages category-wise in the Trace Information section.  errorInfo: This argument refers to an object of the Exception class that contains the exception details associated with the request. For example, you can write the following code in the Page_Load event of your Web page: int i = 30; int j = 0; try

{

int z = i / j;

Response.Write(z);

} catch(DivideByZeroException exp)

{

Trace.Write("Errors","Testing the limits of infinity?",exp);

Response.Write("A numeric value divided by zero gives result as

infinity.");

}

In the preceding code snippet, an exception is raised in the try block. This exception is caught in the catch block. Then, a message, A numeric value divided by zero gives result as infinity, is displayed to a user. The information of the execption caught in the catch block is displayed in the Trace.axd file in the browser, as shown in the following figure.

Displaying Custom Trace Information

In the preceding figure, the trace messages are sorted and displayed as per the execution time. Therefore, the trace messages are being displayed between the Begin Load and End Load events. However, if you sort the trace messages as per the category, the tracing information is displayed in the browser, as shown in the following figure.

Sorting of Trace Information Category-Wise Using Trace Listeners

Trace listeners are used to collect, store, and route tracing messages. You can also use trace listeners to redirect the tracing information to logs, windows, or text files.

ASP.NET provides the following three types of predefined trace listeners:

 TextWriterTraceListener: Used to redirect the trace output to a file or console.  EventLogTraceListener: Used to redirect the trace output to an event log.  DefaultTraceListener: Used to redirect the trace output to OutputDebugString API function and the Debugger.Log method. To enable a trace listener, you need to add it to the Listeners collection. All the three types of trace listeners receive the same trace output when included in the Listeners collection but each of them then redirects this output to a different target.

Adding a Trace Listener

A trace listener is added in the web.config file within the tag of the trace element. The tag is a collection of all the trace listeners. To add a trace listener in the web.config file, you need to include the following code snippet in the web.config file:

type="System.Diagnostics.TextWriterTraceListener"

initializeData="D:\myListener.txt" />

In the preceding code snippet, a listener, MyListener is added to the tag. The MyListener listener writes the trace information to a file, myListener.txt. The autoflush attribute of trace element specifies whether the trace listener automatically flushes the output buffer each time it writes to a text file.

To enable ASP.NET to route tracing information to a System.Diagnostics listener, you need to include the following entry in the web.config file:

Removing a Trace Listener

To remove a trace listener from the Listeners collection, you need to include the following code snippet in the web.config file:

In the preceding code snippet, the trace listener, MyListener is removed by using the element within the element. Trace Switches

Trace switches allow you to enable, disable, and filter tracing output even after the application has been deployed on the server. This can be done by configuring the trace switches through the web.config file. The .NET Framework provides the following types of switches:

 BooleanSwitch: It is a toggle switch that allows you to enable and disable trace statements. It is useful when you want to receive only a specific set of trace statements. It offers two levels of configuration, On and Off.  TraceSwitch: It allows you to set the level from which you want to receive trace statements. By configuring TraceSwitch to the appropriate level, you can control the type of tracing output you want to receive. To use trace switches to filter the tracing output, you need to initialize and configure the trace switches.  SourceSwitch: It provides multilevel switch to control tracing and debug output without recompiling the code. It provides a Level property to test the event level of the switch. The Level property gets or sets the switch's TraceLevel value.

Initializing Trace Switches

To initialize a TraceSwitch, you need to first create its object. The following code snippet shows how you can create and initialize a TraceSwitch object:

System.Diagnostics.TraceSwitch MyTraceSwitch = new System.Diagnostics.TraceSwitch("MySwitch", "Entire application");

In the preceding code snippet, an object of TraceSwitch class is created and initialized. The System.Diagnostics.TraceSwitch class takes two parameters, name and description of trace switch. Configuring Trace Switches

You can configure a trace switch to trace a Web application at different levels. These levels enable you to trace various types of messages such as error messages, warning messages, informational messages, and detailed messages.

The following table lists the levels of the TraceLevel enumeration and their integer values.

The Levels of the TraceLevel Enumeration and Their Integer Values

You can configure a trace switch by setting it to any of the values in the TraceLevel enumeration. The following code snippet shows how you can configure a trace switch:

In the preceding code snippet, the value attribute of the switch MySwitch is set to 2 to display the warning and error messages.

Monitoring Web Applications

After deploying a Web application, you, as a system administrator, need to constantly monitor it for its proper functioning. Many unexpected problems, such as website experiencing heavy load, may occur while the application is running in the real-world environment. By monitoring a Web application, you can detect the problems occurring in the application and troubleshoot them.

Monitoring and troubleshooting is required to improve the performance of a Web application. To help you track and monitor a Web application, ASP.NET provides you with the following two features:

 Health Monitoring  Performance Monitoring Health Monitoring

ASP.NET health monitoring system enables you to monitor the status of the deployed Web applications. It is used to track system events and errors, which can hamper the performance of a Web application.

Health monitoring system enables you to get the detailed run-time information about ASP.NET resources used by a Web application. It is useful in scenarios where you want to monitor an application and be notified when a critical error occurs. For example, you can use health monitoring system to monitor events such as start and end of an application, successful and failed logons, and unhandled exceptions. If you detect any unhandled exception in your Web application, you can make appropriate changes so that it does not occur again.

The ASP.NET health monitoring system is implemented by using the System.Web.Management namespace. This namespace contains classes and interfaces for managing and monitoring the health of Web applications. This namespace includes Web events responsible for packaging health-status data of the Web application. You can capture Web events by using built-in event providers. For example, there is a provider to capture events and send e-mail notifications, a provider to log events to SQL Server, and a provider to drop events into an event log.

Configuring Health Monitoring

You can configure applications to use built-in or customized monitoring providers. These providers process the health-monitoring information and report on the health status and the performance characteristics of a Web application. To use the health monitoring system, you need to perform the following configuration jobs:

 Configure and enable Web events to be monitored.  Configure and enable event providers that listen for and process various Web events.

The following code snippet shows how you can configure health monitoring by using the element in the web.config file:

enabled="true|false"

heartbeatInterval="time interval">

...

...

...

...

...

The following table lists the attributes of the element.

Attribute Description enabled Specifies whether health monitoring is enabled. heartbeatInterval Specifies the interval, in seconds, that indicates how often the WebHeartbeatEvent event is raised.

The Attributes of the Element

The following table lists the child elements of the element.

Element Description bufferModes Specifies the buffering capabilities for a provider. eventMappings Maps friendly event names to the related event types. profiles Defines a collection of parameter sets to use when configuring events. providers Defines the health monitoring providers that process events. rules Maps events to providers.

The Child Elements of the Element

Web Events

Web events contain information about the health of a Web application. These events need to be trapped to report the status of the application’s health. Each Web event is defined by a class. When a Web event is raised, an instance of the associated event class is created. This instance stores the event data, which is processed by the event providers.

There are several events that you can trap to monitor the health of a Web application. Some of the important events are:

 WebBaseEvent: It acts as a base class for all the other Web events.  WebBaseErrorEvent: It acts as a base class for all Web events related to errors in the system.  WebHeartbeatEvent: It records Web events after a predefined interval of time.  WebRequestEvent: It occurs when a user sends a request to a Web server.  WebErrorEvent: It represents the errors that occurred at the configuration or compilation time.  WebApplicationLifetimeEvent: It is raised when an application starts or stops.  WebRequestErrorEvent: It is raised when any unhandled exception occurs or an error related to a user’s request is generated.  WebAuditEvent: It represents a base class for Web events that are raised when a user attempts to log on.  WebSuccessAuditEvent: It is raised when a logon attempt by a user is successful.  WebFailureAuditEvent: It is raised when a logon attempt by a user fails.

You need to enable the Web events by connecting them to the event providers.

Event Providers

The event providers are used to listen for Web events that are raised by a Web application. These providers process the event information either by logging the information or by notifying the system administrator. ASP.NET provides you with several built-in event providers that you can use to capture Web events raised by the Web application. Some of the built-in providers are:

 EventLogWebEventProvider: It logs Web events in the Windows event log.  SqlWebEventProvider: It is a Web event provider for SQL Server databases. It logs Web events in the SQL Server and the SQL Server Express databases.  SimpleMailWebEventProvider and TemplatedMailWebEventProvider: These providers respond to Web events by sending an e-mail message.  TraceWebEventProvider: It sends Web events to the diagnostics trace.  WmiWebEventProvider: It sends Web events to the Management Instrumentation (WMI) subsystem. The following example shows how to use the EventLogWebEventProvider in the web.config file to log Web events in the Windows event log:

provider="EventLogProvider" profile="Default"

minInterval="00:02:00"/>

In the preceding example, a child element is created under the element of the web.config file. Then, a rule, Default Success Audits, is created to handle success audit events. Performance Monitoring

Performance is an important factor in making a Web application or project successful. You need to monitor a Web application to troubleshoot any performance-related issues. For example, a user request may not be processed because of insufficient server resources. You need to keep track of such errors to improve the performance of your Web application.

ASP.NET provides you with several performance counters, such as Application Restarts, Requests Queued, and Errors Total to help you keep track of the execution of your Web application. These performance counters are valuable in determining the performance-related problems in Web applications.

For example, you can determine the number of requests that are in queue for your Web application. A large number of Web requests in the queue may indicate that the application is not efficient enough and needs to be tuned. By monitoring the Requests Queued performance counter, you can track the number of requests waiting for service in the queue. If it is affecting the performance of the application, you can make the necessary changes in the configuration file of the application to improve its performance. You can use the System Monitor (PerfMon) with ASP.NET applications to track the performance counters affecting the performance of applications.

Performance Counters for ASP.NET

ASP.NET supports the following groups of performance counters:

 System performance counters  Application performance counters System Performance Counters

System performance counters are displayed in the Windows Performance monitor in the form of the ASP.NET performance counter object.

The following table lists some of the system performance counters.

System Performance Counter Description

Application Running Represents the number of applications running simultaneously on a Web server.

Requests Disconnected Represents the number of requests that have been disconnected due to communication failure.

Request Wait Time Represents the number of milliseconds that the most recent request waited in the queue for being processed by the server.

State Server Sessions Active Represents the number of user sessions that have become inactive because of some user action. This counter is available only on the computer where the state server service, aspnet_state is running.

Worker Process Running Represents the number of worker processes running on a Web server.

The System Performance Counters

Application Performance Counters

Application performance counters are displayed as the ASP.NET application performance object. These counters enable you to monitor the performance of a single instance of an ASP.NET Web application.

A unique instance of each ASP.NET application collects all the counters of each application. These counters will display a value of zero when no application is running on a Web server.

The following table lists some of the application performance counters.

Application Performance Counter Description Anonymous Requests Represents the number of requests that are using anonymous authentication.

Anonymous Requests/Sec Represents the number of requests per second that are using anonymous authentication.

Cache Total Entries Represents the total number of entries in the cache.

Cache Total Hits Represents the total number of hits from the cache.

Debugging Requests Represents the number of requests that occur while debugging is enabled.

The Application Performance Counters

Summary

In this chapter, you learned that:

 Tracing can be implemented at any of the following levels: o Page Level o Application Level  The properties of the Trace object are: o IsEnabled o TraceMode  Some of the methods of the Trace object are: o Warn o Write  ASP.NET provides three types of predefined trace listeners: o TextWriterTraceListener o EventLogTraceListener o DefaultTraceListener  ASP.NET provides you with the following features for monitoring a Web application: o Health Monitoring o Performance Monitoring  ASP.NET supports the following groups of performance counters: o System performance counters o Application performance counters

Reference Reading

Monitoring Web Applications

Reference Reading: Books Reference Reading: URLs

Pro ASP.NET 3.5 in C# http://www.mail- 2008 by Matthew archive.com/[email protected]/msg15921.html MacDonald, Mario Szpuszta http://www.ajaxline.com/health-monitoring-in-asp-net-3-5

Chapter 15 Creating Web Applications for Mobile Devices

Web applications enable users to access information on a 24x7 basis. Users may need to access Web applications even while they are on the move. This is possible by using mobile devices such as PDAs and cellular phones. However, accessing information by using such devices requires you to make the Web pages available in a format that can be viewed on mobile devices. ASP.NET allows you to create Web applications having Web pages that can run on a variety of mobile devices.

This chapter discusses about how to create mobile Web pages. In addition, it discusses about rendering content on mobile Web pages. Objectives

In this chapter, you will learn to:

Create mobile Web pages

Render content on mobile Web pages Creating Mobile Web Pages

Mobile devices have many limitations such as small display area and low bandwidth. Due to these limitations, a Web page created for desktop browsers cannot be properly displayed on mobile devices. For example, you can create a Web page that contains a header, a navigation bar at the left side of the page, and content in the rest of the page. This Web page can be rendered on desktop browsers. However, this layout of the Web page may not be suitable for mobile device browsers because mobile devices have a smaller display area than desktop monitors. Therefore, you need to create specifically designed Web pages for mobile devices.

ASP.NET provides you with the System.Web.Mobile namespace that is used specifically for mobile Web development. The System.Web.Mobile namespace contains the core capabilities such as authentication and error handling, required for building ASP.NET mobile Web applications. Working with Mobile Web Controls

ASP.NET provides you with mobile Web controls that can be used to create a mobile Web page. Some of these controls are similar to the controls used for creating Web pages for desktop browsers. The ASP.NET mobile Web controls are contained in the System.Web.UI.MobileControls namespace that provides the user interface elements for rendering mobile Web applications. Most of the mobile Web controls are similar to the normal Web server controls. However, there are some specific controls that are specific to the mobile Web pages. These controls are:

 Form  Command  PhoneCall  List and ObjectList  DeviceSpecific  SelectionList  StyleSheet  TextView

Form Control

Mobile devices have small display areas. Therefore, it is difficult to display complex Web pages, containing multiple controls, on a mobile device. To display such complex Web pages on a mobile device, you can break these pages into a collection of forms by using the Form control. A Form control is a container control that provides the capability to group controls together. Each Form control can hold a group of logically related controls. These Form controls can be displayed by setting the ActiveForm property of the Web page, as shown in the following example:

runat="server" />

OnClick="Button1_Click" />

runat="server" />

protected void Button1_Click(object sender, EventArgs e)

{

this.ActiveForm=Form2; //Form2 is the name of the Form control

}

In the preceding example, when the application starts, the default form control Form1 is displayed. When the user clicks the Button1 button control in the Form1 control, the Form2 Form control is displayed.

ASP.NET Web pages can contain more than one Form controls. However, a mobile Web application can display only one Form control at a time. When a user browses a mobile Web page, by default, the first form appears on the page.

Note

A mobile Web page must contain at least one Form control. Form controls cannot be nested.

Command Control

The Command control is similar to the Button Web server control. It combines the functionality of the normal Button, ImageButton, and LinkButton controls. The Command control can be added to a mobile page by using the element, as shown in the following example:

In the preceding example, a Command control, Button1, is added to a Form control. The Text property of the Command control is set to Click Me and the event handler Button1_Click is attached with the Click event of the Command button.

PhoneCall Control

A PhoneCall control is used to enable applications to initiate telephone calls if the user's mobile device supports that capability. If the mobile supports the capability, the phone number specified by using PhoneNumber property of the PhoneCall Control is displayed as hyperlink, selecting which a user can initiate a telephone call.

However, if the mobile device does not support the capability of placing phone calls, the PhoneCall control displays the phone number as text. The PhoneCall control can be added to a mobile page by using the element, as shown in the following example:

In the preceding example, a PhoneCall control with the PhoneNumber property set to 9999037202 is added to a Form control.

To use a PhoneCall control, you need to add the control onto a Form or Panel control or inside a control's template on an ASP.NET mobile Web page. After adding the control, you need to specify the Text and the PhoneNumber properties. You can optionally use the AlternateUrl property, which is set to the URL of the page that the application will navigate to when running on devices that cannot initiate phone calls.

Note

The PhoneNumber property must be set, to use the PhoneCall control. If the PhoneNumber property is not set, the application will throw an error.

List and ObjectList Controls

Mobile Web controls do not include the DataList and Repeater controls. Instead of these controls, the mobile Web controls include the List control. The List control includes the functionality that is provided by the DataList and Repeater controls. The List control can be added to a mobile page by using the > element, as shown in the following example:

In the preceding example, a List control, List1, is added to a form control. The list control has three items.

Similarly, in place of the DataGrid control, the mobile Web controls include the ObjectList control. The ObjectList control includes the functionality that is provided by the DataGrid control. The ObjectList control can be added to a mobile page by using the > element, as shown in the following example:

The following code nippet binds the ObjectList control with a dataset:

ObjectList1.DataSource = ds;

ObjectList1.DataBind();

DeviceSpecific Control

The DeviceSpecific control is used to specify a choice among multiple content alternatives. The DeviceSpecific control allows you to specify one or more choices, each containing attributes that specify how to evaluate the choice against target device capabilities. During run time, each choice specified in the DeviceSpecific control is evaluated in order, and the first choice that is successfully evaluated is used.

The DeviceSpecific control is used to specify template sets and override properties. For example, you can use the DeviceSpecific control to specify device-specific images for the Image control, as shown in the following example:

In the preceding example, if the device is colored as specified by the isColor value of the Filter attribute, the colorImg.gif image will be displayed. For WML device, myImage.wbmp image will be displayed.

SelectionList Control The SelectionList control provides different visual representations for a list of selectable items. It combines the functionality of the CheckBox, CheckBoxList, DropDownList, ListBox, RadioButton, and the RadioButton Web server controls. You can use the SelectType property of the SelectionList control to define the type of selection list button to render.

For example, if you set the SelectType property of the SelectionList control to CheckBox, the item passed to the control as the value of its DataSource property are displayed as check boxes. You can set the SelectType property of the SelectionList control as shown in the following code snippet:

SelectionList sl = new SelectionList(); sl.SelectType = ListSelectType.DropDown;

StyleSheet Control

The StyleSheet control enables you to use styles in the ASP.NET mobile Web Forms. It has no visual representation. The StyleSheet control can only be attached to ASP.NET mobile Web forms or to mobile user controls. There can be only one style sheet for a page or a control.

Each style sheet can contain one or more styles. A control can use the styles defined in the StyleSheet control by using the StyleReference property. The following example shows how to define styles by using the StyleSheet control:

Font-Size="Large"/>

Font-Size="Normal"/>

The preceding example defines two styles, Style1 and Style2. To use these styles for a control, you need to set the StyleReference property of the control as shown in the following example:

Label1.StyleReference = "Style1";

TextView Control

The TextView control is used to display large quantities of text. The TextView control supports device filters for overriding property values. This enables the TextView control to customize its appearance according to the capabilities of the device on which it is rendered. The TextView control can be added to a mobile page by using the element, as shown in the following example: Working with Device Emulators

After developing a mobile Web application, you need to test it on a mobile device. Although, you can test the mobile Web application in a standard Web browser, it will not give a realistic view of how the application would appear on a mobile device. To have a realistic view of the mobile Web application, you can use device emulators. Device emulators are software programs that simulate the environment of a cell phone or Personal Digital Assistant (PDA) on the desktop of your computer. Device emulators are treated as virtual mobile devices.

Device emulators for most mobile devices are available to simulate the behavior of the hardware and browsers of the mobiles. These emulators allow you to view mobile Web forms as they would appear on the actual mobile devices. They enable you test your mobile Web applications before deploying.

Rendering Content on Mobile Web Pages

There are various mobile devices available in the market. These devices have different capabilities and they differ from each other in terms of screen size, color combination, browser type, and many other features. Due to these differences, a Web control is rendered differently on different mobile devices. Therefore, if you want to create a Web application that can run on multiple mobile devices, you need to create a separate user interface for each device. It is a tedious and complex task. This task can be simplified by using control adapters and device filters provided by ASP.NET. Implementing Control Adapters

Mobile devices have different screen sizes and capabilities. When a mobile device requests a Web page, the server first checks the capabilities of the browser that has made the request. Based on the browser capabilities, the controls are rendered on the Web page. For example, consider that a mobile device requests for a Web page that displays a calendar control. Since a mobile device does not have enough space on the screen, the calendar control is rendered as a hyperlink, as shown in the following figure.

Rendering of a Calendar Control on a Mobile Device

When a user clicks the Calendar hyperlink, a menu appears. This menu prompts the users to enter a date. However, if the request for the same Web page comes from Internet Explorer, the Calendar control is rendered as shown in the following figure.

Rendering of a Calendar Control on Internet Explorer

This type of browser-based rendering of controls is known as adaptive rendering and can be implemented by using control adapters.

A control adapter is used for device-specific rendering of mobile Web controls instead of using the control's default rendering logic. To customize the behavior of Web controls, you need to specify an object of the ControlAdapter class. The ControlAdapter class is an abstract class that defines the basic functionality for all adapters. It overrides certain methods and events of the Control class to allow browser or markup-specific handling.

When a control is rendered on a Web page, the Control base class first checks whether a control adapter is currently associated with the control. If an adapter is associated with the control, the Render() method of the adapter is invoked. Otherwise, the standard Render() method of the control is invoked. You need to map the mobile Web control with its adapter through the browser definition files. The browser definition files have a .browser extension. It contains information about the browser capabilities. ASP.NET uses the .browser files to determine the capabilities of the browser, and to decide how to render markup to that browser.

The browser definition file, in addition to the mapping control adapters, is used to populate the HttpBrowserCapabilities class. This class contains information about the capabilities of the browser, such as name, type, and version of the browser. You can determine the capabilities of the browser by accessing the HttpBrowserCapabilities class through the Request.Browser property.

The following table lists some commonly used Request.Browser properties with their description.

Property Description Request.Browser.Browser Gets the name of the browser Request.Browser.Version Gets the full version number of the browser as string Request.Browser.Type Gets the name and major version number of the browser Request.Browser.IsColor Gets a boolean value that indicates whether the browser has a color display Request.Browser.IsMobileDevice Gets a boolean value that indicates whether the browser is a mobile device Request.Browser.CanInitiateVoiceCall Gets a boolean value that indicates whether the browser is capable of initiating a voice call

Some Commonly Used Request.Browser Properties

Consider an example wherein you have created separate home pages for desktop computers and mobile computers. You want to render the home pages depending upon the type of the computer that has requested the page. For this, you need to check the browser capabilities. This can be done by using the following code: protected void Page_Load(object sender, EventArgs e)

{

if (Request.Browser.IsMobileDevice)

{

Response.Redirect("Mobile/Home.aspx");

} }

The preceding code is written within the Page_Load event handler of the home page that is created for the desktop computers. It is the default startup page for the application. When the page is requested by any computer, the type of the device is checked. If the request is from a desktop computer, the default home page is returned. However, if the request comes from a mobile device, the Mobile/Home.aspx page is returned.

Note

You can check the browser capabilities by declaring a HttpBrowserCapabilities type variable as shown in the following code snippet:

HttpBrowserCapabilities browser = Request.Browser;

Response.Write(browser.ActiveXControls);

Note

Some mobile controls require you to use fully qualified redirects. For converting relative paths into fully qualified paths, you need to use the element as shown in the following example:

Implementing Device-Specific Rendering

Different mobile devices have different capabilities. Some devices can access the Internet and send e-mail messages while others cannot. Similarly, some devices have color screens, whereas others have gray-scale screens. When you design a Web page for mobile devices, you do not know which device will be used by the user to access that page. Therefore, you should design a Web page that caters to all the possible types of mobile devices.

For example, you may want to display a colored image on your mobile Web page. However, there are mobile devices that do not support colored images. Therefore, you need to design your Web page in such a way that it can be used by both types of mobile devices. For this, you need to design the Web page in such a way that it displays a gray image on devices that do not support colored images and a colored image on the rest of the devices. The ability to render a control based on the type of the device is known as device-specific rendering. This requires you to set the properties of the controls based on the capabilities of the mobile devices by using device filters. You can customize a mobile Web page for specific types of devices by defining a set of device filters for the page.

ASP.NET allows you to specify device filters for each type of device by using the tags. You can insert the tag as a child element of any mobile control on the Web page. This tag acts as an outer container for holding a number of choices defined by the tag.

The tag represents device characteristic/value pairs, where the device characteristic is drawn from a number of sources. A control can contain only one tag. However, it can contain many tags. Choices are evaluated in the order in which they appear in the DeviceSpecific/Choice construct. Each tag contains:

 A Filter attribute that specifies the devices that this choice applies to.  Additional property values that override the properties of the original control when the device specified by the Filter attribute is used.

Consider a scenario wherein you need to control the display of an image by using the tags. For this, you need to use the tags as shown in the following example:

In the preceding example, if the device is colored as specified by the isColor value of the Filter attribute, the colorImg.gif image will be displayed. For WML device, myImage.wbmp image will be displayed. The third tag does not have any Filter attribute. Therefore, it is the default choice and will be evaluated if the preceding two choices are not matched.

Note WML devices are those devices that support Wireless Markup Language (WML) intended for displaying Web pages on mobile devices. Currently, in place of WML, Extensible HyperText Markup Language (XHTML) is used in mobile devices.

The Filter attribute in each tag either specifies the name of a method on the mobile form or associated .ascx file, or the name of a device filter defined in the element of the web.config file.

Using the Name of a Method as Filters

When the name of a method is used as a filter, the choice is applied on the basis of the Boolean value returned by the method.

The filter method must conform to the following signature: public bool methodName(

System.Web.Mobile.MobileCapabilities capabilities, string optionalArgument);

Using Device Filters in the Web.config File

The Filter attribute can also specify the name of a filter defined in the web.config file. These filters can be of two types:

 Comparison filter: Comparison filters make comparisons that are generally based on a Boolean argument. In comparison filter, you need to provide the name of a capability and the value that you want the filter to compare. The following markup shows a comparison filter:

In the preceding markup, TestIsColor is the name of the filter and IsColor is the capability that is to be compared against the value, true.

 Evaluator-delegate filter: The evaluator-delegate filter is used for more complex evaluation. In evaluator-delegate filter, you need to specify an evaluator-delegate filter by providing the class and the name of a method. The following markup shows a evaluator-delegate filter:

name="TestIsColor"

type="CustomFilter"

method="checkColor" />

In the preceding markup, TestIsColor is the name of the filter, CustomFilter is the name of the class, and checkColor is the method that is called at run time to test the evaluator. You need to write and compile the class containing the method that is used to test the evaluator.

Note

In addition to device-specific rendering by using the element, you can use the XhtmlTextWriter and ChtmlTextWriter classes to provide additional adaptive rendering capabilities to the controls.

Summary

In this chapter, you learned that:

 A Web page created for desktop browsers cannot be properly displayed on mobile devices because mobile devices have small display area and low bandwidth.  ASP.NET provides you with the System.Web.Mobile namespace that is used specifically for mobile Web development.  Mobile Web pages have some specific controls. These are: o Form o Command o PhoneCall o List and ObjectList o DeviceSpecific o SelectionList o StyleSheet o TextView  Device emulators are software programs that simulate the environment of a cell phone or PDA on the desktop of your PC.  A control adapter is used for device-specific rendering of mobile Web controls instead of using the control's default rendering logic.  To customize the behavior of Web controls, you need to specify an object of the ControlAdapter class.  The ControlAdapter class is an abstract class that defines the basic functionality for all adapters.  The ability to render a control based on the type of the device is known as device- specific rendering.

Reference Reading

Creating Mobile Web Pages

Reference Reading: Reference Reading: URLs Books

Pro ASP.NET 3.5 in C# http://msdn.microsoft.com/en-us/library/8htez1ds.aspx 2008 by Matthew MacDonald, Mario Szpuszta

Rendering Content on Mobile Web Pages

Reference Reading: Reference Reading: URLs Books

Pro ASP. Net 3. 5 Server http://en.wikipedia.org/wiki/Mobile_browser Controls and AJAX http://msdn.microsoft.com/en-us/library/7s9fybz5.aspx Components by Rob Cameron, Dale Michalk