Você está na página 1de 385

MC 0081 DOT Net Technologies

Contents Unit 1 Introduction to Microsoft .Net Framework Unit 2 Introducing C# Programming Unit 3 Building Windows and Web Forms Unit 4 ASP.NET Unit 5 ASP.NET Applications Unit 6 State Management using ASP.Net Unit 7 ADO.NET Unit 8 Web Services Unit 9 Website Deployment Unit 10 Security References

1 22 84 108 156 180 204 255 295 322 378

Department: Information Technology Program: MCA Prof. V. B. Nanda Gopal Director & Dean Directorate of Distance Education Sikkim Manipal University of Health, Medical & Technological Sciences

Board of Studies
1. Name Designation Organisation / Institution Location 2. Name Designation Organisation / Institution Location 3. Name Designation Organisation / Institution Location 4. Name Designation Organisation / Institution Location 5. Name Designation Organisation / Institution Location 6. Name Designation Organisation / Institution Location Dr. U.B. Pavanaja General Manager Academics Manipal Universal Learning Pvt Ltd Bangalore Prof. Bhushan Patwardhan Chief Academics Manipal Education Bangalore Dr. Harishchandra Hebbar Director Manipal Centre for Information Sciences Manipal Dr. N.V. Subba Reddy Head of Department, Computer Science and Engineering Manipal Institute of Technology Manipal Dr. Ashok Hegde Vice President MindTree Consulting Ltd Bangalore Dr. Ramprasad Varadachar Director, Computer Studies Dayanand Sagar College of Engineering Bangalore

7. Name Designation Organisation / Institution Location 8. Name Designation Organisation / Institution Location 9. Name Designation Organisation / Institution Location 10. Name Designation Organisation / Institution Location 11. Name Designation Organisation / Institution Location

Nirmal Kumar Nigam Head of Program, Information Technology Sikkim Manipal University Manipal Dr. A. Kumaran Research Manager, Multilingual Research Microsoft Research Labs India Bangalore Ravindranath P. S. Director, Quality Yahoo India Bangalore Dr. Ashok Kallarakkal VP IBM India Bangalore H. Hiriyannaiah Group Manager EDS Mphasis Bangalore

Program (s) : MCA Subject (s) : .NET Technologies Subject Code (s) : MC0081

Content Preparation Team


Content Writing / Compilation Name Designation Organisation / Institution Location Content Editing Name Designation Organisation / Institution Location Language Editing Name Designation Organisation / Institution Location Edition: Fall 2007 This book is a distance education module comprising of written and collated learning material for our students. All rights reserved. No part of this work may be reproduced in any form by any means without permission in writing from Sikkim Manipal University of Health, Medical and Technological Sciences, Gangtok, Sikkim. Printed and Published on behalf of Sikkim Manipal University of Health, Medical and Technological Sciences, Gangtok, Sikkim by Mr. Rajkumar Mascreen, GM, Manipal Universal Learning Pvt. Ltd., Manipal 576 104. Printed at Manipal Press Limited, Manipal. Mr. Nirmal Kumar Nigam Assistant Professor & HOP - IT SMU-DDE Manipal Mr. Ravi Angadi Assistant Manager Mphasis an EDS Company Mangalore Mrs. Vasanta Raviprakash Sr.Lecturer, Department of English MGM College Udupi

SUBJECT INTRODUCTION
This book aims to help the readers make the transition from traditional Windows programming into the world of .Net programming. The Microsoft .Net framework includes the Common Language Runtime (CLR) and a set of base classes that radically simplify the development of large-scale applications and services. Microsoft announced the .Net initiative in July 2000. The .Net platform is a new development framework with a new programming interface to Windows services and APIs integrating a number of technologies that emerged from Microsoft during the late 1990s. Incorporated into .Net are COM+ component services; the ASP Web development framework; a commitment to XML and Object-oriented design; support for new web services protocols such as SOAP, WSDL, and UDDI; and a focus on the Internet. Unit 1: Introduction to Microsoft .Net Framework This unit introduces the reader with the introductory concepts of .Net platform. It describes the features of .Net platform, followed by the architecture of .Net framework. It introduces the concepts of Assmeblies in a .net environment and describes the types and usages of assemblies in application development. Unit 2: Introducing C# Programming This unit introduces the user with the Microsoft C# language used mainly for provision of interoperability. This unit enables the reader to describe the features of the C# language and write programs using the command line. It deals with the data types, control structures and other features of the C# language.

Unit 3: Building Windows and Web Forms This unit introduces the reader with advanced concepts of C# programming language. It discusses the design and execution of Windows based and Web based form development using the C# programming language. Unit 4: ASP.NET This unit introduces the user with the usage of ASP.NET for the purpose of developing Web Applications. It explains all the features and architecture of ASP.NET for Web application development. It also explains the usage of Master Pages, Content Pages, Themes, and Control skins in a Web page. Unit 5: ASP.NET Applications This unit starts with the anatomy of an ASP.NET application. It then explains the importance and usage of the configuration files: Web.config file and Global.asax file in application development. Unit 6: State Management using ASP.NET This unit introduces the reader with the aspects of state management using ASP.NET. It describes the usage of Cookies concept in an ASP.NET application. It describes the various states of an ASP.NET application like Application and Session states. Unit 7: ADO.NET This unit deals with the Microsofts ADO.NET, a set of APIs to manipulate data from an existing data source. It starts with the explanation of

disconnected architecture. It then explains the architecture of ADO.NET, connection strings, connection string builders, namespaces and so on. Unit 8: Web Services This unit deals with an introduction to Web services. It explains a basic web service application and the process of testing or executing it. It describes the code-behind concept of Web services. It discusses Web Service Description

Language (WSDL), example web services like DISCO, UDDI. It also takes a tour through Web clients, Web proxies, Web Service standards, and so on. Unit 9: Website Deployment This unit introduces the Microsoft built in Web server the Internet Information Services (IIS 6.0), which can be used for running and deploying the Web applications on the Web. It describes the features and architecture of IIS. It then explains creation of application pools and their management using IIS. It also demonstrates the deployment of Web applications developed using ASP.NET using IIS. Unit 10: Security The Security measures indicated in this unit help protect the data behind your applications and the applications themselves from fraudulent use. This unit introduces the user to the ASP.NET security model. It demonstrates various Form Authentication and Window Authentication measures. It describes the Memberships, Authorization and roles in ASP.NET security model. It discusses the various cryptographic classes present in ASP.ENT. It also discusses the Custom membership providers in ASP.NET.

DOT Net Technologies

Unit 1

Unit 1 Introduction to Microsoft .Net Framework


Structure: 1.1 Introduction to .Net Platform Objectives 1.2 1.3 1.4 1.5 1.6 1.7 1.8 Features of .Net Platform Components of .Net Architecture Assemblies Overview Summary Self Assessment Questions Terminal Questions Answers to Self Assessment Questions

1.1 Introduction to .Net Platform


The Microsofts .Net platform encompasses a virtual machine that abstracts away much of the windows API from development. It includes a class library with more functionality than any other created to date, and a development environment that spans multiple languages. It provides an architecture that makes multiple language integration simple and straightforward. This is the first development platform designed from the ground up with Internet in mind. .Net is designed and intended for highly distributed software, making Internet functionality and interoperability easier and more transparent to include in systems than ever before. Microsoft has taken many of the best ideas from the industry, combined with some ideas of their own, and brought them altogether into one coherent package.

Sikkim Manipal University

Page No. 1

DOT Net Technologies

Unit 1

Objectives: The .Net Framework is an amazing technology introduced by Microsoft which helps to build web applications. At the end of this unit the student would be able to: Describe in brief about .Net Platform along with its applications Explain the various features of .Net platform Describe the components of .Net Architecture Discuss regarding the role of assemblies in application execution

1.2 Features of .Net Platform


The .NET Framework is an integral Windows component that supports building and running the next generation of applications and XML Web services. The .NET Framework is designed to fulfill the following objectives:

To provide a consistent object-oriented programming environment whether object code is stored and executed locally, executed locally but Internet-distributed, or executed remotely.

To provide a code-execution environment that minimizes software deployment and versioning conflicts.

To provide a code-execution environment that promotes safe execution of code, including code created by an unknown or semi-trusted third party.

To

provide

code-execution

environment

that

eliminates

the

performance problems of scripted or interpreted environments.

To make the developer experience consistency across widely varying types of applications, such as Windows-based applications and Webbased applications.

To build all communication on industry standards to ensure that code based on the .NET Framework can integrate with any other code.

Sikkim Manipal University

Page No. 2

DOT Net Technologies

Unit 1

The .NET Framework has two main components: the common language runtime and the .NET Framework class library. The common language runtime is the foundation of the .NET Framework. You can think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety and other forms of code accuracy that promote security and robustness. In fact, the concept of code management is a fundamental principle of the runtime. Code that targets the runtime is known as managed code, while code that does not target the runtime is known as unmanaged code. The class library, the other main component of the .NET Framework, is a comprehensive, object-oriented collection of reusable types that you can use to develop applications ranging from traditional command-line or graphical user interface (GUI) applications to applications based on the latest innovations provided by ASP.NET, such as Web Forms and XML Web services. The .NET Framework can be hosted by unmanaged components that load the common language runtime into their processes and initiate the execution of managed code, thereby creating a software environment that can exploit both managed and unmanaged features. The .NET Framework not only provides several runtime hosts, but also supports the development of thirdparty runtime hosts. For example, ASP.NET hosts the runtime to provide a scalable, server-side environment for managed code. ASP.NET works directly with the runtime to enable ASP.NET applications and XML Web services, both of which are discussed later in this topic. Internet Explorer is an example of an unmanaged application that hosts the runtime (in the form of a MIME type extension). Using Internet Explorer to host the runtime enables you to embed managed components or Windows
Sikkim Manipal University Page No. 3

DOT Net Technologies

Unit 1

Forms controls in HTML documents. Hosting the runtime in this way makes managed mobile code (similar to Microsoft ActiveX controls) possible, but with significant improvements that only managed code can offer, such as semi-trusted execution and isolated file storage. The figure 1.1 shows the relationship of the common language runtime and the class library to your applications and to the overall system. It also shows how managed code operates within a larger architecture.

Figure 1.1: Relationship between Common Language Runtime (CLR) and Class Library

.NET Framework Class Library


The .NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime. The class library is object oriented, providing types from which your own managed code can derive functionality. This not only makes the .NET Framework types easy to use, but also reduces the time associated with learning new features of the .NET Framework. In addition, third-party components can integrate seamlessly with classes in the .NET Framework.
Sikkim Manipal University Page No. 4

DOT Net Technologies

Unit 1

For example, the .NET Framework collection classes implement a set of interfaces that you can use to develop your own collection classes. Your collection classes will blend seamlessly with the classes in the .NET Framework. As you would expect from an object-oriented class library, the .NET Framework types enable you to accomplish a range of common programming tasks, including tasks such as string management, data collection, database connectivity, and file access. In addition to these common tasks, the class library includes types that support a variety of specialized development scenarios. For example, you can use the .NET Framework to develop the following types of applications and services:

Console applications. Windows GUI applications (Windows Forms). Windows Presentation Foundation (WPF) applications. ASP.NET applications. Web services. Windows services. Service-oriented Foundation (WCF). applications using Windows Communication

Workflow-enabled applications using Windows Workflow Foundation (WF).

For example, the Windows Forms classes are a comprehensive set of reusable types that vastly simplify Windows GUI development. If you write an ASP.NET Web Form application, you can use the Web Forms classes.

Sikkim Manipal University

Page No. 5

DOT Net Technologies

Unit 1

1.3 Components of .Net Architecture


The major components of the .Net framework are shown in the figure 1.2 below:

ASP.NET Web Services Web Forms

Windows Forms Controls Drawing

ASP.NET Application Services

Windows Application Services

.NET Framework Base Classes ADO.NET Net XML Security Threading Diagnostics IO Etc.

Common Language Runtime


Memory Management Common Type System Life Cycle Monitoring

Figure 1.2: Major Components of .Net Framework

At the lowest level, the framework starts with Memory Management and Component Loading and goes all the way up to multiple ways of rendering user and program interfaces. The middle layer provides any system level capability that a developer needs. The base to the Framework is the Common Language Runtime (CLR). The CLR is the heart of the .Net framework, the engine that drives the key functionality. For example the CLR includes a common system of data types. These common types plus a standard interface convention, make cross language
Sikkim Manipal University Page No. 6

DOT Net Technologies

Unit 1

inheritance possible. The CLR also does the reference counting for objects and handles garbage collection. The middle layer consists of standard system services such as ADO.NET AND XML. These services are controlled by the framework making them universally available and standardizing their usage across languages. The top layer has the user and program interfaces. Windows Forms: They provide a new way to create standard Win32 desktop applications, based on the Windows Foundation Classes (WFC) produced for J++. Web Forms: They provide a powerful forms based UI for the web. Web Services: They provide a mechanism for programs to communicate over the Internet using SOAP. They provide an analog of COM and DCOM for object brokering and interfacing, but based on Internet technologies so that allowance is made for integration even with non Microsoft platforms. The Web Forms and Web Services comprise the Internet interface portion of the .Net, and are implemented through a section of the .Net Framework referred to as ASP.NET. All the above objects are available to any language based on the .Net platform. For completeness, there is also a console interface that allows creation of character based applications.

Sikkim Manipal University

Page No. 7

DOT Net Technologies

Unit 1

The Common Language Runtime

Common Type System (Data, Types, etc.) Intermediate Language (IL) To native code compilers Execution Support (traditional runtime functions) Security

Garbage Collection, Stack Walk, Code Manager

Class Loader and Memory Layout

Figure 1.3: Major Components of Common Language Runtime (CLR)

A runtime is an environment in which the programs are executed. The CLR is an environment used for running the .Net applications that have been compiled to a common language, namely Microsoft Intermediate Language (MSIL) often referred to as IL. The Execution Support: It contains most of the capabilities normally associated with the language runtime (viz. VBRUNxxx.dll runtime of Visual Basic). Garbage Collection: The .NET Framework's garbage collector manages the allocation and release of memory for your application. Each time you use the new operator to create an object, the runtime allocates memory for the object from the managed heap. As long as address space is available in the managed heap, the runtime continues to allocate space for new objects. However, memory is not infinite. Eventually the garbage collector must perform a collection in order to free some memory. The garbage collector's optimizing engine determines the best time to perform a collection, based upon the allocations being made. When the garbage collector performs a
Sikkim Manipal University Page No. 8

DOT Net Technologies

Unit 1

collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory. Stack Walk: This concept is helpful to anyone interested in building a profiler to examine managed applications. The following lines describe how you can program your profiler to walk managed stacks in the common language runtime (CLR) of the .NET Framework. The profiling API in version 2.0 of the CLR has a new method named DoStackSnapshot that lets your profiler walk the call stack of the application you're profiling. Version 1.1 of the CLR exposed similar functionality through the in-process debugging interface. But walking the call stack is easier, more accurate, and more stable with DoStackSnapshot. The DoStackSnapshot method uses the same stack walker used by the garbage collector, security system, exception system, and so on. Access to a full stack trace gives users of your profiler the ability to get the big picture of what's going on in an application when something interesting happens. Depending on the application and on what a user wants to profile, you can imagine a user wanting a call stack when an object is allocated, when a class is loaded, when an exception is thrown, and so on. Even getting a call stack for something other than an application event, for example, a timer event would be interesting for a sampling profiler. Looking at hot spots in code becomes more enlightening when you can see who called the function containing the hot spot. We are going to focus on getting stack traces with the DoStackSnapshot API. Another way to get stack traces is by building shadow stacks: you can hook FunctionEnter and FunctionLeave to keep a copy of the managed call stack for the current thread. Shadow stack building is useful if you need stack information at all times during application execution, and if you don't
Sikkim Manipal University Page No. 9

DOT Net Technologies

Unit 1

mind the performance cost of having your profiler's code run on every managed call and return. The DoStackSnapshot method is best if you need slightly sparser reporting of stacks, such as in response to events. Even a sampling profiler taking stack snapshots every few milliseconds is much sparser than building shadow stacks. So DoStackSnapshot is well suited for sampling profilers. Class Loader: Normally, the Java Virtual Machine loads classes from the local file system in a platform-dependent manner. For example, on UNIX systems, the Virtual Machine loads classes from the directory defined by the CLASSPATH environment variable. However, some classes may not originate from a file; they may originate from other sources, such as the network, or they could be constructed by an application. The method defineClass converts an array of bytes into an instance of class Class. Instances of this newly defined class can be created using the newInstance method in class Class. The methods and constructors of objects created by a class loader may refer other classes. To determine the class(es) referred to, the Java Virtual Machine calls the loadClass method of the class loader that originally created the class. If the Java Virtual Machine only needs to determine if the class exists and if it does exist to know its superclass, the resolve flag is set to false. However, if an instance of the class is being created or any of its methods are being called, the class must also be resolved. In this case the resolve flag is set to true, and the resolveClass method should be called. For example, an application could create a network class loader to download class files from a server. Sample code might look like: ClassLoader loader = new NetworkClassLoader(host, port); Object main = loader.loadClass("Main", true).newInstance(); ...
Sikkim Manipal University Page No. 10

DOT Net Technologies

Unit 1

Hosts such as Microsoft Internet Explorer, ASP.NET, and the Windows shell load the common language runtime into a process, create an application domain in that process, and then load and execute user code in that application domain when running a .NET Framework application. In most cases, you do not have to worry about creating application domains and loading assemblies into them because the runtime host performs those tasks. However, if you are creating an application that will host the common language runtime, creating tools or code you want to unload

programmatically, or creating pluggable components that can be unloaded and reloaded on the fly, you will be creating your own application domains. Even if you are not creating a runtime host, this section provides important information on how to work with application domains and assemblies loaded in these application domains. The common language runtime allows you to add keyword-like descriptive declarations, called attributes, to annotate programming elements such as types, fields, methods, and properties. Attributes are saved with the metadata of a Microsoft .NET Framework file and can be used to describe your code to the runtime or to affect application behavior at run time. While the .NET Framework supplies many useful attributes, you can also design and deploy your own. Security: The .Net framework includes an integrated security model that grants permission to resources based on evidence found in the assemblies. The common language runtime and the .NET Framework provide many useful classes and services that enable developers to easily write security code. These classes and services also enable system administrators to customize the access that code has to protected resources. In addition, the

Sikkim Manipal University

Page No. 11

DOT Net Technologies

Unit 1

runtime and the .NET Framework provide useful classes and services that facilitate the use of cryptography and role-based security.

1.4 Assemblies Overview


Assemblies are a fundamental part of programming with the .NET Framework. An assembly performs the following functions: It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. Note that each assembly can have only one entry point (that is, DllMain, WinMain, or Main). It forms a security boundary. An assembly is the unit at which permissions are requested and granted. It forms a type boundary. Every type's identity includes the name of the assembly in which it resides. A type called MyType loaded in the scope of one assembly is not the same as a type called MyType loaded in the scope of another assembly. It forms a reference scope boundary. The assembly's manifest contains assembly metadata that is used for resolving types and satisfying resource requests. It specifies the types and resources that are exposed outside the assembly. The manifest also enumerates other assemblies on which it depends. It forms a version boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit. The assembly's manifest describes the version dependencies you specify for any dependent assemblies. For more information about versioning, see Assembly Versioning.

Sikkim Manipal University

Page No. 12

DOT Net Technologies

Unit 1

It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes, can be retrieved on demand. This allows applications to be kept simple and thin when first downloaded. For more information about deploying assemblies, see Deploying Applications.

It is the unit at which side-by-side execution is supported. For more information about running multiple versions of an assembly, see Assemblies and Side-by-Side Execution.

Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in portable executable (PE) files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed. There are several ways to create assemblies. You can use development tools, such as Visual Studio 2005, that you have used in the past to create .dll or .exe files. You can use tools provided in the Windows Software Development Kit (SDK) to create assemblies with modules created in other development environments. You can also use common language runtime APIs, such as Reflection.Emit, to create dynamic assemblies. Benefits of Assemblies Assemblies are designed to simplify application deployment and to solve versioning problems that can occur with component-based applications. End users and developers are familiar with versioning and deployment issues that arise from today's component-based systems. Some end users have experienced the frustration of installing a new application on their
Sikkim Manipal University Page No. 13

DOT Net Technologies

Unit 1

computer, only to find that an existing application has suddenly stopped working. Many developers have spent countless hours trying to keep all necessary registry entries consistent in order to activate a COM class. Many deployment problems have been solved by the use of assemblies in the .NET Framework. Because they are self-describing components that have no dependencies on registry entries, assemblies enable zero-impact application installation. They also simplify uninstalling and replicating applications. Versioning Problems Currently two versioning problems occur with Win32 applications: 1. Versioning rules cannot be expressed between pieces of an application and enforced by the operating system. The current approach relies on backward compatibility, which is often difficult to guarantee. Interface definitions must be static, once published, and a single piece of code must maintain backward compatibility with previous versions.

Furthermore, code is typically designed so that only a single version of it can be present and executing on a computer at any given time. 2. There is no way to maintain consistency between sets of components that are built together and the set that is present at run time. These two versioning problems combine to create DLL conflicts, where installing one application can inadvertently break an existing application because a certain software component or DLL was installed that was not fully backward compatible with a previous version. Once this situation occurs, there is no support in the system for diagnosing and fixing the problem. An End to DLL Conflicts Microsoft Windows 2000 began to fully address these problems. It provides two features that partially fix DLL conflicts:
Sikkim Manipal University Page No. 14

DOT Net Technologies

Unit 1

Windows 2000 enables you to create client applications where the dependent .dll files are located in the same directory as the application's .exe file. Windows 2000 can be configured to check for a component in the directory where the .exe file is located before checking the fully qualified path or searching the normal path. This enables components to be independent of components installed and used by other applications.

Windows 2000 locks files that are shipped with the operating system in the System32 directory so they cannot be inadvertently replaced when applications are installed.

The common language runtime uses assemblies to continue this evolution toward a complete solution to DLL conflicts. The Assembly Solution To solve versioning problems, as well as the remaining problems that lead to DLL conflicts, the runtime uses assemblies to do the following: Enable developers to specify version rules between different software components. Provide the infrastructure to enforce versioning rules. Provide the infrastructure to allow multiple versions of a component to be run simultaneously (called side-by-side execution). Assembly Contents In general, a static assembly can consist of four elements: The assembly manifest, which contains assembly metadata. Type metadata. Microsoft Intermediate Language (MSIL) code that implements the types. A set of resources.

Only the assembly manifest is required, but either types or resources are needed to give the assembly any meaningful functionality. There are several
Sikkim Manipal University Page No. 15

DOT Net Technologies

Unit 1

ways to group these elements in an assembly. You can group all elements in a single physical file, which is shown in the following illustration: Single-file Assembly MyAssembly.dll
Assembly Manifest Type metadata MSIL Code Resources

Alternatively, the elements of an assembly can be contained in several files. These files can be modules of compiled code (.netmodule), resources (such as .bmp or .jpg files), or other files required by the application. Create a multi-file assembly when you want to combine modules written in different languages and to optimize downloading an application by putting seldom used types in a module that is downloaded only when needed. In the following illustration, the developer of a hypothetical application has chosen to separate some utility code into a different module and to keep a large resource file (in this case a .bmp image) in its original file. The .NET Framework downloads a file only when it is referenced; keeping infrequently referenced code in a separate file from the application optimizes code download. Multi-file Assembly Assembly Manifest Type metadata MSIL Code Util.netmodule Type metadata MSIL Code Graphic.bmp

Resources

Sikkim Manipal University

Page No. 16

DOT Net Technologies

Unit 1

Note: The files that make up a multifile assembly are not physically linked by the file system. Rather, they are linked through the assembly manifest and the common language runtime manages them as a unit. In this illustration, all three files belong to an assembly, as described in the assembly manifest contained in MyAssembly.dll. To the file system, they are three separate files. Note that the file Util.netmodule was compiled as a module because it contains no assembly information. When the assembly was created, the assembly manifest was added to MyAssembly.dll, indicating its relationship with Util.netmodule and Graphic.bmp. As you currently design your source code, you make explicit decisions about how to partition the functionality of your application into one or more files. When designing .NET Framework code, you will make similar decisions about how to partition the functionality into one or more assemblies. Assembly Manifest Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information.

Sikkim Manipal University

Page No. 17

DOT Net Technologies

Unit 1

The following illustration shows the different ways the manifest can be stored: Types of Assemblies
A Single file Assembly
file2.dll File1.dll Manifest Manifest

A Multi file Assembly

Graphic.jpg

Logo.bmp

For an assembly with one associated file, the manifest is incorporated into the PE file to form a single-file assembly. You can create a multifile assembly with a standalone manifest file or with the manifest incorporated into one of the PE files in the assembly. Each assembly's manifest performs the following functions: Enumerates the files that make up the assembly. Governs how references to the assembly's types and resources map to the files that contain their declarations and implementations. Enumerates other assemblies on which the assembly depends. Provides a level of indirection between consumers of the assembly and the assembly's implementation details. Renders the assembly self-describing.

Sikkim Manipal University

Page No. 18

DOT Net Technologies

Unit 1

Assembly Manifest Contents The following table shows the information contained in the assembly manifest. The first four itemsthe assembly name, version number, culture, and strong name informationmake up the assembly's identity.
Information Assembly name Version number Description A text string specifying the assembly's name. A major and minor version number, and a revision and build number. The common language runtime uses these numbers to enforce version policy. Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information. (An assembly with culture information is automatically assumed to be a satellite assembly.) The public key from the publisher if the assembly has been given a strong name. A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest. Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly. A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.

Culture

Strong name information List of all files in the assembly

Type reference information

Information on referenced assemblies

You can add or change some information in the assembly manifest by using assembly attributes in your code. You can change version information and informational attributes, including Trademark, Copyright, Product, Company, and Informational Version.

Sikkim Manipal University

Page No. 19

DOT Net Technologies

Unit 1

1.5 Summary
This chapter provides an introduction and overview of the Microsofts latest .Net Platform, which has interoperability and cross platform development features. It starts with the basic features of .Net platform and describes the major components of .Net platform. It then provides with a clear picture of the .Net Architecture and its components. It then ends with providing the basic view of Assemblies and their usage in application development. Self Assessment Questions 1. The .NET Framework can be hosted by ___________ components that load the common language runtime into their processes and initiate the execution of managed code. 2. ASP.NET hosts the ______ to provide a scalable, server-side environment for managed code. 3. The ____________ is a collection of reusable types that tightly integrate with the common language runtime. 4. The _______ Provide a mechanism for programs to communicate over the Internet using SOAP. 5. The concept of _________ is helpful to anyone interested in building a profiler to examine managed applications. 6. The ______ assemblies are stored on disk in portable executable (PE) files.

1.7 Terminal Questions


1. Discuss the features of .Net platform. (Refer to 1.2) 2. Discuss the architecture of .Net with a supporting diagram (Refer to 1.3) 3. Describe the Assemblies in .Net environment. (Refer to 1.4)

Sikkim Manipal University

Page No. 20

DOT Net Technologies

Unit 1

1.8 Answers to Self Assessment Questions


1. unmanaged 2. runtime 3. NET Framework class library 4. Web Services 5. Stack Walk 6. Static

Sikkim Manipal University

Page No. 21

DOT Net Technologies

Unit 2

Unit 2
Structure: 2.1 Introduction Objectives 2.2 2.3 2.4 2.5 2.6 2.7 2.8

Introducing C# Programming

Creating your first C# Program Introducing Data Types Control Statements Understanding Properties & Indexes Delegates and Events Exception Handling Summary Self Assessment Questions

2.9 2.10

Terminal Questions Answers to Self Assessment Questions

2.1 Introduction
The C# language (pronounced as C Sharp or see Sharp) is an Object Oriented Programming Language developed by Microsoft to become a key part of their .Net software development platform. The C# language is based on the C++ Language, but it is mostly developed on the lines of Microsofts Visual Basic. The .NET Framework defines a "Common Language Specification" (CLS), a sort of lingua franca that ensures seamless interoperability between CLScompliant languages and class libraries. For C# developers, this means that even though C# is a new language, it has complete access to the same rich class libraries that are used by seasoned tools such as Visual Basic .NET and Visual C++ .NET. C# itself does not include a class library.

Sikkim Manipal University

Page No. 22

DOT Net Technologies

Unit 2

The principal designer of the C# language was Anders Hajlsberg. C# was designed to take advantage of the Common Language Runtime (CLR) that .Net program rely on. All applications written in C# require CLR to run. The Cornerstone components of .Net Platform: There are four major cornerstone components of .Net platform as follows: 1. .Net Building Block services such as Passport 2. .Net Compact Framework that runs on devices such as mobile phones 3. .Net through XML integration 4. .Net infrastructure such as the .Net framework CLR and .Net framework class libraries and application developments such as Microsoft Visual Studio.Net All the .Net programming languages have the .Net framework class libraries integrated into them. The .Net class libraries also support functions such as file I/O, database operations, XML and SOAP. Sample Program: This is just a basic program that illustrates how a C# program looks like.
public class Class1 { public static void Main() { System.Console.WriteLine( Welcome to C#); } } Figure 2.1: A Sample C# Program

The output of this program would be Welcome to C# on the console. Objectives This unit is an introduction to Microsofts C# programming Language developed exclusively to allow interoperability features in .Net environment.
Sikkim Manipal University Page No. 23

DOT Net Technologies

Unit 2

At the end of this unit the student would be able to: Describe the importance of C# in Web Application development and highlight its features Describe the step-by-step procedure to edit, compile, and run Command based C# programs. Discuss the data types available in C#. Write programs using control statements of C#. Discuss about Properties, Indexes, Delegates and Events. Describe the Excpetion handling mechanisms used in C#.

2.2 Creating your first C# Program


It would be very easy to create, compile and run a C# program by following the steps illustrated in the following topics Compiling and Executing The minimum requirements for getting started with C# programming are: 1. A text editor (like Windows Notepad) 2. The Microsoft .NET Framework The text editor allows you to type in the C# code that will be compiled.

Figure 2.2: The sample program typed in Notepad

Sikkim Manipal University

Page No. 24

DOT Net Technologies

Unit 2

The Microsoft .Net Framework In addition to the text editor, you should have the Microsoft .Net Framework installed on your PC or Laptop.

Figure 2.3: The sample program saved as filename.cs from notepad

Figure 2.4: Compiling and executing the sample C# program

You can download the latest version of the .NET Framework from the following URL: http://msdn.microsoft.com/netframework/.

Sikkim Manipal University

Page No. 25

DOT Net Technologies

Unit 2

Steps for writing and compiling the C# code: Step 1: Type the C# code in the notepad as shown below:

Figure 2.5: Step 1: Keying a program in an editor

Step 2: Save the file into the folder containing the folder corresponding to C#. In my machine it is: C:\Program Files\Microsoft Visual Studio\SDK\V2.0> Save the notepad file as shown below:

Figure 2.6: Step 2 Saving the program into the directory or folder

Sikkim Manipal University

Page No. 26

DOT Net Technologies

Unit 2

Step 3: Open the command prompt (Start -> Run and type cmd and click OK) and navigate to the folder where you have saved the file. Alternatively you can start the command window from Windows Start Menu as shown below:

Figure 2.7: Step - 3: Opening the command prompt window

Step 4: Now we are ready to compile the program from the C# command line. The compiler used here is called csc.exe and is in the folder v2.0 of SDK. The syntax for compiling the sample C# program is:

csc.exe <filename>.cs
The name of our C# program is hello.cs. The syntax for compilation of the above program file is: csc.exe hello.cs

Sikkim Manipal University

Page No. 27

DOT Net Technologies

Unit 2

The following diagram illustrates the steps of the compilation of the sample program.

Figure 2.8: Step - 4: Compiling the program at the Command Prompt

Step 5: The source code is now compiled into an executable format. The name of the executable file thus generated is hello.exe, which is having the same name as the source code file name, except that the .cs extension is replaced by the .exe extension. To run the executable file, the following command should be typed at the command prompt: hello.exe The executable file gets executed by the environment and the string message Welcome to C# would be displayed on the console window.

Figure 2.9: Output of the Sample Program Sikkim Manipal University Page No. 28

DOT Net Technologies

Unit 2

A C# program can consist of more than one source file. The source files are turned into programs using a compiler. csc: It is the C# compiler that ships with the .Net Framework. The source code hello.cs is the C# source file passed to the compiler as an argument for compilation.

Figure 2.10: Sample Program Modified

using System: The using directive refers to a namespace called System, provided by the Common Language Infrastructure (CLI ), a synonym for the .Net Framework. The System namespace contains the Console class. The using Directive: By using this directive, we can make use of the unqualified types that are members of the namespace, i.e. it allows us to use only the command Console.WriteLine() instead of the entire command System.Console.WriteLine(). Defining a Class C# is an object-oriented programming language and uses classes and structs to implement types such as Windows Forms, user interface controls, and data structures. A typical C# application consists of classes defined by the programmer, combined with classes from the .NET Framework. Classes enable you to develop applications using object-oriented

programming (OOP) techniques. Classes are templates that define objects.


Sikkim Manipal University Page No. 29

DOT Net Technologies

Unit 2

When you create a new form in a C# project, you are actually creating a class that defines a form; forms instantiated at runtime are derived from the class. Using objects derived from predefined classes, such as a C# Form class, is just the start of enjoying the benefits of object-oriented programming to truly realize the benefits of OOP, you must create your own classes. All generic class declarations will have one or more type parameters. C# provides many powerful ways of defining classes, such as providing different access levels, inheriting features from other classes, and enabling the programmer to specify what occurs when types are instantiated or destroyed. Classes can also be defined as generic by using type parameters that enable client code to customize the class in a type-safe and efficient manner.A single generic class, for example System.Collections.

Generic.List(T) in the .NET Framework can be used by client code to store integers, strings, or any other type of object. A class is the most powerful data type in C#. Like structures, a class defines the data and behavior of the data type. Programmers can then create objects that are instances of this class. Unlike structures, classes support inheritance, which is a fundamental part of object-oriented programming. Declaring Classes Classes are defined by using the class keyword, as shown in the following example:

Figure 2.11: Declaration of classes in C# Sikkim Manipal University Page No. 30

DOT Net Technologies

Unit 2

The class keyword is preceded by the access level. Because public is used in this case, anyone can create objects from this class. The name of the class follows the class keyword. The remainder of the definition is the class body, where the behavior and data are defined. Fields, properties, methods, and events on a class are collectively referred to as class members. Creating Objects Although they are sometimes used interchangeably, a class and an object are different things. A class defines a type of object, but it is not an object itself. An object is a concrete entity based on a class, and is sometimes referred to as an instance of a class. Objects can be created by using the new keyword followed by the name of the class that the object will be based on, like this:

Figure 2.12: Creating Objects from a Class

When an instance of a class is created, a reference to the object is passed back to the programmer. In the previous example, object1 is a reference to an object that is based on Customer. This reference refers to the new object but does not contain the object data itself. In fact, you can create an object reference without creating an object at all.

Figure 2.13: Creation of an Object Reference

We do not recommend creating object references such as this one that does not refer to an object because trying to access an object through such a reference will fail at run time. However, such a reference can be made to refer to an object, either by creating a new object, or by assigning it to an existing object, such as this:
Sikkim Manipal University Page No. 31

DOT Net Technologies

Unit 2

Figure 2.14: Creation of Object References

This code creates two object references that both refer to the same object. Therefore, any changes to the object made through object3 will be reflected in subsequent uses of object4. Because objects that are based on classes are referred to by reference, classes are known as reference types. Declaring the Main() method: The Main() method is a member of the class Hello1 (as in Program 2.10). It is the point at which the application execution begins, i.e. it is the entry point for the application. There can only be one entry point in a C# program. The Main method can be declared with or without parameters. Parameters can be read as zero-indexed command line arguments. A Static Modifier is used so that the method it is assigned to becomes a method of the class rather than an instance of the class. Using the using keyword: The using keyword has two major uses: 1. As a Directive: When it is used to create an alias for a namespace or to import types defined in other namespaces. The using directive has two uses: To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace:

Figure Usage of types in the namespace

Sikkim Manipal University

Page No. 32

DOT Net Technologies

Unit 2

To create an alias for a namespace or a type.

Figure Creation of Aliases for namespaces or types

2. As a Statement: When it defines a scope at the end of which an object will be disposed. It helps the users or the programmers to ensure that IDisposable objects such as files and fonts are handled correctly. Adding Comments The following console program is the C# version of the traditional "Hello World!" program, which displays the string Hello World!.

Figure 2.17: A Sample Hello World Program with Comments

The line //A Hello World program in C# is a single line comment, which would be ignored by the compiler during compilation or execution. There are two types of comment statements within C# Language similar to that of Java or C++ language syntax elements. 1. Single Line Comments: A one line comment can be given within a program using // 2. Multi Line Comments: A comment can be extended beyond a single line by enclosing all the statements within /* and */.

Sikkim Manipal University

Page No. 33

DOT Net Technologies

Unit 2

2.3 Introducing Data Types


A Type is how a programming language classifies different values and expressions. Since the computer stores all the data internally in the form of zeros and ones, the data needs to have a context or meaning. In order to preserve this meaning, Types are used in a programming language. Since C# is a strongly typed language; every variable and object used as part of the programs must have a declared type. In any programming language, it's critical that the compiler, the part of the Visual Studio framework that interprets the code you write into a language the computer can understand, fully understands the type of data you're manipulating in code. For example, if you ask the compiler to add the following values, it would get confused: 659 / "Dog" When the compiler gets confused, it either refuses to compile the code (which is the preferred situation because you can address the problem before your users run the application), or it will halt execution and display an exception (error) when it reaches the confusing line of code. Obviously, you can't subtract 659 by the word "Dog"; these two values are different types of data. In C#, these two values are said to have two different data types. In C#, constants, variables, and arrays must always be defined to hold a specific type of information. Determining the Data Type Data Typing: The act of defining a constant, a variable, or an array's data type can be confusing. To C#, a number is not a number. A number that contains a decimal value is different from a number that does not. C# can perform arithmetic on numbers of different data types, but you can't store data of one type in a variable with an incompatible type. Because of this limitation, you must give careful consideration to the type of data you plan to
Sikkim Manipal University Page No. 34

DOT Net Technologies

Unit 2

store in a constant, a variable, or an array at the time you define it. C# supports two categories of data types: value types and reference types. The main difference between these two types is how their values are stored in memory. As you continue to create more complex applications, this difference may have an impact on your programming. Overview of C# Data Types A Data Type can be described as being either: A built-in numeric type, such as an int or char, or A user-defined type, such as a class or interface. An anonymous type, which consists of a set of public properties encapsulated in a nameless reference type. Types can also be defined as being either: Value Types (C# Reference), which store values. These include the primitive numeric types, enums and structs, and also nullable versions of these types. Reference Types (C# Reference), which store references to the actual data. These include classes, interfaces, arrays and delegates. Value Types The value types consist of two main categories: Structs Enumerations Structs fall into these categories: Numeric types Integral types Floating-point types Decimal

Bool User defined structs


Sikkim Manipal University Page No. 35

DOT Net Technologies

Unit 2

Main Features of Value Types: Variables that are based on value types directly contain values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself. All value types are derived implicitly from the System.ValueType. Unlike with reference types, you can derive a new type from a value type. However, like reference types, structs can implement interfaces. Unlike reference types, a value type cannot contain the null value. However, the nullable types feature does allow for values types to be assigned to null. Each value type has an implicit default constructor that initializes the default value of that type. Each of the variables will have their own copy of the data and an operation on one copy does not affect the others. All of the simple types those integral to the C# language -- are aliases of the .NET Framework System types. For example, int is an alias of System.Int32. Constant expressions, whose operands are all simple type constants, are evaluated at compilation time. Simple types can be initialized by using literals. For example, 'A' is a literal of the type char and 2001 is a literal of the type int. Initializing Value Types Local variables in C# must be initialized before they are used. For example, you might declare a local variable without initialization as in the following example: int i1;

Sikkim Manipal University

Page No. 36

DOT Net Technologies

Unit 2

You cannot use i1 before initializing. To initialize we can use the following statement: i1 = new int(); // Invokes the default constructor for the int data type. The above initialization statement is equivalent to: i1 = 0; Alternatively, you can have the above two statements combined into a single statement:

OR

Either of the above statements are correct. Using the new operator calls the default constructor of the specific type and assigns the default value to the variable. In the preceding example, the default constructor assigned the value 0 to i1. We can use the new operator to invoke the default constructor with user defined data types. For example, the following statement invokes the default constructor of the Point struct:

After this call, the struct is considered to be definitely assigned; i.e. all its members are initialized to their default values.

Sikkim Manipal University

Page No. 37

DOT Net Technologies

Unit 2

Primitive Data Types The following reference tables summarize the C# types: Built-in Integral Floating - point 1. Built in Data Types
C# Type .NET Framework Type System.Boolean Meaning

bool

An alias of System.Boolean and is used to declare variables to store the Boolean values, true and false. Note: If you require a Boolean variable that can also have a value of null, use bool. An unsigned 8-bit integer A signed 8-bit integer Used to declare a Unicode character. Constants of the char type can be written as character literals, hexadecimal escape sequence, or Unicode representation. You can also cast the integral character codes. Indicates a 128-bit data type. Compared to floatingpoint types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations. The double keyword signifies a simple type that stores 64-bit floating-point values. Note: To treat an integer number as double, use the suffix d or D A simple type that stores 32-bit floating-point values. Note: To initialize a float variable, use the suffix f or F. Signed 32-bit integer Unsigned 32-bit integer Signed 64-bit integer Unsigned 64-bit integer

byte sbyte char

System.Byte System.SByte System.Char

decimal

System.Decimal

double

System.Double

float

System.Single

int uint long ulong object short

System.Int32 System.UInt32 System.Int64 System.UInt64 System.Object System.Int16

Signed 16-bit integer

Sikkim Manipal University

Page No. 38

DOT Net Technologies

Unit 2

ushort string

System.UInt16 System.String

Unsigned 16-bit integer Represents a sequence of zero or more Unicode characters. An alias for String in the .NET Framework. Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive.

Note: 1. All types in the table, except object and string, are referred to as simple types. 2. The C# type keywords and their aliases are interchangeable. 3. To display the actual type for any C# type, use the system method GetType(). For example, the following statement displays the system alias that represents the type of myVariable:

2. Integral Types:
Type sbyte byte char short ushort int uint long ulong Range -128 to 127 0 to 255 U+0000 to U+ffff -32,768 to 32,767 0 to 65,535 -2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 0 to 18,446,744,073,709,551,615

Sikkim Manipal University

Page No. 39

DOT Net Technologies

Unit 2

3. Floating-Point Types The following table shows the precision and approximate ranges for the floating-point types.
Type float double Approximate range 1.5e45 to 3.4e38 5.0e324 to 1.7e308 Precision 7 digits 15-16 digits

Reference Types Variables of reference types, referred to as objects, store references to the actual data. This section introduces the following keywords used to declare reference types: class interface delegate This section also introduces the following built-in reference types: object string 1. class Classes are declared using the keyword class. Unlike C++, only single inheritance is allowed in C#, i.e. a class can inherit implementation from one base class only. However, a class can implement more than one interface. The following table shows examples of class inheritance and interface implementation:
Inheritance None Single None, implements two interfaces Single, implements one interface Example Class ClassA() Class DerivedClass: BaseClass { } Class ImplClass: IFace1, IFace2 { } Class ImplDerivedClass: BaseClass, IFace1 { }

Sikkim Manipal University

Page No. 40

DOT Net Technologies

Unit 2

The access levels protected and private are only allowed on nested classes. You can also declare generic classes that have type parameters. Access Modifiers: Keywords used to specify the declared accessibility of a member or a type. This following are the Four Access Modifiers: Public Protected Internal Private The following Five Accessibility Levels can be specified using the access modifiers: 1. Public: Access is not restricted. 2. Protected: Access is limited to the containing class or types derived from the containing class. 3. Internal: Access is limited to the current assembly. 4. Protected Internal: Access is limited to the current assembly or types derived from the containing class. 5. Private: Access is limited to the containing type. Generic Classes: Encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on. Operations such as adding and removing items from the collection are performed in basically the same way regardless of the type of data being stored. For most scenarios that require collection classes, the recommended approach is to use the ones provided in the .NET Framework class library. Typically, you create generic classes by starting with an existing concrete class, and changing types into type parameters one at a time until you reach the optimal balance of generalization and usability.
Sikkim Manipal University Page No. 41

DOT Net Technologies

Unit 2

2. Interfaces: An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface, as shown in the following example:

An interface can be a member of a namespace or a class and can contain signatures of the following members:

Methods Properties Indexers Events

An interface can inherit from one or more base interfaces. When a base type list contains a base class and interfaces, the base class must come first in the list. A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.
Sikkim Manipal University Page No. 42

DOT Net Technologies

Unit 2

3. The Delegate Data Type This keyword is used to declare a reference type that can be used to encapsulate a named or an anonymous method. Features of Delegate: Delegates are similar to function pointers in C++. Delegates are type-safe and secure. Delegates are the basis for Events. The declaration syntax of a delegate type is as follows:

A delegate can be instantiated by associating it either with a named or anonymous method. For more information, see Named Methods and Anonymous Methods. For use with named methods, the delegate must be instantiated with a method that has an acceptable signature. For use with anonymous methods, the delegate and the code to be associated with it are declared together. A delegate is a type that refers to a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be invoked like any other method, with parameters and a return value, as in this example:

Any method from any accessible class or struct that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. The method can be either static or an instance method. This makes it possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the signature of the delegate, you can assign your own delegated method.

Sikkim Manipal University

Page No. 43

DOT Net Technologies

Unit 2

This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows for the algorithm to be written in a more general way.

Sikkim Manipal University

Page No. 44

DOT Net Technologies

Unit 2

4. The Object Data Type The object type is an alias for Object in the .NET Framework. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. You can assign values of any type to variables of type object. When a variable of a value type is converted to object, it is said to be boxed. When a variable of type object is converted to a value type, it is said to be unboxed. Example The following sample shows how variables of type object can accept values of any data type and how variables of type object can use methods on Object from the .NET Framework.

Sikkim Manipal University

Page No. 45

DOT Net Technologies

Unit 2

5. The Array Data Type An array is a data structure that contains several variables of the same type. Arrays are declared with a type:

The following examples create single-dimensional, multidimensional, and jagged arrays:

An array has the following properties:


An array can be Single-Dimensional, Multidimensional or Jagged. The default value of numeric array elements are set to zero, and reference elements are set to null.

A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.

Array elements can be of any type, including an array type.


Page No. 46

Sikkim Manipal University

DOT Net Technologies

Unit 2

Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable(T), you can use foreach iteration on all arrays in C#.

6. The string Data type The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework. Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:

This displays "True" and then "False" because the content of the strings are equivalent, but a and b do not refer to the same string instance. The + operator concatenates strings:

This creates a string object that contains "good morning". Strings are immutable -- the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and the variable b continues to hold "h".

Sikkim Manipal University

Page No. 47

DOT Net Technologies

Unit 2

The [] operator can be used to access individual characters of a string:

String literals are of type string and can be written in two forms, quoted and @-quoted. Quoted string literals are enclosed in double quotation marks ("):

String literals can contain any character literal. Escape sequences are included:

This string contains a backslash, the letter f, and new line.

@-quoted string literals start with @ and are also enclosed in double quotation marks. For example:

The advantage of @-quoting is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:

To include a double quotation mark in an @-quoted string, double it:

Sikkim Manipal University

Page No. 48

DOT Net Technologies

Unit 2

Another use of the @ symbol is to use referenced (/reference) identifiers that are C# keywords.

2.4 Control Statements


A statement is a procedural building-block that helps in constructing programs. A statement can be used to: Declare a local variable or constant, Call a method, Create an object, or Assign a value to a variable, property, or field.

Control Statements: The control statements can be used to: Create looping structures (For Example a for loop, a dowhile loop and so on). Make a decision and branch to a new block of code

Statements are usually terminated by a semicolon. A series of statements surrounded by curly braces form a block of code; for example, a set of statements written inside a procedure or function.

Sikkim Manipal University

Page No. 49

DOT Net Technologies

Unit 2

These code blocks often follow a control statement. Variables or constants declared within a code block are only available to statements within the same code block. Example: The following code shows a method block and a code block following a control statement:

Statements in C# (or any language like C, Java, etc.) contain expressions. An expression in C# is a: Fragment of code containing a literal value, A simple name, or An operator and its operands.

Most common expressions, when evaluated, yield a literal value, a variable, or an object property or object indexer access. Whenever a variable, object property or object indexer access is identified from an expression, the value of that item is used as the value of the expression. In C#, an expression can be placed anywhere that a value or object is required as long as the expression ultimately evaluates to the required type. The if Statement It selects a statement for execution based on the value of a Boolean expression.

Sikkim Manipal University

Page No. 50

DOT Net Technologies

Unit 2

Example: A Boolean flag f1 is set to true and checked in the if statement.

To execute more than one statement, multiple statements can be conditionally executed by including them into blocks using {}. Example 1: The user enters a character from the keyboard and the program checks if the input character is an alphabetic character. If so, it checks if it is lowercase or uppercase. In each case, the proper message is displayed.

Sikkim Manipal University

Page No. 51

DOT Net Technologies

Unit 2

The if else Statement

The steps used to carry out the execution of if statements are as follows: 1. The Boolean expression the if statement depends on is first evaluated. 2. If the Boolean expression evaluates to true, control is transferred to the first embedded statement(s). If the control reaches the end point of that statement, control is transferred to the end point of the entire if statement. 3. If the Boolean expression evaluates to false and an else clause is present, control is transferred to the second embedded statement(s). If the control reaches the end point of that statement, control is transferred to the end point of the entire if statement. 4. If the Boolean expression evaluates to false and an else clause is not present, control is transferred to the end point of the entire if statement. The switch-case Statement The switch statement selects a statement list for execution that has a switch label that corresponds to the value of the switch expression.
Sikkim Manipal University Page No. 52

DOT Net Technologies

Unit 2

This statement is a substitute for multiple if statements. Control is transferred to the case statement which matches the value of the switch. The switch statement can include any number of case instances, but no two case statements can have the same value. Execution of the statement body begins at the selected statement and proceeds until the break statement transfers control out of the case body. A jump statement such as a break is required after each case block, including the last block whether it is a case statement or a default statement. With one exception, (unlike the C++ switch statement), C# does not support an implicit fall through from one case label to another. The one exception is if a case statement has no code. If no case expression matches the switch value, then control is transferred to the statement(s) that follow the optional default label. If there is no default label, control is transferred outside the switch. The for Statement The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The for loop is useful for iterating over arrays and for sequential processing.

Sikkim Manipal University

Page No. 53

DOT Net Technologies

Unit 2

In the following example, the value of int i is written to the console and i is incremented every time through the loop by 1.

Example of for statement

All of the expressions of the for statement are optional; The while Statement The while statement executes a statement or a block of statements until a specified expression evaluates to false.

Sikkim Manipal University

Page No. 54

DOT Net Technologies

Unit 2

The do while Statement The do statement executes a statement or a block of statements enclosed in {} repeatedly until a specified expression evaluates to false. Example: In the following example the do-while loop statements execute as long as the variable y is less than 5.

The break Statement The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any. Example In this example, the conditional statement contains a counter that is supposed to count from 1 to 100; however, the break statement terminates the loop after 4 counts

Sikkim Manipal University

Page No. 55

DOT Net Technologies

Unit 2

2.4.8 The continue Statement The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears. Example In this example, a counter is initialized to count from 1 to 10. By using the continue statement in conjunction with the expression (i < 9), the statements between continue and the end of the for body are skipped.

The return Statement The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return an optional value. If the method is a void type, the return statement can be omitted.

2.5 Understanding Properties & Indexes


Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
Sikkim Manipal University Page No. 56

DOT Net Technologies

Unit 2

In this example, the TimePeriod class stores a time period. Internally the class stores the time in seconds, but a property named Hours enables a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.
class TimePeriod { private double seconds;

public double Hours { get { return seconds / 3600; } set { seconds = value * 3600; } } } class Program { static void Main() { TimePeriod t = new TimePeriod(); // Assigning the Hours property causes the 'set' accessor to be called. t.Hours = 24; // Evaluating the Hours property causes the 'get' accessor to be called. System.Console.WriteLine("Time in hours: " + t.Hours); } }

Output Time in hours: 24 Properties Overview

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.

Sikkim Manipal University

Page No. 57

DOT Net Technologies

Unit 2

The value keyword is used to define the value being assigned by the set indexer.

Properties that do not implement a set method are read only.

Using Properties Properties combine aspects of both fields and methods. To the user of an object, a property appears to be a field, accessing the property requires the same syntax. To the implementer of a class, a property is one or two code blocks, representing a get accessor and/or a set accessor. The code block for the get accessor is executed when the property is read; the code block for the set accessor is executed when the property is assigned a new value. A property without a set accessor is considered read-only. A property without a get accessor is considered write-only. A property that has both accessors is read-write. Unlike fields, properties are not classified as variables. Therefore, you cannot pass a property as a ref (C# Reference) or out (C# Reference) parameter. Properties have many uses: they can validate data before allowing a change; they can transparently expose data on a class where that data is actually retrieved from some other source, such as a database; they can take an action when data is changed, such as raising an event, or changing the value of other fields. Properties are declared in the class block by specifying the access level of the field, followed by the type of the property, followed by the name of the property, and followed by a code block that declares a get-accessor and/or a set accessor.

Sikkim Manipal University

Page No. 58

DOT Net Technologies

Unit 2

Example
public class Date { private int month = 7; //"backing store" public int Month { get { return month; } set { if ((value > 0) && (value < 13)) { month = value; } } } }

In this example, Month is declared as a property so that the set accessor can make sure that the Month value is set between 1 and 12. The Month property uses a private field to track the actual value. The real location of a property's data is often referred to as the property's "backing store." It is common for properties to use private fields as a backing store. The field is marked private in order to make sure that it can only be changed by calling the property. The get Accessor The body of the get accessor resembles that of a method. It must return a value of the property type. The execution of the get accessor is equivalent to reading the value of the field. For example, when you are returning the private variable from the get accessor and optimizations are enabled, the call to the get accessor method is in lined by the compiler so there is no method-call overhead. However, a virtual get accessor method cannot be in lined because the compiler does not know at compile-time which method
Sikkim Manipal University Page No. 59

DOT Net Technologies

Unit 2

may actually be called at run time. The following is a get accessor that returns the value of a private field name:
class Person { private string name; // the name field public string Name // the Name property { get { return name; } } }

When you reference the property, except as the target of an assignment, the get accessor is invoked to read the value of the property. Example:
Person p1 = new Person(); //... System.Console.Write(p1.Name); // the get accessor is invoked here

The get accessor must end in a return or throw statement, and control cannot flow off the accessor body. It is a bad programming style to change the state of the object by using the get accessor. Example: The following accessor produces the side effect of changing the state of the object every time that the number field is accessed.
private int number; public int Number { get { return number++; // Don't do this } } Sikkim Manipal University Page No. 60

DOT Net Technologies

Unit 2

The get accessor can be used to return the field value or to compute it and return it. Example:
class Employee { private string name; public string Name { get { return name != null ? name : "NA"; } } }

In the previous code segment, if you do not assign a value to the Name property, it will return the value NA. Set Accessor The set accessor resembles a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property. In the following example, a set accessor is added to the Name property:
class Person { private string name; // the name field public string Name // the Name property { get { return name; } set { name = value; } } }

Sikkim Manipal University

Page No. 61

DOT Net Technologies

Unit 2

When you assign a value to the property, the set accessor is invoked by using an argument that provides the new value. Example
Person p1 = new Person(); p1.Name = "Joe"; // the set accessor is invoked here System.Console.Write(p1.Name); // the get accessor is invoked here

It is an error to use the implicit parameter name, value, for a local variable declaration in a set accessor.

2.6 Using Delegates and Events


An event is a message sent by an object to signal the occurrence of an action. The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic. The object that raises the event is called the event sender. The object that captures the event and responds to it is called the event receiver. In event communication, the event sender class does not know which object or method will receive (handle) the events it raises. What is needed is an intermediary (or pointer-like mechanism) between the source and the receiver. The .NET Framework defines a special type (Delegate) that provides the functionality of a function pointer. A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a typesafe function pointer or a callback. While delegates have other uses, the discussion here focuses on the event handling functionality of delegates. A delegate declaration is sufficient to define a delegate class. The declaration supplies the signature of the delegate, and the common language runtime

Sikkim Manipal University

Page No. 62

DOT Net Technologies

Unit 2

provides the implementation. The following example shows an event delegate declaration.

The syntax is similar to that of a method declaration; however, the delegate keyword informs the compiler that AlarmEventHandler is a delegate type. By convention, event delegates in the .NET Framework have two parameters, the source that raised the event and the data for the event. An instance of the AlarmEventHandler delegate can bind to any method that matches its signature, such as the AlarmRang method of the WakeMeUp class shown in the following example.
C# Code public class WakeMeUp { // AlarmRang has the same signature as AlarmEventHandler. public void AlarmRang(object sender, AlarmEventArgs e) {...}; ... }

Custom event delegates are needed only when an event generates event data. Many events, including some user-interface events such as mouse clicks, do not generate event data. In such situations, the event delegate provided in the class library for the no-data event, System.EventHandler, is adequate. Its declaration follows.

C# Code
delegate void EventHandler(object sender, EventArgs e); Event delegates are multicast, which means that they can hold references to more than one event handling method. Delegates allow for flexibility and fine-grain control in event handling. A delegate acts as an event dispatcher
Sikkim Manipal University Page No. 63

DOT Net Technologies

Unit 2

for the class that raises the event by maintaining a list of registered event handlers for the event.

Using Delegates
A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are objectoriented, type safe, and secure. The type of a delegate is defined by the name of the delegate. The following example declares a delegate named Del that can encapsulate a method that takes a string as an argument and returns void:

C# Code
public delegate void Del(string message);

A delegate object is normally constructed by providing the name of the method the delegate will wrap, or with an anonymous Method. Once a delegate is instantiated, a method call made to the delegate will be passed by the delegate to that method. The parameters passed to the delegate by the caller are passed to the method, and the return value, if any, from the method is returned to the caller by the delegate. This is known as invoking the delegate. An instantiated delegate can be invoked as if it were the wrapped method itself. For example:
C# Code // Create a method for a delegate. public static void DelegateMethod(string message) { System.Console.WriteLine(message); } // Instantiate the delegate. Del handler = DelegateMethod; // Call the delegate. handler("Hello World");

Sikkim Manipal University

Page No. 64

DOT Net Technologies

Unit 2

Delegate types are derived from the Delegate class in the .NET Framework. Delegate types are sealed they cannot be derived from and it is not possible to derive custom classes from Delegate. Because the instantiated delegate is an object, it can be passed as a parameter, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later time. This is known as an asynchronous callback, and is a common method of notifying a caller when a long process has completed. When a delegate is used in this fashion, the code using the delegate does not need any knowledge of the implementation of the method being used. The functionality is similar to the encapsulation interfaces provide. Another common use of callbacks is defining a custom comparison method and passing that delegate to a sort method. It allows the caller's code to become part of the sort algorithm. The following example method uses the Del type as a parameter:
C# Code public void MethodWithCallback(int param1, int param2, Del callback) { callback("The number is: " + (param1 + param2).ToString()); }

You can then pass the delegate created above to that method:
C# Code MethodWithCallback(1, 2, handler);

and receive the following output to the console: The number is: 3 Using the delegate as an abstraction, MethodWithCallback does not need to call the console directly it does not have to be designed with a console in mind. What MethodWithCallback does is simply prepare a string and pass

Sikkim Manipal University

Page No. 65

DOT Net Technologies

Unit 2

the string to another method. This is especially powerful since a delegated method can use any number of parameters. When a delegate is constructed to wrap an instance method, the delegate references both the instance and the method. A delegate has no knowledge of the instance type aside from the method it wraps, so a delegate can refer to any type of object as long as there is a method on that object that matches the delegate signature. When a delegate is constructed to wrap a static method, it only references the method. Consider the following declarations: C# Code public class MethodClass { public void Method1(string message) { } public void Method2(string message) { } } Along with the static DelegateMethod shown previously, we now have three methods that can be wrapped by a Del instance. A delegate can call more than one method when invoked. This is referred to as multicasting. To add an extra method to the delegate's list of methods the invocation list simply requires adding two delegates using the addition or addition assignment operators ('+' or '+='). For example:
C# Code MethodClass obj = new MethodClass(); Del d1 = obj.Method1; Del d2 = obj.Method2; Del d3 = DelegateMethod; //Both types of assignment are valid. Del allMethodsDelegate = d1 + d2; allMethodsDelegate += d3;

Sikkim Manipal University

Page No. 66

DOT Net Technologies

Unit 2

At this point allMethodsDelegate contains three methods in its invocation list Method1, Method2, and DelegateMethod. The original three delegates, d1, d2, and d3, remain unchanged. When allMethodsDelegate is invoked, all three methods are called in order. If the delegate uses reference parameters, the reference is passed sequentially to each of the three methods in turn, and any changes by one method are visible to the next method. When any of the methods throws an exception that is not caught within the method, that exception is passed to the caller of the delegate and no subsequent methods in the invocation list are called. If the delegate has a return value and/or out parameters, it returns the return value and parameters of the last method invoked. To remove a method from the invocation list, use the decrement or decrement assignment operator ('-' or '='). For example: C# Code //remove Method1 allMethodsDelegate -= d1; // copy AllMethodsDelegate while removing d2 Del oneMethodDelegate = allMethodsDelegate - d2; Because delegate types are derived from System.Delegate, the methods and properties defined by that class can be called on the delegate. For example, to find the number of methods in a delegate's invocation list, you may write: C# Code int invocationCount = d1.GetInvocationList().GetLength(0); Delegates with more than one method in their invocation list derive from MulticastDelegate, which is a subclass of System.Delegate. The above code works in either case because both classes support GetInvocationList.
Sikkim Manipal University Page No. 67

DOT Net Technologies

Unit 2

Multicast delegates are used extensively in event handling. Event source objects send event notifications to recipient objects that have registered to receive that event. To register for an event, the recipient creates a method designed to handle the event, then creates a delegate for that method and passes the delegate to the event source. The source calls the delegate when the event occurs. The delegate then calls the event handling method on the recipient, delivering the event data. The delegate type for a given event is defined by the event source. Comparing delegates of two different types assigned at compile-time will result in a compilation error. If the delegate instances are statically of the type System.Delegate, then the comparison is allowed, but will return false at run time. For example:
C# Code delegate void Delegate1(); delegate void Delegate2(); static void method(Delegate1 d, Delegate2 e, System.Delegate f) { // Compile-time error. //Console.WriteLine(d == e); // OK at compile-time. False if the run-time type of f //is not the same as that of d. System.Console.WriteLine(d == f); }

Events
Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers. In a typical C# Windows Forms or Web application, you subscribe to events raised by controls such as buttons and list boxes. You can use the Visual
Sikkim Manipal University Page No. 68

DOT Net Technologies

Unit 2

C# integrated development environment (IDE) to browse the events that a control publishes and select the ones that you want to handle. The IDE automatically adds an empty event handler method and the code to subscribe to the event. Events Overview Events have the following properties: The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event. An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers. Events that have no subscribers are never called. Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces. When an event has multiple subscribers, the event handlers are invoked synchronously

when

an

event

is

raised.

To

invoke

events

asynchronously, see Calling Synchronous Methods Asynchronously. Events can be used to synchronize threads. In the .NET Framework class library, events are based on the EventHandler delegate and the EventArgs base class.

2.7 Exception Handling


C#, like many object-oriented languages, handles errors and abnormal conditions with exceptions. An exception is an object that encapsulates information about an unusual program occurrence. It is important to distinguish between bugs, errors, and exceptions. A bug is a programmer mistake that should be fixed before the code is shipped. Exceptions are not a protection against bugs. Although a bug might cause an exception to be thrown, you should not rely on exceptions to handle your bugs. Rather, you should fix the bug.
Sikkim Manipal University Page No. 69

DOT Net Technologies

Unit 2

An error is caused by user action. For example, the user might enter a number where a letter is expected. Once again, an error might cause an exception, but you can prevent that by catching errors with validation code. Whenever possible, errors should be anticipated and prevented. Even if you remove all bugs and anticipate all user errors, you will still run into predictable but unpreventable problems, such as running out of memory or attempting to open a file that no longer exists. You cannot prevent exceptions, but you can handle them so that they do not bring down your program. When your program encounters an exceptional circumstance, such as running out of memory, it throws (or "raises") an exception. When an exception is thrown, execution of the current function halts and the stack is unwound until an appropriate exception handler is found. This means that if the currently running function does not handle the exception, the current function will terminate and the calling function will get a chance to handle the exception. If none of the calling functions handles it, the exception will ultimately be handled by the CLR, which will abruptly terminate your program. An Exception Handler is a block of code designed to handle the exception you've thrown. Exception handlers are implemented as catch statements. Ideally, if the exception is caught and handled, the program can fix the problem and continue. Even if your program can't continue, by catching the exception you have an opportunity to print a meaningful error message and terminate gracefully. If there is code in your function that must run regardless of whether an exception is encountered (e.g., to release resources you've allocated), you can place that code in a finally block, where it is certain to run, even in the presence of exceptions.
Sikkim Manipal University Page No. 70

DOT Net Technologies

Unit 2

Throwing and Catching Exceptions In C#, you can throw only objects of type System.Exception, or objects derived from that type. The CLR System namespace includes a number of exception types that can be used by your program. These exception types include ArgumentNullException, InvalidCastException, and

OverflowException, as well as many others. The throw Statement To signal an abnormal condition in a C# class, you throw an exception. To do this, use the keyword throw. This line of code creates a new instance of System.Exception and then throws it: C# Code throw new System.Exception( ); Throwing an exception immediately halts execution while the CLR searches for an exception handler. If an exception handler cannot be found in the current method, the runtime unwinds the stack, popping up through the calling methods until a handler is found. If the runtime returns all the way through Main( ) without finding a handler, it terminates the program.
Example: Throwing an Exception using System; public class Test { public static void Main( ) { Console.WriteLine("Enter Main..."); Test t = new Test( ); t.Func1( ); Console.WriteLine("Exit Main..."); }

Sikkim Manipal University

Page No. 71

DOT Net Technologies

Unit 2

Example: Continued
public void Func1( ) { Console.WriteLine("Enter Func1..."); Func2( ); Console.WriteLine("Exit Func1..."); } public void Func2( ) { Console.WriteLine("Enter Func2..."); throw new System.Exception( ); Console.WriteLine("Exit Func2..."); } } Output: Enter Main... Enter Func1... Enter Func2... Exception occurred: System.Exception: An exception of type System.Exception was thrown. at Programming_CSharp.Test.Func2( ) in ...exceptions01.cs:line 26 at Programming_CSharp.Test.Func1( ) in ...exceptions01.cs:line 20 at Programming_CSharp.Test.Main( ) in ...exceptions01.cs:line 12 This simple example writes to the console as it enters and exits each method. Main( ) creates an instance of type Test and call Func1( ). After printing out the Enter Func1 message, Func1( ) immediately calls Func2( ). Func2( ) prints out the first message and throws an object of type System.Exception. Execution immediately stops, and the CLR looks to see if there is a handler in Func2( ).
Sikkim Manipal University Page No. 72

DOT Net Technologies

Unit 2

There is not, and so the runtime unwinds the stack (never printing the exit statement) to Func1( ). Again, there is no handler, and the runtime unwinds the stack back to Main( ). With no exception handler there, the default handler is called, which prints the error message. The catch Statement In C#, an exception handler is called a catch block and is created with the catch keyword. In the example given below, the throw statement is executed within a try block, and a catch block is used to announce that the error has been handled. using System; public class Test { public static void Main( ) { Console.WriteLine("Enter Main..."); Test t = new Test( ); t.Func1( ); Console.WriteLine("Exit Main..."); } public void Func1( ) { Console.WriteLine("Enter Func1..."); Func2( ); Console.WriteLine("Exit Func1..."); }

Sikkim Manipal University

Page No. 73

DOT Net Technologies

Unit 2

public void Func2( ) { Console.WriteLine("Enter Func2..."); try { Console.WriteLine("Entering try block..."); throw new System.Exception( ); Console.WriteLine("Exiting try block..."); } catch { Console.WriteLine( "Exception caught and handled."); } Console.WriteLine("Exit Func2..."); } } Output: Enter Main... Enter Func1... Enter Func2... Entering try block... Exception caught and handled. Exit Func2... Exit Func1... Exit Main...

You would typically put the try block around a potentially "dangerous" statement, such as accessing a file, allocating memory, and so forth. Following the try statement is a generic catch statement. The catch statement is generic because you haven't specified what kind of exceptions to catch. In this case, the statement will catch any exceptions that are thrown.

Sikkim Manipal University

Page No. 74

DOT Net Technologies

Unit 2

Taking Corrective Action In the above example, the catch statement simply reports that the exception has been caught and handled. In a real-world example, you might take corrective action to fix the problem that caused an exception to be thrown. For example, if the user is trying to open a read-only file, you might invoke a method that allows the user to change the attributes of the file. If the program has run out of memory, you might give the user an opportunity to close other applications. If all others fail, the catch block can print an error message so that the user come to know what had gone wrong. Unwinding the call stack Examine the output of Example above carefully. You see the code enter Main( ), Func1( ), Func2( ), and the try block. You never see it exit the try block, though it does exit Func2( ), Func1( ), and Main( ). What happened? When the exception is thrown, execution halts immediately and is handed to the catch block. It never returns to the original code path. It never gets to the line that prints the exit statement for the try block. The catch block handles the error, and then execution falls through to the code following catch. Without catch the call stack unwinds, but with catch it does not unwind as a result of the exception. The exception is now handled; there are no more problems and the program continues. This becomes a bit clearer if you move the try/catch blocks up to Func1( ), as shown in Example below:

Sikkim Manipal University

Page No. 75

DOT Net Technologies

Unit 2

using System; public class Test { public static void Main( ) { Console.WriteLine("Enter Main..."); Test t = new Test( ); t.Func1( ); Console.WriteLine("Exit Main..."); } public void Func1( ) { Console.WriteLine("Enter Func1..."); try { Console.WriteLine("Entering try block..."); Func2( ); Console.WriteLine("Exiting try block..."); } catch { Console.WriteLine( "Exception caught and handled."); } Console.WriteLine("Exit Func1..."); }

public void Func2( ) { Console.WriteLine("Enter Func2..."); throw new System.Exception( ); Console.WriteLine("Exit Func2..."); } } Output: Enter Main... Enter Func1... Entering try block... Enter Func2... Exception caught and handled. Exit Func1... Exit Main...

Sikkim Manipal University

Page No. 76

DOT Net Technologies

Unit 2

This time the exception is not handled in Func2( ); it is handled in Func1( ). When Func2( ) is called, it prints the Enter statement and then throws an exception. Execution halts and the runtime looks for a handler, but there isn't one. The stack unwinds, and the runtime finds a handler in Func1( ). The catch statement is called, and execution resumes immediately following the catch statement, printing the Exit statement for Func1( ) and then for Main( ). Make sure you are comfortable with why the Exiting Try Block statement and the Exit Func2 statement are not printed. This is a classic case where putting the code into a debugger and then stepping through it can make things very clear. Creating dedicated catch statements So far, you've been working only with generic catch statements. You can create dedicated catch statements that handle only some exceptions and not others, based on the type of exception thrown. Example below illustrates how to specify which exception you'd like to handle. using System; public class Test { public static void Main( ) { Test t = new Test( ); t.TestFunc( ); } // try to divide two numbers // handle possible exceptions

Sikkim Manipal University

Page No. 77

DOT Net Technologies

Unit 2

public void TestFunc( ) { try { double a = 5; double b = 0; Console.WriteLine ("{0} / {1} = {2}", a, b, DoDivide(a,b)); } // most derived exception type first catch (System.DivideByZeroException) { Console.WriteLine( "DivideByZeroException caught!"); } catch (System.ArithmeticException) { Console.WriteLine( "ArithmeticException caught!"); } // generic exception type last catch { Console.WriteLine("Unknown exception caught"); } } // do the division if legal public double DoDivide(double a, double b) { if (b == 0) throw new System.DivideByZeroException( ); if (a == 0) throw new System.ArithmeticException( ); return a/b; } } } Output: DivideByZeroException caught!

In this example, the DoDivide( ) method will not let you divide zero by another number, nor will it let you divide a number by zero. It throws an instance of DivideByZeroException if you try to divide by zero. If you try to divide zero by another number, there is no appropriate exception -- dividing zero by another number is a legal mathematical operation and shouldn't
Sikkim Manipal University Page No. 78

DOT Net Technologies

Unit 2

throw an exception at all. For the sake of this example, assume you don't want to allow division by zero; you will throw an ArithmeticException. When the exception is thrown, the runtime examines each exception handler in order and matches the first one it can. When you run this with a=5 and b=7, the output is: 5 / 7 = 0.7142857142857143 As you'd expect, no exception is thrown. However, when you change the value of a to 0, the output is: ArithmeticException caught! The exception is thrown, and the runtime examines the first exception, DivideByZeroException. Because this does not match, it goes on to the next handler, ArithmeticException, which does match. In a final pass through, suppose you change a to 7 and b to 0. This throws the DivideByZeroException. It is possible to distribute your try/catch statements, catching some specific exceptions in one function and more generic exceptions in higher, calling functions. Your design goals should dictate the exact design. Assume you have a method A that calls another method B, which in turn calls method C. Method C calls method D, which then calls method E. Method E is deep in your code; methods B and A are higher up. If you anticipate that method E might throw an exception, you should create a try/catch block deep in your code to catch that exception as close as possible to the place where the problem arises. You might also want to create more general exception handlers higher up in the code in case unanticipated exceptions slip by.

The finally Statement


In some instances, throwing an exception and unwinding the stack can create a problem. For example, if you have opened a file or otherwise committed a resource, you might need an opportunity to close the file or flush the buffer.

Sikkim Manipal University

Page No. 79

DOT Net Technologies

Unit 2

In the event, however, that there is some action you must take regardless of whether an exception is thrown, such as closing a file, you have two strategies to choose from. One approach is to enclose the dangerous action in a try block and then to close the file in both the catch and try blocks. However, this is an ugly duplication of code, and it's error prone. C# provides a better alternative in the finally block. The code in the finally block is guaranteed to be executed regardless of whether an exception is thrown. The TestFunc( ) method in Example below simulates opening a file as its first action. The method undertakes some mathematical operations, and the file is closed. It is possible that some time between opening and closing the file an exception will be thrown. If this were to occur, it would be possible for the file to remain open. The developer knows that no matter what happens, at the end of this method the file should be closed, so the file close function call is moved to a finally block, where it will be executed regardless of whether an exception is thrown.

Sikkim Manipal University

Page No. 80

DOT Net Technologies

Unit 2

catch { Console.WriteLine("Unknown exception caught"); } finally { Console.WriteLine ("Close file here."); }}}} // do the division if legal public double DoDivide(double a, double b) { if (b == 0) throw new System.DivideByZeroException( ); if (a == 0) throw new System.ArithmeticException( ); return a/b; } Output: Open file here DivideByZeroException caught! Close file here. Output when b = 12: Open file here 5 / 12 = 0.416666666666667 This line may or may not print Close file here.

In this example, one of the catch blocks has been eliminated to save space and a finally block has been added. Whether or not an exception is thrown, the finally block is executed, and so in both output examples you see the message: Close file here.

2.8 Summary
This unit makes the user familiar with the Microsoft language developed especially for .Net Application development. It has the major features like Object-orientation, interoperability, and component development. It is a language developed on the lines of Visual Basic. It takes advantage of the Common Language Runtime of .Net environment. It takes the reader a
Sikkim Manipal University Page No. 81

DOT Net Technologies

Unit 2

walkthrough regarding the features of C# language. It shows a step-by-step approach in developing programs using C#. It introduces the data types of C# and code samples illustrating their usage. It then illustrates the control statements and their applications with respect to C# programming language. It then introduces the concept of properties and indexes, and then continues with Delegates and Events of C#. Self Assessment Questions 1. The _______ language is an Object Oriented Programming Language developed by Microsoft to become a key part of their .Net software development platform. a) C++ b) Visual C++ c) C# d) Visual Basic.Net

2. The syntax for compiling the sample C# program is _______ 3. To run a C# executable file, the command that should be typed at the command prompt is _________ 4. The using directive references a namespace called System, provided by the ________________, a synonym for the .Net Framework. 5. Classes can also be defined as ______ by using type parameters that enable client code to customize the class in a type-safe and efficient manner. 6. A _______ modifier is used so that the method it is assigned to becomes a method of the class rather than an instance of the class. 7. The ________ directive allows the use of types in a namespace so that you do not have to qualify the use of a type in that namespace. 8. The Struct and Enumeration in C# are of _________ data types a) int b) value c) char d) string

9. Using the ______ operator calls the default constructor of the specific type and assigns the default value to the variable.

Sikkim Manipal University

Page No. 82

DOT Net Technologies

Unit 2

2.9 Terminal Questions


1. Describe the steps involved in compiling and executing a C# program. (Refer to 2.2) 2. Describe the steps involved in creating classes and objects with the help of a program in C#. (Refer to 2.2) 3. Write a program to demonstrate the usage of if statements (Refer to 2.4) 4. Write a program to demonstrate exception handling in C# (Refer to 2.7)

2.10 Answers to Self Assessment Questions


1. c 2. csc.exe <filename>.cs 3. <filename>.exe 4. Common Language Infrastructure (CLI ) 5. generic 6. static 7. using 8. b 9. new

Sikkim Manipal University

Page No. 83

DOT Net Technologies

Unit 3

Unit 3
Structure: 3.1 Introduction Objectives 3.2 3.3 3.4 3.5 3.6

Building Windows and Web Forms

Creating a Simple Windows Form Developing Web Forms: An introduction Web Form Life Cycle Creating a Web Form Summary Self Assessment Questions

3.7 3.8

Terminal Questions Answers to Terminal Questions

3.1 Introduction
The previous chapters have used console applications to demonstrate C# and the Common Language Runtime. Although console applications can be implemented simply, it is time to turn your attention to the reason you're learning the C# language in the first place: building Windows and web applications. In the early days of Windows computing, an application ran on a desktop, in splendid isolation. Over time, developers found it beneficial to spread their applications across a network, with the user interface on one computer and a database on another. This division of responsibilities or partitioning of an application came to be called two-tier or client-server application development. Later three-tier or n-tier approaches emerged as developers began to use web servers to host business objects that could handle the database access on behalf of clients.

Sikkim Manipal University

Page No. 84

DOT Net Technologies

Unit 3

When the Web first came along, there was a clear distinction between Windows applications and web applications. Windows applications ran on the desktop or a local area network (LAN), and web applications ran on a distant server and were accessed by a browser. This distinction is now being blurred as Windows applications reach out to the Web for services. Many new applications consist of logic running on a client, a database server, and remote third-party computers located on the Web. Traditional desktop applications such as Excel or Outlook are now able to integrate data retrieved through web connections seamlessly, and web applications can distribute some of their processing to client-side components. The primary remaining distinction between a Windows application and a web application might be this: Who owns the user interface? Will your application use a browser to display its user interface, or Will the UI be built into the executable running on the desktop? There are enormous advantages to web applications, starting with the obvious: they can be accessed from any browser that can connect to the server. In addition, updates can be made at the server, without the need to distribute new dynamic link libraries (DLLs) to your customers. On the other hand, if your application derives no benefit from being on the Web, you might find that you can achieve greater control over the look and feel of your application or that you can achieve better performance by building a desktop application. .NET offers closely related, but distinguishable, suites of tools for building Windows or web applications. Both are based on forms, with the premise that many applications have user interfaces centered on interacting with the user through forms and controls, such as buttons, list boxes, text, and so forth.

Sikkim Manipal University

Page No. 85

DOT Net Technologies

Unit 3

The tools for creating web applications are called Web Forms. The tools for creating Windows applications are called Windows Forms. In the following pages, you will learn how to create a simple Windows Form using either a text editor such as Notepad or the Design tool in Visual Studio .NET. Next you will build a more complex Windows application using Visual Studio, the Windows Forms framework, and a number of C# programming techniques you learned in earlier units. Objectives: This unit is an extension of command based C# programming and highlights the window based and web based form development. At the end of this unit, the student would be able to: Create a simple windows form Develop web based forms Describe the Web form life cycle

3.2 Creating a Simple Windows Form


A Windows Form is a tool for building a Windows application. The .NET Framework offers extensive support for Windows application development, the centerpiece of which is the Windows Forms framework. Not surprisingly, Windows Forms use the metaphor of a form. This idea was borrowed from the wildly successful Visual Basic (VB) environment and supports Rapid Application Development (RAD). Arguably, C# is the first development environment to marry the RAD tools of Visual Basic with the object-oriented and high performance characteristics of a C-family language. Using Notepad Visual Studio .NET provides a rich set of drag-and-drop tools for working with Windows Forms. It is possible to build a Windows application without using the Visual Studio Integrated Development Environment (IDE), but it is
Sikkim Manipal University Page No. 86

DOT Net Technologies

Unit 3

far more painful and takes a lot longer. However, just to prove the point, you'll use Notepad to create a simple Windows Form application that displays text in a window and implements a Cancel button. The application display is shown in Figure 3.1.

Figure 3.1: The hand-drawn Windows Form

You start by adding a using statement for the Windows Forms namespace: using System.Windows.Forms; The key to create a Windows Form application is to derive your form from System.Windows.Forms.Form: public class HandDrawnClass : Form The Form object represents any window displayed in your application. You can use the Form class to create standard windows, as well as floating windows, tools, dialog boxes, and so forth. All the Windows widgets you'll need (labels, buttons, list boxes, etc.) are found within the Windows.Forms namespace. In the IDE, you'll be able to drag and drop these objects onto a designer, but for now you'll declare them right in your program code. To get started, declare the two widgets you need, a label to hold the Hello World text, and a button to exit the application: private System.Windows.Forms.Label lblOutput; private System.Windows.Forms.Button btnCancel; You're now ready to instantiate these objects, which is done in the Form's constructor: this.lblOutput = new System.Windows.Forms.Label( );
Sikkim Manipal University Page No. 87

DOT Net Technologies

Unit 3

this.btnCancel = new System.Windows.Forms.Button( ); Next you can set the Form's title text to Hello World: this.Text = "Hello World"; Set the label's location, text, and size: lblOutput.Location = new System.Drawing.Point (16, 24); lblOutput.Text = "Hello World!"; lblOutput.Size = new System.Drawing.Size (216, 24); The location is expressed as a System.Drawing.Point object, whose constructor takes a horizontal and vertical position. The size is set with a Size object, whose constructor takes a pair of integers that represent the width and height of the object. Next, do the same for the button object, setting its location, size, and text: btnCancel.Location = new System.Drawing.Point (150,200); btnCancel.Size = new System.Drawing.Size (112, 32); btnCancel.Text = "&Cancel"; The button also needs an event handler. Events (in this case the cancel button-click event) are implemented using delegates. The publishing class (Button) defines a delegate (System.EventHandler) that the subscribing class (your form) must implement. The delegated method can have any name but must return void and take two parameters: an object (sender) and a SystemEventArgs object, typically named e: protected void btnCancel_Click ( object sender, System.EventArgs e) { //... }

Sikkim Manipal University

Page No. 88

DOT Net Technologies

Unit 3

Register your event-handler method in two steps. First, create a new System.EventHandler delegate, passing in the name of your method as a parameter: new System.EventHandler (this.btnCancel_Click); Then add that delegate to the button's click event-handler list with the += operator. The following line combines these steps into one: btnCancel.Click += new System.EventHandler (this.btnCancel_Click); Now you must set up the form's dimensions. The form property AutoScaleBaseSize sets the base size used at display time to compute the scaling factor for the form. The ClientSize property sets the size of the form's client area, which is the size of the form excluding borders and titlebar. (When you use the designer, these values are provided for you interactively.): this.AutoScaleBaseSize = new System.Drawing.Size (5, 13); this.ClientSize = new System.Drawing.Size (300, 300); Finally, remember to add the widgets to the form: this.Controls.Add (this.btnCancel); this.Controls.Add (this.lblOutput); Having registered the event handler, you must supply the implementation. For this example, clicking Cancel will exit the application, using the static method Exit( ) of the Application class: protected void btnCancel_Click ( object sender, System.EventArgs e) { Application.Exit ( ); } That's it; you just need an entry point to invoke the constructor on the form: public static void Main( ) {
Sikkim Manipal University Page No. 89

DOT Net Technologies

Unit 3

Application.Run(new HandDrawnClass( )); } The complete source is shown in Example 13-1. When you run this application, the window is opened and the text is displayed. Pressing Cancel closes the application.

Sikkim Manipal University

Page No. 90

DOT Net Technologies this.Controls.Add (this.btnCancel); this.Controls.Add (this.lblOutput); } // handle the cancel event protected void btnCancel_Click ( object sender, System.EventArgs e) { Application.Exit( ); } // Run the app public static void Main( ) { Application.Run(new HandDrawnClass( )); } } }

Unit 3

Using the Visual Studio .Net Designer Although hand coding is always a great fun, it involves a lot of work, and the result in the previous example is not as elegant as most programmers would expect. The Visual Studio IDE provides a design tool for Windows Forms that is much easier to use. To begin work on a new Windows application, first open Visual Studio and choose New Project. In the New Project window, create a new C# Windows application and name it ProgCSharpWindowsForm, as shown in Figure 3.2.

Figure 3.2: Creating a Windows Form application Sikkim Manipal University Page No. 91

DOT Net Technologies

Unit 3

Visual Studio responds by creating a Windows Form application, and, best of all, putting you into a design environment, as shown in Figure 3.3.

Figure 3.3: The Design Environment

The Design window displays a blank Windows Form (Form1). A Toolbox window is also available, with a selection of Windows widgets and controls. If the Toolbox is not displayed, try clicking the word "Toolbox," or select View Toolbox on the Visual Studio menu. You can also use the keyboard shortcut Ctrl-Alt-X to display the Toolbox. With the Toolbox displayed, you can drag a label and a button directly onto the form, as shown in Figure 3.4.

Sikkim Manipal University

Page No. 92

DOT Net Technologies

Unit 3

Figure 3.4: The Windows Form development environment

The Toolbox is filled with controls that you can add to your Windows Form application. In the upper-right corner you should see the Solution Explorer, which is a window that displays all the files in your projects. In the lowerright corner is the Properties window, which displays all the properties of the currently selected item. In Figure 3.4, the label (label1) is selected, and the Properties window displays its properties. You can use the Properties window to set the static properties of the various controls. For example, to add text to label1, you can type the words "Hello World" into the box to the right of its Text property. If you want to change the font for the lettering in the HelloWorld label, click the Font property shown in the lower-right corner of Figure 3.5. (You can provide text in the same way

Sikkim Manipal University

Page No. 93

DOT Net Technologies

Unit 3

for your button (button1) by selecting it in the Property window and typing the word "Cancel" into its Text property.)

Figure 3.5: Modifying the font

Once you have the form laid out the way you want, all that remains is to create an event handler for the Cancel button. Double-clicking the Cancel button will create the event handler, register it, and put you on the codebehind page (the page that holds the source code for this form), in which you can enter the event-handling logic, as shown in Figure 3.6.

Sikkim Manipal University

Page No. 94

DOT Net Technologies

Unit 3

Figure 3.6

The cursor is already in place; you have to enter only the one line of code: Application.Exit( ); Visual Studio .NET generates all the code necessary to create and initialize the components, except the one line of code for the Cancel button click event as shown below: this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); The form derives from System.Windows.Forms.Form. The widgets are defined as: public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Label lblOutput; private System.Windows.Forms.Button btnCancel;
Sikkim Manipal University Page No. 95

DOT Net Technologies

Unit 3

The designer creates a private container variable for its own use: private System.ComponentModel.Container components = null; In this and in every Windows Form application generated by Visual Studio .NET, the constructor calls a private method, InitializeComponent( ). This is used to define and set the properties of all the controls. The properties are set based on the values you've chosen (or on the default values you've left alone) in the designer. The InitializeComponent( ) method is marked with a comment that you should not modify the contents of this method; making changes to this method might confuse the designer.

3.3 Developing Web Forms: An introduction


Rather than writing traditional Windows desktop and client-server applications, more and more developers are now writing web-based applications, even when their software is for desktop use. The following are many obvious advantages: 1. You do not have to create as much of the user interface; you can let Internet Explorer and Netscape Navigator handle a lot of it for you. 2. Another, perhaps bigger advantage is that distribution of revisions is faster, easier, and less expensive. 3. Distributed processing: With a web-based application, it is far easier to provide server-side processing. The Web provides standardized protocols (e.g., HTTP, HTML, and XML) to facilitate building n-tier applications. The .NET technology for building web applications (and dynamic web sites) is ASP.NET, which provides a rich collection of types for building web applications in its System.Web and System.Web.UI namespaces. In this unit, the focus is on where ASP.NET and C# programming intersect: the creation of Web Forms.

Sikkim Manipal University

Page No. 96

DOT Net Technologies

Unit 3

Web Forms bring Rapid Application Development (RAD) techniques (such as those used in Windows Forms) to the development of web applications. As with Windows Forms, drag and drop controls onto a form and write the supporting code either inline or in code-behind pages. With Web Forms, however, the application is deployed to a web server, and users interact with the application through a standard browser. Understanding Web Forms Web Forms implement a programming model in which web pages are dynamically generated on a web server for delivery to a browser over the Internet. They are, in some ways, the successor to ASP pages, and they marry ASP technology with traditional programming. With Web Forms, you create an HTML page with static content, and you write C# code to generate dynamic content. The C# code runs on the server, and the data produced is integrated with your static HTML to create the web page. What is sent to the browser is standard HTML. Web Forms are designed to run on any browser, with the server rendering the correct browser-compliant HTML. You can do the programming for the logic of the Web Form in any .NET language. We will use C#, which is arguably the language of choice, though some ASP developers who have used VBScript might opt for VB.NET. Just as with Windows Forms, you can create Web Forms in Notepad (or another editor of your choice) rather than in Visual Studio. Many developers will choose to do so, but Visual Studio makes the process of designing and testing Web Forms much easier. Web Forms divide the user interface into two parts: the visual part or user interface (UI), and the logic that lies behind it. But with Web Forms the UI page and the code are in separate files.

Sikkim Manipal University

Page No. 97

DOT Net Technologies

Unit 3

The UI page is stored in a file with the extension .aspx. The logic (code) for that page can be stored in a separate code-behind C# source file. When you run the form, the code-behind class file runs and dynamically creates the HTML sent to the client browser. This code makes use of the rich Web Forms types found in the System.Web and System.Web.UI namespaces of the .NET Framework Class Library (FCL). With Visual Studio, Web Forms programming couldn't be simpler: open a form, drag some controls onto it, and write the code to handle events. Presto! You've written a web application. On the other hand, even with Visual Studio writing a robust and complete web application can be a daunting task. Web Forms offer a very rich UI; the number and complexity of web controls have greatly multiplied in recent years, and user expectations about the look and feel of web applications have risen accordingly. In addition, web applications are inherently distributed. Typically, the client will not be in the same building as the server. For most web applications, you must take network latency, bandwidth, and network server performance into account when creating the UI; a round trip from client to host might take a few seconds. Web Form Events Web Forms are event-driven. An event is an object that encapsulates the idea that "something happened." An event is generated (or raised) when the user presses a button, or selects from a list box, or otherwise interacts with the UI. Events can also be generated by the system starting or finishing work. For example, open a file for reading, and the system raises an event when the file has been read into memory.

Sikkim Manipal University

Page No. 98

DOT Net Technologies

Unit 3

The method that responds to the event is called the event handler. Event handlers are written in C# in the code-behind page and are associated with controls in the HTML page through control attributes. Event handlers are delegates. By convention, ASP.NET event handlers return void and take two parameters. The first parameter represents the object raising the event. The second, called the event argument , contains information specific to the event, if any. For most events, the event argument is of type EventArgs, which does not expose any properties. For some controls, the event argument might be of a type derived from EventArgs that can expose properties specific to that event type. In web applications, most events are typically handled on the server and, therefore, require a round trip. ASP.NET only supports a limited set of events, such as button clicks and text changes. These are events that the user might expect to cause a significant change, as opposed to Windows events (such as mouse-over) that might happen many times during a single user driven task. Postback versus non-postback events Postback events are those that cause the form to be posted back to the server immediately. These include click type events, such as the Button Click event. In contrast, many events (typically change events) are considered non-postback in that the form is not posted back to the server immediately. Instead, these events are cached by the control until the next time that a postback event occurs. You can force controls with non-postback events to behave in a postback manner by setting their AutoPostBack property to true. State A web application's State is the current value of all the controls and variables for the current user in the current session. The Web is inherently a
Sikkim Manipal University Page No. 99

DOT Net Technologies

Unit 3

"stateless" environment. This means that every post to the server loses the state from previous posts, unless the developer takes great pains to preserve this session knowledge. ASP.NET, however, provides support for maintaining the state of a user's session. Whenever a page is posted to the server, it is re-created by the server from scratch before it is returned to the browser. ASP.NET provides a mechanism that automatically maintains state for server controls. Thus, if you provide a list and the user has made a selection, that selection is preserved after the page is posted back to the server and redrawn on the client.

3.4 Web Form Life Cycle


Every request for a page made from a web server causes a chain of events at the server. These events, from beginning to end, constitute the life cycle of the page and all its components. The life cycle begins with a request for the page, which causes the server to load it. When the request is complete, the page is unloaded. From one end of the life cycle to the other, the goal is to render appropriate HTML output back to the requesting browser. The life cycle of a page is marked by the following events, each of which you can handle yourself or leave to default handling by the ASP.NET server: Initialize: Initialize is the first phase in the life cycle for any page or control. It is here that any settings needed for the duration of the incoming request are initialized. Load ViewState: The ViewState property of the control is populated. The ViewState information comes from a hidden variable on the control, used to persist the state across round trips to the server. The input string from this hidden variable is parsed by the page framework, and the ViewState property is set. This can be modified via the LoadViewState( ) method: This allows ASP.NET to manage the state of your control across page loads
Sikkim Manipal University Page No. 100

DOT Net Technologies

Unit 3

so that each control is not reset to its default state each time the page is posted. Process Postback Data: During this phase, the data sent to the server in the posting is processed. If any of this data results in a requirement to update the ViewState, that update is performed via the LoadPostData( ) method. Load: CreateChildControls( ) is called, if necessary, to create and initialize server controls in the control tree. State is restored, and the form controls show client-side data. You can modify the load phase by handling the Load event with the OnLoad method. Send Postback Change Modifications: If there are any state changes between the current state and the previous state, change events are raised via the RaisePostDataChangedEvent( ) method. Handle Postback Events: The client-side event that caused the postback is handled. PreRender: This is the phase just before the output is rendered to the browser. It is essentially your last chance to modify the output prior to rendering using the OnPreRender( ) method. Save State: Near the beginning of the life cycle, the persisted view state was loaded from the hidden variable. Now it is saved back to the hidden variable, persisting as a string object that will complete the round trip to the client. You can override this using the SaveViewState() method. Render: This is where the output to be sent back to the client browser is generated. You can override it using the Render method.

CreateChildControls( ) is called, if necessary, to create and initialize server controls in the control tree.
Sikkim Manipal University Page No. 101

DOT Net Technologies

Unit 3

Dispose: This is the last phase of the life cycle. It gives you an opportunity to do any final cleanup and release references to any expensive resources, such as database connections. You can modify it using the Dispose( ) method.

3.5 Creating a Web Form


To create the simple Web Form that will be used in the next example, start up Visual Studio .NET and open a New Project named ProgrammingCSharpWeb. Select the Visual C# Projects folder (because C# is your language of choice), select ASP.NET Web Application as the project type, and type in its name, ProgrammingCSharpWeb. Visual Studio .NET will display http://localhost/ as the default location, as shown in Figure 3.7.

Figure 3.7: Creating a project in the New Project window of Visual Studio .NET

Visual Studio places nearly all the files it creates for the project in a folder within your local machine's default web site for example, c:\Inetpub\wwwroot\ProgrammingCSharpWeb. The solution files and other Visual Studio-specific files are stored in <drive>\Documents and Settings\<user name>\My Documents\Visual Studio Projects (where <drive> and
Sikkim Manipal University Page No. 102

DOT Net Technologies

Unit 3

<user name> are specific to your machine). When the application is created, Visual Studio places a number of files in your project. The Web Form itself is stored in a file named WebForm1.aspx. This file will contain only HTML. A second, equally important file, WebForm1.aspx.cs, stores the C# associated with your form; this is the code-behind file. Notice that the code-behind file does not appear in the Solution Explorer. To see the code behind (.cs) file, you must place the cursor within Visual Studio .NET, right-click the form, and choose "View Code" in the pop-up menu. You can now tab back and forth between the form itself, WebForm1.aspx, and the C# code-behind file, WebForm1.aspx.cs. When viewing the form, WebForm1.aspx, you can choose between Design mode and HTML mode by clicking the tabs at the bottom of the Editor window. Design mode lets you drag controls onto your form; HTML mode allows you to view and edit the HTML code directly. Let's take a closer look at the .aspx and code-behind files that Visual Studio creates. Start by renaming WebForm1.aspx to HelloWeb.aspx. To do this, close WebForm1.aspx, and then right-click its name in the Solution Explorer. Choose Rename and enter the name HelloWeb.aspx. After you rename it, open HelloWeb.aspx and view the code; you will find that the code-behind file has been renamed as well to HelloWeb.aspx.cs.When you create a new Web Form application, Visual Studio .NET will generate a bit of boilerplate code to get you started, as shown in Example 3.1 below: <%@ Page language="c#" Codebehind="HelloWeb.aspx.cs" AutoEventWireup="false" Inherits="ProgrammingCSharpWeb.WebForm1" %>
Sikkim Manipal University Page No. 103

DOT Net Technologies

Unit 3

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <html> <head> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> </form> </body> </html>

Example 3.1 Wizard-generated code for a Web Form What you see is typical boilerplate HTML except for the first line, which contains the following ASP.NET code: <%@ Page language="c#" Codebehind="HelloWeb.aspx.cs" AutoEventWireup="false" Inherits="ProgrammingCSharpWeb.WebForm1" %> The language attribute indicates that the language used on the code-behind page is C#. The Codebehind attribute designates that the filename of that
Sikkim Manipal University Page No. 104

DOT Net Technologies

Unit 3

page is HelloWeb.cs, and the Inherits attribute indicates that this page derives from WebForm1. WebForm1 is a class declared in HelloWeb.cs. public class WebForm1 : System.Web.UI.Page As the C# code makes clear, WebForm1 inherits from

System.Web.UI.Page, which is the class that defines the properties, methods, and events common to all server-side pages. Returning to the HTML view of HelloWeb.aspx, you see that a form has been specified in the body of the page using the standard HTML form tag: <form id="Form1" method="post" runat="server"> Web Forms assumes that you need at least one form to manage the user interaction, and creates one when you open a project. The attribute runat="server" is the key to the serverside magic. Any tag that includes this attribute is considered a server-side control to be executed by the ASP.NET framework on the server. Having created an empty Web Form, the first thing you might want to do is add some text to the page. By switching to HTML view, you can add script and HTML directly to the file just as you could with classic ASP. Adding the following line to the body segment of the HTML page will cause it to display a greeting and the current local time: Hello World! It is now <% = DateTime.Now.ToString( ) %> The <% and %> marks work just as they did in classic ASP, indicating that code falls between them (in this case, C#). The = sign immediately following the opening tag causes ASP.NET to display the value, just like a call to Response.Write( ). You could just as easily write the line as: Hello World! It is now <% Response.Write(DateTime.Now.ToString( )); %>

Sikkim Manipal University

Page No. 105

DOT Net Technologies

Unit 3

Run the page by pressing Ctrl-F5 (or save it and navigate to it in your browser). You should see the string printed to the browser, as in Figure 3.8.

Figure 3.8: Output generated by the HelloWorld.aspx file

3.6 Summary
This unit introduces the user with the basics of GUI based applications like development of forms in both window based and Web based applications. This unit starts with a sample application demonstrating both the coding and designing of a simple GUI based interface using C#. It then starts with another sample application demonstrating the Web based Forms

Development using Visual Studio. It also describes the Web forms development cycle. Self Assessment Questions 1. The tools for creating web applications are called _______. 2. _________ is the first development environment to marry the RAD tools of Visual Basic with the object-oriented and high performance characteristics of a C-family language. 3. The _____ object represents any window displayed in your application. 4. The ______ method can have any name but must return void and take two parameters: an object (sender) and a SystemEventArgs object. 5. The ________ keyboard shortcut is used to display the Toolbox. 6. The __________________ is a window that displays all the files in your projects.
Sikkim Manipal University Page No. 106

DOT Net Technologies

Unit 3

7. The _______ implement a programming model in which web pages are dynamically generated on a web server for delivery to a browser over the Internet.

3.7 Terminal Questions


1. Design a simple Window based form application to perform basic arithmetic operations. (Refer to 3.1) 2. Design a simple Web Based Form to produce a bill of any stores. (Refer to 3.2) 3. Describe the Web Form Life cycle. (Refer to 3.4) 4. Describe the basic steps in creating a web form. (Refer to 3.5)

3.8 Answers to Terminal Questions


1. Web Forms 2. C# 3. Form 4. delegated 5. Ctrl-Alt-X 6. Solution Explorer 7. Web Forms

Sikkim Manipal University

Page No. 107

DOT Net Technologies

Unit 10

Unit 10
Structure: 10.1 The ASP.NET Security Model Objectives 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 Forms Authentication Membership Windows Authentication Authorization and Roles Profile Cryptography Custom Membership Providers Summary Self Assessment Questions 10.10 Terminal Questions 10.11 Answers to Self Assessment Questions

Security

10.1 The ASP.NET Security Model


ASP.NET is central to the development of the distributed Web applications discussed in this section. It provides a rich and easily accessible set of security capabilities that facilitate the creation of secure Web applications. ASP.NET is designed to work with the existing security capabilities of Internet Information Services (IIS), the Windows platform, and the .NET Framework, but it is also flexible and extensible. This means that you can build custom security mechanisms that can be tightly integrated with your applications. This module presents guidance and recommendations that help you address the issues of authentication, authorization, and secure

communication when building secure ASP.NET Web applications.


Sikkim Manipal University Page No. 322

DOT Net Technologies

Unit 10

ASP.NET Security Architecture ASP.NET works in conjunction with IIS, the .NET Framework, and the underlying security services provided by the operating system, to provide a range of authentication and authorization mechanisms. These are summarized in Figure 10.1 below:

Figure 10.1: ASP.NET security services

Figure

10.1

above

illustrates

the

authentication

and

authorization

mechanisms provided by IIS and ASP.NET. When a client issues a Web request, the following sequence of authentication and authorization events occurs: 1. The HTTP(S) Web request is received from the network. SSL can be used to ensure the server identity (using server certificates) and, optionally, the client identity. 2. SSL (Secure Socket Layer) also provides a secured channel to protect sensitive data passed between client and server (and vice-versa). 3. IIS authenticates the caller by using Basic, Digest, Integrated (NTLM or Kerberos), or Certificate authentication. If all or part of your site does not require authenticated access, IIS can be configured for
Sikkim Manipal University Page No. 323

DOT Net Technologies

Unit 10

anonymous authentication. IIS creates a Windows access token for each authenticated user. If anonymous authentication is selected, IIS creates an access token for the anonymous Internet user account (which, by default, is IUSR_MACHINE). 4. IIS authorizes the caller to access the requested resource. NTFS permissions defined by ACLs attached to the requested resource are used to authorize access. IIS can also be configured to accept requests only from client computers with specific IP addresses. 5. IIS passes the authenticated caller's Windows access token to ASP.NET (this may be the anonymous Internet user's access token, if anonymous authentication is being used). 6. ASP.NET authenticates the caller. 7. If ASP.NET is configured for Windows authentication, no additional authentication occurs at this point. ASP.NET will accept any token it receives from IIS. 8. If ASP.NET is configured for Forms authentication, the credentials supplied by the caller (using an HTML form) are authenticated against a data store; typically a SQL Server database or Active Directory. If ASP.NET is configured for Passport authentication, the user is redirected to a Passport site, and the Passport authentication service authenticates the user. 9. ASP.NET authorizes access to the requested resource or operation. 10. The UrlAuthorizationModule (a system provided HTTP module) uses authorization rules configured in Web.config (specifically, the

<authorization> element) to ensure that the caller can access the requested file or folder. 11. With Windows authentication, the FileAuthorizationModule (another HTTP module) checks that the caller has the necessary permission to

Sikkim Manipal University

Page No. 324

DOT Net Technologies

Unit 10

access the requested resource. The caller's access token is compared against the ACL that protects the resource. 12. .NET roles can also be used either declaratively or programmatically to ensure that the caller is authorized to access the requested resource or perform the requested operation. 13. Code within your application accesses local and/or remote resources by using a particular identity. By default, ASP.NET performs no impersonation and as a result, the configured ASP.NET process account provides the identity. Alternate options include the original caller's identity if impersonation is enabled, or a configured service identity. Gatekeepers: IIS & ASP.NET The authorization points or gatekeepers within an ASP.NET Web application are provided by IIS and ASP.NET: IIS With anonymous authentication turned off, IIS permits requests only from users that it can authenticate either in its domain or in a trusted domain. For static file types (for example .jpg, .gif and .htm filesfiles that are not mapped to an ISAPI extension), IIS uses the NTFS permissions associated with the requested file to perform access control. ASP.NET The ASP.NET gatekeepers include the UrlAuthorizationModule,

FileAuthorizationModule and principal permission demands and role checks. UrlAuthorizationModule You can configure <authorization> elements within your application's Web.config file to control which users and groups of users should have

Sikkim Manipal University

Page No. 325

DOT Net Technologies

Unit 10

access to the application. Authorization is based on the IPrincipal object stored in HttpContext.User. FileAuthorizationModule For file types mapped by IIS to the ASP.NET ISAPI extension (Aspnet_isapi.dll), automatic access checks are performed using the authenticated user's Windows access token (which may be

IUSR_MACHINE) against the ACL attached to the requested ASP.NET file. Note: Impersonation is not required for file authorization to work. The FileAuthorizationModule class only performs access checks against the requested file, and not for files accessed by the code in the requested page, although these are access checked by IIS. For example, if you request Default.aspx and it contains an embedded user control

(Usercontrol.ascx), which in turn includes an image tag (pointing to Image.gif), the FileAuthorizationModule performs an access check for Default.aspx and Usercontrol.ascx, because these file types are mapped by IIS to the ASP.NET ISAPI extension. The FileAuthorizationModule does not perform a check for Image.gif, because this is a static file handled internally by IIS. However, as access checks for static files are performed by IIS, the authenticated user must still be granted read permission to the file with an appropriately configured ACL. This scenario is shown in Figure 10.2 below: Note: (To System Administrators) The authenticated user requires NTFS read permissions to all of the files involved in the scenario. The only variable is regarding which gatekeeper is used to enforce access control. The ASP.NET process account only requires read access to the ASP.NET registered file types.

Sikkim Manipal University

Page No. 326

DOT Net Technologies

Unit 10

Figure 10.2: IIS and ASP.NET gatekeepers working together

In this scenario you can prevent access at the file gate. If you configure the ACL attached to Default.aspx and deny access to a particular user, the user control or any embedded images will not get a chance to be sent to the client by the code in Default.aspx. If the user requests the images directly, IIS performs the access checks itself. Principal Permission Demands and Explicit Role Checks In addition to the IIS and ASP.NET configurable gatekeepers, you can also use principal permission demands (declaratively or programmatically) as an additional fine-grained access control mechanism. Principal permission checks (performed by the PrincipalPermissionAttribute class) allow you to control access to classes, methods, or individual code blocks based on the identity and group membership of individual users, as defined by the IPrincipal object attached to the current thread.

Sikkim Manipal University

Page No. 327

DOT Net Technologies

Unit 10

Note: Principal permission demands used to demand role membership are different from calling IPrincipal.IsInRole to test role membership; the former results in an exception if the caller is not a member of the specified role, while the latter simply returns a Boolean value to confirm role membership. With Windows authentication, ASP.NET automatically attaches a

WindowsPrincipal object that represents the authenticated user to the current Web request (using HttpContext.User). Forms and Passport authentication create a GenericPrincipal object with the appropriate identity and no roles and attaches it to the HttpContext.User. Authentication and Authorization Strategies ASP.NET provides a number of declarative and programmatic authorization mechanisms that can be used in conjunction with a variety of authentication schemes. This allows you to develop an in depth authorization strategy and one that can be configured to provide varying degrees of granularity; for example, per-user or per-user group (role-based). This section shows you which authorization options (both configurable and programmatic) are available for a set of commonly used authentication options. The authentication options that follow are summarized here: Windows authentication with impersonation Windows authentication without impersonation Windows authentication using a fixed identity Forms authentication Passport authentication

Available Authorization Options The following table 10.1 shows you the set of available authorization options. For each one the table indicates whether or not Windows authentication and/or impersonation are required. If Windows authentication is not required, the particular authorization option is available for all other
Sikkim Manipal University Page No. 328

DOT Net Technologies

Unit 10

authentication

types.

Use

the

table

to

help

refine

your

authentication/authorization strategy. Table 10.1: Windows authentication and impersonation


Authorization Option FileAuthorizationModule UrlAuthorizationModule Principal Permission Demands .NET Roles Enterprise Services Roles NTFS Permissions (for directly requested static files types; not mapped to an ISAPI extension) Requires Windows Authentication Yes No No No Yes N/AThese files are not handled by ASP.NET. With any (non-Anonymous) IIS authentication mechanism, permissions should be configured for individual authenticated users. With Anonymous authentication, permissions should be configured for IUSR_MACHINE. No Requires Impersonation No No No No Yes (within the ASP.NET Web application) No (IIS performs the access check.)

NTFS Permissions (for files accessed by Web application code)

No If impersonating, configure ACLs against the impersonated Windows identity, which is either the original caller or the identity specified on the <identity> element in Web.config.

Windows Authentication with Impersonation The following configuration elements show you how to enable Windows (IIS) authentication Machine.config. Note: You should configure authentication on a per-application basis in each application's Web.config file. <authentication mode="Windows" />
Sikkim Manipal University Page No. 329

and

impersonation

declaratively

in

Web.config

or

DOT Net Technologies

Unit 10

<identity impersonate="true" /> With this configuration, your ASP.NET application code impersonates the IIS-authenticated caller. Configurable Security When you use Windows authentication together with impersonation, the following authorization options are available to you: Windows ACLs Client Requested Resources. The ASP.NET

FileAuthorizationModule performs access checks for requested file types that are mapped to the ASP.NET ISAPI. It uses the original caller's access token and ACL attached to requested resources in order to perform access checks. For static files types (not mapped to an ISAPI extension), IIS performs access checks using the caller's access token and ACL attached to the file. Resources Accessed by Your Application. You can configure Windows ACLs on resources accessed by your application (files, folders, registry keys, Active Directory objects, and so on) against the original caller. URL Authorization. Configure URL authorization in Web.config. With Windows authentication, user names take the form

DomainName\UserName and roles map one-to-one with Windows groups. <authorization> <deny user="DomainName\UserName" /> <allow roles="DomainName\WindowsGroup" /> </authorization>

Enterprise Services (COM+) Roles. Roles are maintained in the COM+ catalog. You can configure roles with the Component Services administration tool or script.

Sikkim Manipal University

Page No. 330

DOT Net Technologies

Unit 10

Programmatic Security Programmatic security refers to security checks located within your Web application code. The following programmatic security options are available when you use Windows authentication and impersonation: PrincipalPermission Demands o Imperative (in-line within a method's code) PrincipalPermission permCheck = new PrincipalPermission( null, @"DomainName\WindowsGroup"); permCheck.Demand(); o Declarative (attributes preceding interfaces, classes and methods) [PrincipalPermission(SecurityAction.Demand, Role=@"DomainName\WindowsGroup)]

Explicit Role Checks. You can perform role checking using the IPrincipal interface. IPrincipal.IsInRole(@"DomainName\WindowsGroup");

Enterprise Services (COM+) Roles. You can perform role checking programmatically using the ContextUtil class. ContextUtil.IsCallerInRole("Manager")

When to Use Use Windows authentication and impersonation when: Your application's users have Windows accounts that can be authenticated by the server. You need to flow the original caller's security context to the middle tier and/or data tier of your Web application to support fine-grained (peruser) authorization. You need to flow the original caller's security context to the downstream tiers to support operating system level auditing. Before using impersonation within your application, make sure you understand the relative trade-offs of this approach in comparison to using the trusted subsystem model.
Sikkim Manipal University Page No. 331

DOT Net Technologies

Unit 10

The disadvantages of impersonation include: Reduced application scalability due to the inability to effectively pool database connections. Increased administration effort as ACLs on back-end resources need to be configured for individual users. Delegation requires Kerberos authentication and a suitably configured environment. Windows Authentication without Impersonation The following configuration elements show how you enable Windows (IIS) authentication with no impersonation declaratively in Web.config. <authentication mode="Windows" /> <!-- The following setting is equivalent to having no identity element --> <identity impersonate="false" /> Configurable Security When you use Windows authentication without impersonation, the following authorization options are available to you:

Windows ACLs Client Requested Resources. The ASP.NET FileAuthorizationModule performs access checks for requested file types that are mapped to the ASP.NET ISAPI. It uses the original caller's access token and ACL attached to requested resources in order to perform access checks. Impersonation is not required. For static files types (not mapped to an ISAPI extension) IIS performs access checks using the caller's access token and ACL attached to the file.

Resources accessed by your application. Configure Windows ACLs on resources accessed by your application (files, folders, registry keys, Active Directory objects) against the ASP.NET process identity.

Sikkim Manipal University

Page No. 332

DOT Net Technologies

Unit 10

URL Authorization. Configure URL Authorization in Web.config. With Windows groups. <authorization> <deny user="DomainName\UserName" /> <allow roles="DomainName\WindowsGroup" /> </authorization> authentication, user names take the form DomainName\UserName and roles map one-to-one with Windows

Programmatic Security The following programmatic security options are available: Principal Permission Demands o Imperative PrincipalPermission permCheck = new PrincipalPermission( null, @"DomainName\WindowsGroup"); permCheck.Demand(); o Declarative [PrincipalPermission(SecurityAction.Demand, Role=@"DomainName\WindowsGroup")] Explicit Role Checks. You can perform role checking using the IPrincipal interface. IPrincipal.IsInRole(@"DomainName\WindowsGroup"); When to Use Use Windows authentication without impersonation when: Your application's users have Windows accounts that can be authenticated by the server. You want to use a fixed identity to access downstream resources (for example, databases) in order to support connection pooling. Windows Authentication Using a Fixed Identity The <identity> element in Web.config supports optional user name and password attributes, which allows you to configure a specific fixed identity
Sikkim Manipal University Page No. 333

DOT Net Technologies

Unit 10

for your application to impersonate. This is shown in the following configuration file fragment. <identity impersonate="true" userName="registry:HKLM\SOFTWARE\YourSecureApp\ identity\ASPNET_SETREG,userName" password="registry:HKLM\SOFTWARE\YourSecureApp\ identity\ASPNET_SETREG,password" /> This example shows the <identity> element where the credentials are encrypted in the registry using the aspnet_setreg.exe utility. The clear text userName and password attribute values have been replaced with pointers to the secured registry key and named values that contain the encrypted credentials. When to Use Using a fixed impersonated identity is not recommended when using the .NET Framework 1.0 on Windows 2000 servers. This is because you would need to give the ASP.NET process account the powerful "Act as part of the operating system" privilege. This privilege is required by the ASP.NET process because it performs a LogonUser call using the credentials that you have provided. Note: The .NET Framework version 1.1 will provide an enhancement for this scenario on Windows 2000. The log on will be performed by the IIS process, so that ASP.NET does not require the "Act as part of the operating system" privilege. Forms Authentication The following configuration elements show how you enable Forms authentication declaratively in Web.config. <authentication mode="Forms"> <forms loginUrl="logon.aspx" name="AuthCookie" timeout="60" path="/"> </forms> </authentication>
Sikkim Manipal University Page No. 334

DOT Net Technologies

Unit 10

Configurable Security When you use Forms authentication, the following authorization options are available to you: Windows ACLs Client Requested Resources. Requested resources require ACLs that allow read access to the anonymous Internet user account. (IIS should be configured to allow anonymous access when you use Forms authentication). ASP.NET File authorization is not available because it requires Windows authentication. Resources Accessed by Your Application. Configure Windows ACLs on resources accessed by your application (files, folders, registry keys, and Active Directory objects) against the ASP.NET process identity. URL Authorization Configure URL Authorization in Web.config. With Forms authentication, the format of user names is determined by your custom data store; a SQL Server database, or Active Directory. If you are using a SQL Server data store: <authorization> <deny users="?" /> <allow users="Mary,Bob,Joe" roles="Manager,Sales" /> </authorization> If you are using Active Directory as your data store, user names, and group names appear in X.500 format: <authorization> <deny users="someAccount@domain.corp.yourCompany.com" /> <allow roles ="CN=Smith James,CN=FTE_northamerica,CN=Users, DC=domain,DC=corp,DC=yourCompany,DC=com" /> </authorization>
Sikkim Manipal University Page No. 335

DOT Net Technologies

Unit 10

Programmatic Security The following programmatic security options are available: Principal Permission Demands o Imperative PrincipalPermission permCheck = new PrincipalPermission( null, "Manager"); permCheck.Demand(); o Declarative [PrincipalPermission(SecurityAction.Demand, Role="Manager")] Explicit Role Checks. You can perform role checking using the IPrincipal interface. IPrincipal.IsInRole("Manager"); When to Use Forms authentication is most ideally suited to Internet applications. Use Forms authentication when: Your application's users do not have Windows accounts. You want users to log on to your application by entering credentials using an HTML form. Passport Authentication The following configuration elements show how you enable Passport authentication declaratively in Web.config. <authentication mode="Passport" /> When to Use Passport authentication is used on the Internet when application users do not have Windows accounts and you want to implement a single-sign-on solution. Users who have previously logged on with a Passport account at a participating Passport site will not have to log on to your site configured with Passport authentication.

Sikkim Manipal University

Page No. 336

DOT Net Technologies

Unit 10

Configuring Security This section shows you the practical steps required to configure security for an ASP.NET Web application. These are summarized in Figure below:

Figure 10.9: Configuring ASP.NET application security

Configure IIS Settings To configure IIS security, you must perform the following steps: 1. Optionally install a Web server certificate (if you need SSL). 2. For more information, see "How To Set Up SSL on a Web Server."." 3. Configure IIS authentication.

Sikkim Manipal University

Page No. 337

DOT Net Technologies

Unit 10

4. Optionally configure client certificate mapping (if using certificate authentication). 5. Set NTFS permissions on files and folders. Between them, IIS and the ASP.NET FileAuthorizationModule check that the authenticated user (or the anonymous Internet user account) has the necessary access rights (based on ACL settings) to access the requested file. Configure ASP.NET Settings Application level configuration settings are maintained in Web.config files, which are located in your application's virtual root directory and optionally within additional subfolders (these settings can sometimes override the parent folder settings). 1. Configure authentication. This should be set on a per-application basis (not in Machine.config) in the Web.config file located in the application's virtual root directory. 2. <authentication mode="Windows|Forms|Passport|None" /> 3. Configure Impersonation. By default, ASP.NET applications do not impersonate. The applications run using the configured ASP.NET process identity (usually ASP.NET) and all resource access performed by your application uses this identity. You only need impersonation in the following circumstances: a. You are using Enterprise Services and you want to use Enterprise Services (COM+) roles to authorize access to functionality provided by serviced components. b. IIS is configured for Anonymous authentication and you want to use the anonymous Internet user account for resource access. c. You have ported a classic ASP application to ASP.NET and want the same impersonation behavior. Classic ASP impersonates the caller by default.

Sikkim Manipal University

Page No. 338

DOT Net Technologies

Unit 10

4. To configure ASP.NET impersonation use the following <identity> element in your application's Web.config. 5. <identity impersonate="true" /> URL Authorization Notes Take note of the following when you configure URL authorization: "*" refers to all identities. "?" refers to unauthenticated identities (that is, the anonymous identity). You don't need to impersonate for URL authorization to work. Authorization settings in Web.config usually refer to all of the files in the current directory and all subdirectories (unless a subdirectory contains its own Web.config with an <authorization> element. In this case the settings in the subdirectory over ride the parent directory settings). Note URL authorization only applies to file types that are mapped by IIS to the ASP.NET ISAPI extension, aspnet_isapi.dll. You can use the <location> tag to apply authorization settings to an individual file or directory. The following example shows how you can apply authorization to a specific file (Page.aspx). <location path="page.aspx" /> <authorization> <allow users="DomainName\Bob, DomainName\Mary" /> <deny users="*" /> </authorization> </location> Users and roles for URL authorization are determined by your authentication settings: o When you have <authentication mode="Windows" /> you are authorizing access to Windows user and group accounts. User names take the form "DomainName\WindowsUserName"
Page No. 339

Sikkim Manipal University

DOT Net Technologies

Unit 10

Role names take the form "DomainName\WindowsGroupName" Note The local administrators group is referred to as

"BUILTIN\Administrators". The local users group is referred to as "BUILTIN\Users". o When you have <authentication mode="Forms" /> you are authorizing against the user and roles for the IPrincipal object that was stored in the current HTTP context. For example, if you used Forms to authenticate users against a database, you will be authorizing against the roles retrieved from the database. o When you have <authentication mode="Passport" /> you authorize against the Passport User ID (PUID) or roles retrieved from a store. For example, you can map a PUID to a particular account and set of roles stored in a SQL Server database or Active Directory. Note This functionality will be built into the Microsoft Windows .NET Server 2003 operating system. o When you have <authentication mode="None" /> you may not be performing authorization. "None" specifies that you don't want to perform any authentication or that you don't want to use any of the .NET authentication modules and want to use your own custom mechanism. However, if you use custom authentication, you should create an IPrincipal object with roles and store it into the HttpContext.User. When you subsequently perform URL authorization, it is performed against the user and roles (no matter how they were retrieved) maintained in the IPrincipal object.

Sikkim Manipal University

Page No. 340

DOT Net Technologies

Unit 10

Windows Authentication Use Windows authentication when the users of your application have Windows accounts that can be authenticated by the server (for example, in intranet scenarios). If you configure ASP.NET for Windows authentication, IIS performs user authentication by using the configured IIS authentication mechanism. This is shown in Figure below:

Figure 10.10: ASP.NET Windows authentication uses IIS to authenticate callers

The access token of the authenticated caller (which may be the Anonymous Internet user account if IIS is configured for Anonymous authentication) is made available to the ASP.NET application. Note the following: This allows the ASP.NET FileAuthorizationModule to perform access checks against requested ASP.NET files using the original caller's access token. Note: ASP.NET File authorization only performs access checks against file types that are mapped to Aspnet_isapi.dll. File authorization does not require impersonation. With impersonation enabled, any resource access performed by your application uses the impersonated caller's identity. In this event, ensure that the ACLs
Sikkim Manipal University Page No. 341

DOT Net Technologies

Unit 10

attached to resources contain an Access Control Entry (ACE) that grants at least read access to the original caller's identity. Identifying the Authenticated User

ASP.NET associates a WindowsPrincipal object with the current Web


request. This contains the identity of the authenticated Windows user together with a list of roles that the user belongs to. With Windows authentication, the role list consists of the set of Windows groups to which the user belongs. The following code shows how to obtain the identity of the authenticated Windows user and to perform a simple role test for authorization. WindowsPrincipal user = User as WindowsPrincipal; if (null != user) { string username = user.Identity.Name; // Perform a role check if ( user.IsInRole(@"DomainName\Manager") ) { // User is authorized to perform manager functionality } } else { // Throw security exception as we don't have a WindowsPrincipal }

Sikkim Manipal University

Page No. 342

DOT Net Technologies

Unit 10

Objectives Secure your ASP.NET application. Secure secrets and state information maintained by ASP.NET applications. Understand the security architecture of ASP.NET applications and learn how the security capabilities of IIS, Windows, the .NET Framework, and ASP.NET work in unison to provide security for your distributed Web application. Choose an authentication and authorization strategy that is appropriate to your application. Understand the effect of ASP.NET process identity and impersonation on the ability of your application to access downstream resources such as files and databases.

Implement the security design for your ASP.NET web application using a combination of product configuration tools and programming techniques.

10.2 Forms Authentication


When you are using Forms authentication, the sequence of events triggered by an unauthenticated user who attempts to access a secured file or resource (where URL authorization denies the user access), is shown in Figure below:

Sikkim Manipal University

Page No. 343

DOT Net Technologies

Unit 10

Figure 10.11: Forms authentication sequence of events

The following describes the sequence of events shown in Figure below: 1. The user issues a Web request for Default.aspx. 2. IIS allows the request because Anonymous access is enabled. ASP.NET checks the <authorization> elements and finds a <deny users=?" /> element. 3. The user is redirected to the login page (Login.aspx) as specified by the loginUrl attribute of the <forms> element. 4. The user supplies credentials and submits the login form. 5. The credentials are validated against a store (SQL Server or Active Directory) and roles are optionally retrieved. You must retrieve a role list if you want to use role-based authorization. 6. A cookie is created with a FormsAuthenticationTicket and sent back to the client. Roles are optionally stored in the ticket. By storing the role list in the ticket, you avoid accessing the database to re-retrieve the list for each successive Web request from the same user.

Sikkim Manipal University

Page No. 344

DOT Net Technologies

Unit 10

7. The user is redirected with client-side redirection to the originally requested page (Default.aspx). 8. In the Application_AuthenticateRequest event handler (in Global.asax), the ticket is used to create an IPrincipal object and it is stored in HttpContext.User. 9. ASP.NET checks the <authorization> elements and finds a <deny users=?" /> element. However, this time the user is authenticated. ASP.NET checks the <authorization> elements to ensure that the user is in the <allow> element. The user is granted access to Default.aspx. Development Steps for Forms Authentication The following list highlights the key steps that you must perform to implement Forms authentication: 1. Configure IIS for anonymous access. 2. Configure ASP.NET for Forms authentication. 3. Create a logon Web form and validate the supplied credentials. 4. Retrieve a role list from the custom data store. 5. Create a Forms authentication ticket (store roles in the ticket). 6. Create an IPrincipal object. 7. Put the IPrincipal object into the current HTTP context. 8. Authorize the user based on user name/role membership. Configure IIS for Anonymous Access Your application's virtual directory must be configured in IIS for anonymous access. To configure IIS for anonymous access 1. Start the Internet Information Services administration tool.

Sikkim Manipal University

Page No. 345

DOT Net Technologies

Unit 10

2. Select your application's virtual directory, right-click, and then click Properties. 3. Click Directory Security. 4. In the Anonymous access and authentication control group, click Edit. 5. Select Anonymous access. Configure ASP.NET for Forms Authentication A sample configuration is shown below. <authentication mode="Forms"> <forms name="MyAppFormsAuth" loginUrl="login.aspx" protection="Encryption" timeout="20" path="/" > </forms> </authentication>

10.5 Cryptography Overview


Cryptography helps protect data from being viewed, provides ways to detect whether data has been modified, and helps provide a secure means of communication over otherwise nonsecure channels. For example, data can be encrypted by using a cryptographic algorithm, transmitted in an encrypted state, and later decrypted by the intended party. If a third party intercepts the encrypted data, it will be difficult to decipher. Cryptographic Primitives In a typical situation where cryptography is used, two parties (Alice and Bob) communicate over a nonsecure channel. Alice and Bob want to ensure that their communication remains incomprehensible by anyone who might be listening. Furthermore, because Alice and Bob are in remote locations, Alice must make sure that the information she receives from Bob has not been modified by anyone during transmission. In addition, she must make sure
Sikkim Manipal University Page No. 346

DOT Net Technologies

Unit 10

that the information really does originate from Bob and not from someone who is impersonating Bob. Cryptography is used to achieve the following goals: Confidentiality: To help protect a user's identity or data from being read. Data integrity: To help protect data from being changed. Authentication: To ensure that data originates from a particular party. Public-key cryptography can also provide non-repudiation. To achieve these goals, you can use a combination of algorithms and practices known as cryptographic primitives to create a cryptographic scheme. The following table 10.4 lists the cryptographic primitives and their uses. Table 10.4: Cryptographic Primitives and Uses
Cryptographic primitive Secret-key encryption (symmetric cryptography) Use Performs a transformation on data to keep it from being read by third parties. This type of encryption uses a single shared, secret key to encrypt and decrypt data. Performs a transformation on data to keep it from being read by third parties. This type of encryption uses a public/private key pair to encrypt and decrypt data. Helps verify that data originates from a specific party by creating a digital signature that is unique to that party. This process also uses hash functions. Maps data from any length to a fixed-length byte sequence. Hashes are statistically unique; a different two-byte sequence will not hash to the same value.

Public-key encryption (asymmetric cryptography)

Cryptographic signing

Cryptographic hashes

Sikkim Manipal University

Page No. 347

DOT Net Technologies

Unit 10

Secret-Key Encryption Secret-key encryption algorithms use a single secret key to encrypt and decrypt data. You must secure the key from access by unauthorized agents, because any party that has the key can use it to decrypt your data or encrypt their own data, claiming it originated from you. Secret-key encryption is also referred to as symmetric encryption because the same key is used for encryption and decryption. Secret-key encryption algorithms are very fast (compared with public-key algorithms) and are well suited for performing cryptographic transformations on large streams of data. Asymmetric encryption algorithms such as RSA are limited mathematically in how much data they can encrypt. Symmetric encryption algorithms do not generally have those problems. Public-Key Encryption Public-key encryption uses a private key that must be kept secret from unauthorized users and a public key that can be made public to anyone. The public key and theprivate key are mathematically linked; data that is encrypted with the public key can be decrypted only with the private key, and data that is signed with the private key can be verified only with the public key. The public key can be made available to anyone; it is used for encrypting data to be sent to the keeper of the private key. Public-key cryptographic algorithms are also known as asymmetric algorithms because one key is required to encrypt data, and another key is required to decrypt data. Both keys should be unique for each communication session. However, although this requirement is true for symmetric algorithms, in practice, asymmetric keys are generally long-lived. .NET Framework Cryptography Model The .NET Framework provides implementations of many standard cryptographic algorithms. These algorithms are easy to use and have the
Sikkim Manipal University Page No. 348

DOT Net Technologies

Unit 10

safest possible default properties. In addition, the .NET Framework cryptography model of object inheritance, stream design, and configuration are extremely extensible. Object Inheritance The .NET Framework security system implements an extensible pattern of derived class inheritance. The hierarchy is as follows: Algorithm type class, such as SymmetricAlgorithm or HashAlgorithm. This level is abstract. Algorithm class that inherits from an algorithm type class; for example, RC2 or SHA1. This level is abstract. Implementation of an algorithm class that inherits from an algorithm class; for example, RC2CryptoServiceProvider or SHA1Managed. This level is fully implemented. Using this pattern of derived classes, it is easy to add a new algorithm or a new implementation of an existing algorithm. For example, to create a new public-key algorithm, you would inherit from the AsymmetricAlgorithm class. To create a new implementation of a specific algorithm, you would create a nonabstract derived class of that algorithm. Stream Design The common language runtime uses a stream-oriented design for implementing symmetric algorithms and hash algorithms. The core of this design is the CryptoStream class, which derives from the Stream class. Stream-based cryptographic objects all support a single standard interface (CryptoStream) for handling the data transfer portion of the object. Because all the objects are built on a standard interface, you can chain together multiple objects (such as a hash object followed by an encryption object), and you can perform multiple operations on the data without needing any intermediate storage for it. The streaming model also allows
Sikkim Manipal University Page No. 349

DOT Net Technologies

Unit 10

you to build objects from smaller objects. For example, a combined encryption and hash algorithm can be viewed as a single stream object even though this object might be built from a set of stream objects. Cryptographic Configuration Cryptographic configuration allows you to resolve a specific implementation of an algorithm to an algorithm name, allowing extensibility of the .NET Framework cryptography classes. You can add your own hardware or software implementation of an algorithm and map the implementation to the algorithm name of your choice. If an algorithm is not specified in the configuration file, the default settings are used. The System.Security.Cryptography namespace contains classes that allow you to perform both symmetric and asymmetric cryptography, create hashes, and provide random number generation. Successful cryptography is the result of combining these tasks. This section describes the key cryptographic tasks that you can perform to create a cryptographic scheme. Encrypting and Decrypting Data To encrypt and decrypt data, you must use a key with an encryption algorithm that performs a transformation on the data. The .NET Framework provides several classes that enable you to perform cryptographic transformations on data using several standard algorithms. This section describes how to create and manage keys and how to encrypt and decrypt data using public-key and secret-key algorithms. Generating Keys for Encryption and Decryption Creating and managing keys is an important part of the cryptographic process. Symmetric algorithms require the creation of a key and an initialization vector (IV) that must be kept secret from anyone who should not decrypt your data. Asymmetric algorithms require the creation of a public key and a private key. The public key can be made public to anyone, while
Sikkim Manipal University Page No. 350

DOT Net Technologies

Unit 10

the private key must known only by the party who will decrypt the data encrypted with the public key. This section describes how to generate and manage keys for both symmetric and asymmetric algorithms. Symmetric Keys The symmetric encryption classes supplied by the .NET Framework require a key and a new initialization vector (IV) to encrypt and decrypt data. Whenever you create a new instance of one of the managed symmetric cryptographic classes using the default constructor, a new key and IV are automatically created. Anyone that you allow to decrypt your data must possess the same key and IV and use the same algorithm. Generally, a new key and IV should be created for every session, and neither the key nor IV should be stored for use in a later session. To communicate a symmetric key and IV to a remote party, you would usually encrypt the symmetric key and IV using asymmetric encryption. Sending these values across an insecure network without encrypting them is extremely unsafe, as anyone that intercepts these values can then decrypt your data. The following example shows the creation of a new instance of the TripleDESCryptoServiceProvider class that implements the TripleDES algorithm. C# Code
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();

When the previous code is executed, a new key and IV are generated and placed in the Key and IV properties, respectively. Sometimes you might need to generate multiple keys. In this situation, you can create a new instance of a class that implements a symmetric algorithm and then create a new key and IV by calling the GenerateKey and
Sikkim Manipal University Page No. 351

DOT Net Technologies

Unit 10

GenerateIV methods. The following code example illustrates how to create new keys and IVs after a new instance of the asymmetric cryptographic class has been made. C# Code TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider(); TDES.GenerateIV(); TDES.GenerateKey(); When the previous code is executed, a key and IV are generated when the new instance of TripleDESCryptoServiceProvider is made. Another key and IV are created when the GenerateKey and GenerateIV methods are called. Asymmetric Keys The .NET Framework provides the RSACryptoServiceProvider and DSACryptoServiceProvider classes for asymmetric encryption. These classes create a public/private key pair when you use the default constructor to create a new instance. Asymmetric keys can be either stored for use in multiple sessions or generated for one session only. While the public key can be made generally available, the private key should be closely guarded. A public/private key pair is generated whenever a new instance of an asymmetric algorithm class is created. After a new instance of the class is created, the key information can be extracted using one of two methods: The ToXMLString method, which returns an XML representation of the key information. The ExportParameters method, which returns an RSAParameters structure that holds the key information. Both methods accept a Boolean value that indicates whether to return only the public key information or to return both the public-key and the privatekey information. An RSACryptoServiceProvider class can be initialized to

Sikkim Manipal University

Page No. 352

DOT Net Technologies

Unit 10

the value of an RSAParameters structure by using the ImportParameters method. Asymmetric private keys should never be stored verbatim or in plain text on the local computer. If you need to store a private key, you should use a key container. C# Code
//Generate a public/private key pair. RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); //Save the public key information to an RSAParameters structure. RSAParameters RSAKeyInfo = RSA.ExportParameters(false);

System.Security.Cryptography Namespace The System.Security.Cryptography namespace provides cryptographic services, including secure encoding and decoding of data, as well as many other operations, such as hashing, random number generation, and message authentication. Table 10.5: Understanding the .NET Cryptography Classes
Class Aes Description Represents the abstract base class from which all implementations of the Advanced Encryption Standard (AES) must inherit. Performs asymmetric encryption and decryption using the Cryptographic Application Programming Interfaces (CAPI) implementation of the Advanced Encryption Standard (AES) algorithm. Provides a managed implementation of the Advanced Encryption Standard (AES) symmetric algorithm. Represents Abstract Syntax Notation One (ASN.1)encoded data. Represents a collection of AsnEncodedData objects. This class cannot be inherited. Provides the ability to navigate through an AsnEncodedDataCollection object. This class cannot be inherited.

AesCryptoService Provider

AesManaged AsnEncodedData AsnEncodedData Collection AsnEncodedData Enumerator

Sikkim Manipal University

Page No. 353

DOT Net Technologies

Unit 10

AsymmetricAlgorithm AsymmetricKey ExchangeDeformatter AsymmetricKeyExchan geFormatter AsymmetricSignatureD eformatter AsymmetricSignatureF ormatter CngAlgorithm CngAlgorithmGroup CngKey CngKeyBlobFormat CngKeyCreation Parameters CngProperty Collection CngProvider CngUIPolicy

Represents the abstract base class from which all implementations of asymmetric algorithms must inherit. Represents the base class from which all asymmetric key exchange deformatters derive. Represents the base class from which all asymmetric key exchange formatters derive. Represents the abstract base class from which all implementations of asymmetric signature deformatters derive. Represents the base class from which all implementations of asymmetric signature formatters derive. Encapsulates the name of an encryption algorithm. Encapsulates the name of an encryption algorithm group. Defines the core functionality for keys that are used with Cryptography Next Generation (CNG) objects. Specifies a key BLOB format for use with Microsoft Cryptography Next Generation (CNG) objects. Contains advanced properties for key creation. Provides a strongly typed collection of Cryptography Next Generation (CNG) properties. Encapsulates the name of a key storage provider (KSP) for use with Cryptography Next Generation (CNG) objects. Encapsulates optional configuration parameters for the user interface (UI) that Cryptography Next Generation (CNG) displays when you access a protected key. Performs a cryptographic transformation of data. This class cannot be inherited. Accesses the cryptography configuration information. Contains a type and a collection of values associated with that type. Contains a set of CryptographicAttributeObject objects. Provides enumeration functionality for the CryptographicAttributeObjectCollection collection. This class cannot be inherited. The exception that is thrown when an error occurs during a cryptographic operation.

CryptoAPITransform CryptoConfig CryptographicAttribute Object CryptographicAttribute ObjectCollection CryptographicAttribute ObjectEnumerator Cryptographic Exception

Sikkim Manipal University

Page No. 354

DOT Net Technologies

Unit 10

Cryptographic UnexpectedOperation Exception CryptoStream CspKeyContainerInfo CspParameters

The exception that is thrown when an unexpected operation occurs during a cryptographic operation.

Defines a stream that links data streams to cryptographic transformations. Provides additional information about a cryptographic key pair. This class cannot be inherited. Contains parameters that are passed to the cryptographic service provider (CSP) that performs cryptographic computations. This class cannot be inherited. Represents the abstract base class from which all classes that derive byte sequences of a specified length inherit. Represents the base class for the Data Encryption Standard (DES) algorithm from which all DES implementations must derive. Defines a wrapper object to access the cryptographic service provider (CSP) version of the Data Encryption Standard (DES) algorithm. This class cannot be inherited. Represents the abstract base class from which all implementations of the Digital Signature Algorithm (DSA) must inherit. Defines a wrapper object to access the cryptographic service provider (CSP) implementation of the DSA algorithm. This class cannot be inherited. Verifies a Digital Signature Algorithm (DSA) PKCS#1 v1.5 signature. Creates a Digital Signature Algorithm (DSA) signature.

DeriveBytes DES

DESCryptoService Provider DSA

DSACryptoService Provider DSASignature Deformatter DSASignature Formatter ECDiffieHellman

Provides an abstract base class that Elliptic Curve DiffieHellman (ECDH) algorithm implementations can derive from. This class provides the basic set of operations that all ECDH implementations must support. Provides a Cryptography Next Generation (CNG) implementation of the Elliptic Curve Diffie-Hellman (ECDH) algorithm. This class is used to perform cryptographic operations. Specifies an Elliptic Curve Diffie-Hellman (ECDH) public key for use with the ECDiffieHellmanCng class.

ECDiffieHellmanCng

ECDiffieHellmanCng PublicKey

Sikkim Manipal University

Page No. 355

DOT Net Technologies

Unit 10

ECDiffieHellmanPublic Key ECDsa ECDsaCng

Provides an abstract base class from which all ECDiffieHellmanCngPublicKey implementations must inherit. Provides an abstract base class that encapsulates the Elliptic Curve Digital Signature Algorithm (ECDSA). Provides a Cryptography Next Generation (CNG) implementation of the Elliptic Curve Digital Signature Algorithm (ECDSA).

FromBase64Transform Converts a CryptoStream from base 64. HashAlgorithm HMAC Represents the base class from which all implementations of cryptographic hash algorithms must derive. Represents the abstract class from which all implementations of Hash-based Message Authentication Code (HMAC) must derive. Computes a Hash-based Message Authentication Code (HMAC) using the MD5 hash function. Computes a Hash-based Message Authentication Code (HMAC) using the RIPEMD160 hash function. Computes a Hash-based Message Authentication Code (HMAC) using the SHA1 hash function. Computes a Hash-based Message Authentication Code (HMAC) using the SHA256 hash function. Computes a Hash-based Message Authentication Code (HMAC) using the SHA384 hash function. Computes a Hash-based Message Authentication Code (HMAC) using the SHA512 hash function. Represents the abstract class from which all implementations of keyed hash algorithms must derive. Determines the set of valid key sizes for the symmetric cryptographic algorithms. Computes a Message Authentication Code (MAC) using TripleDES for the input data CryptoStream. Provides information for a manifest signature.

HMACMD5 HMACRIPEMD160 HMACSHA1 HMACSHA256 HMACSHA384 HMACSHA512 KeyedHashAlgorithm KeySizes MACTripleDES ManifestSignature Information ManifestSignature InformationCollection MaskGeneration

Represents a read-only collection of ManifestSignatureInformation objects. Represents the abstract class from which all mask

Sikkim Manipal University

Page No. 356

DOT Net Technologies

Unit 10

Method MD5 MD5Cng

generator algorithms must derive. Represents the abstract class from which all implementations of the MD5 hash algorithm inherit. Provides a CNG (Cryptography Next Generation) implementation of the MD5 (Message Digest 5) 128-bit hashing algorithm. Computes the MD5 hash value for the input data using the implementation provided by the cryptographic service provider (CSP). This class cannot be inherited. Represents a cryptographic object identifier. This class cannot be inherited. Represents a collection of Oid objects. This class cannot be inherited. Provides the ability to navigate through an OidCollection object. This class cannot be inherited. Derives a key from a password using an extension of the PBKDF1 algorithm. Computes masks according to PKCS #1 for use by key exchange algorithms. Provides methods for protecting and unprotecting data. This class cannot be inherited. Provides methods for protecting and unprotecting memory. This class cannot be inherited. Represents the abstract class from which all implementations of cryptographic random number generators derive. Represents the base class from which all implementations of the RC2 algorithm must derive.

MD5CryptoService Provider Oid OidCollection OidEnumerator PasswordDeriveBytes PKCS1Mask Generation Method ProtectedData ProtectedMemory RandomNumber Generator RC2

RC2CryptoServiceProv Defines a wrapper object to access the cryptographic ider service provider (CSP) implementation of the RC2 algorithm. This class cannot be inherited. Rfc2898DeriveBytes Implements password-based key derivation functionality, PBKDF2, by using a pseudo-random number generator based on HMACSHA1. Represents the base class from which all implementations of the Rijndael symmetric encryption algorithm must inherit. Accesses the managed version of the Rijndael algorithm. This class cannot be inherited.

Rijndael RijndaelManaged

Sikkim Manipal University

Page No. 357

DOT Net Technologies

Unit 10

RijndaelManaged Transform RIPEMD160 RIPEMD160Managed RNGCryptoService Provider

Performs a cryptographic transformation of data using the Rijndael algorithm. This class cannot be inherited. Represents the abstract class from which all implementations of the MD160 hash algorithm inherit. Computes the RIPEMD160 hash for the input data using the managed library. Implements a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP). This class cannot be inherited. Represents the base class from which all implementations of the RSA algorithm inherit. Performs asymmetric encryption and decryption using the implementation of the RSA algorithm provided by the cryptographic service provider (CSP). This class cannot be inherited. Decrypts Optimal Asymmetric Encryption Padding (OAEP) key exchange data. Creates Optimal Asymmetric Encryption Padding (OAEP) key exchange data using RSA.

RSA RSACryptoService Provider

RSAOAEPKey ExchangeDeformatter RSAOAEPKey ExchangeFormatter

RSAPKCS1KeyExchan Decrypts the PKCS #1 key exchange data. geDeformatter RSAPKCS1Key ExchangeFormatter RSAPKCS1Signature Deformatter RSAPKCS1Signature Formatter SHA1 SHA1Cng SHA1CryptoService Provider SHA1Managed Creates the PKCS#1 key exchange data using RSA.

Verifies an RSA PKCS #1 version 1.5 signature.

Creates an RSA PKCS #1 version 1.5 signature.

Computes the SHA1 hash for the input data. Provides a Cryptography Next Generation (CNG) implementation of the Secure Hash Algorithm (SHA). Computes the SHA1 hash value for the input data using the implementation provided by the cryptographic service provider (CSP). This class cannot be inherited. Computes the SHA1 hash for the input data using the managed library.

Sikkim Manipal University

Page No. 358

DOT Net Technologies

Unit 10

SHA256 SHA256Cng

Computes the SHA256 hash for the input data. Provides a Cryptography Next Generation (CNG) implementation of the Secure Hash Algorithm (SHA) for 256-bit hash values. Defines a wrapper object to access the cryptographic service provider (CSP) implementation of the SHA256 algorithm. Computes the SHA256 hash for the input data using the managed library. Computes the SHA384 hash for the input data. Provides a Cryptography Next Generation (CNG) implementation of the Secure Hash Algorithm (SHA) for 384-bit hash values. Defines a wrapper object to access the cryptographic service provider (CSP) implementation of the SHA384 algorithm. Computes the SHA384 hash for the input data using the managed library. Computes the SHA512 hash for the input data. Provides a Cryptography Next Generation (CNG) implementation of the Secure Hash Algorithm (SHA) for 512-bit hash values. Defines a wrapper object to access the cryptographic service provider (CSP) implementation of the SHA512 algorithm. Computes the SHA512 hash algorithm for the input data using the managed library. Contains information about the properties of a digital signature. Holds the strong name signature information for a manifest.

SHA256CryptoService Provider SHA256Managed SHA384 SHA384Cng

SHA384CryptoService Provider SHA384Managed SHA512 SHA512Cng

SHA512CryptoService Provider SHA512Managed SignatureDescription StrongNameSignature Information SymmetricAlgorithm ToBase64Transform

Represents the abstract base class from which all implementations of symmetric algorithms must inherit. Converts a CryptoStream to base 64.

Sikkim Manipal University

Page No. 359

DOT Net Technologies

Unit 10

TripleDES

Represents the base class for Triple Data Encryption Standard algorithms from which all TripleDES implementations must derive. Defines a wrapper object to access the cryptographic service provider (CSP) version of the TripleDES algorithm. This class cannot be inherited.

TripleDESCrypto ServiceProvider

ASP.NET Security Data Flow Scenario 1: Impersonation The impersonation scenario relies on Microsoft Internet Information Services (IIS) authentication and Microsoft Windows file access security to minimize security programming in the ASP.NET application itself. The data flow is shown in the following illustration of Figure 10.12. Impersonation

Figure 10.12: Impersonation

Sikkim Manipal University

Page No. 360

DOT Net Technologies

Unit 10

The illustration shows the following sequence of events: 1. A request from a network client comes to IIS. 2. IIS authenticates the client using basic, digest, or Windows integrated security (NTLM or Kerberos). 3. If the client is authenticated, IIS passes the authenticated request to ASP.NET. 4. The ASP.NET application impersonates the requesting client using the access token passed from IIS, and it relies on NTFS file permissions for granting access to resources. The ASP.NET application needs only to verify that impersonation is set to true in the ASP.NET configuration file; no ASP.NET security code is required. If impersonation is not enabled, the application runs with the ASP.NET process identity. For Microsoft Windows 2000 Server and Windows XP Professional, the default identity is a local account named ASPNET that is created automatically when ASP.NET is installed. For Microsoft Windows Server 2003, the default identity is the identity of the application pool for the IIS application (by default, the NETWORK SERVICE account.) 5. If access is granted, the ASP.NET application returns the requested resource through IIS. Scenario 2 - Forms Authentication In the forms authentication scenario, an application collects credentials such as name and password directly from the user and makes its own determination about their authenticity. IIS authentication is not used by the application, but IIS authentication settings can affect forms authentication. As a rule, when you use forms authentication, you enable anonymous access in IIS. Otherwise, if users do not pass IIS authentication, they do not reach your application in order to provide a user name and password to forms authentication.
Sikkim Manipal University Page No. 361

DOT Net Technologies

Unit 10

The data flow in this scenario is shown in the following illustration in Figure 10.13.

Figure 10.13: Forms Authentication

This illustration shows the following sequence of events: 1. A user generates a request for a protected resource. 2. IIS receives the request, and because IIS anonymous access is enabled, IIS does not perform any user authentication and the request is passed to the ASP.NET application. 3. Because the ASP.NET authentication mode is set to forms, the ASP.NET application examines the request for a forms authentication
Sikkim Manipal University Page No. 362

DOT Net Technologies

Unit 10

ticket (a specific cookie). If there is no authentication ticket attached to the request, ASP.NET redirects the request to the logon page specified in the application's configuration file. 4. On the logon page, the user enters the required credentials, usually a name and password. The application code checks the credentials to confirm their authenticity. If the credentials are authenticated, the application code attaches an authentication ticket to the response that represents the user credentials. (The password is not included). If authentication fails, the response is returned with an access denied message or the logon form is presented again. 5. The authentication ticket that is issued is included with subsequent requests to the ASP.NET application. ASP.NET checks the ticket for validity using a message authentication check (MAC). 6. If the user is authenticated, ASP.NET checks authorization and can either allow access to the originally requested resource, redirect the request to some other page, or redirect the request to a custom authorization module where the credentials are tested for authorization to access the protected resource. If authorization fails, ASP.NET redirects the user to the logon page. If the user is authorized, access is granted to the protected resource; or the application might require an additional test of the credentials before authorizing access to the protected resource, depending on the design of the application. Encrypting QueryStrings with .NET Once upon a time in the tech world, obscurity was security - this being most true in the early years of the industry, when there were gaping holes in privacy policies and confidential client information was bandied about from site to site without a care as to who actually could read the information.

Sikkim Manipal University

Page No. 363

DOT Net Technologies

Unit 10

With the new Cryptography classes in .NET, there's absolutely no excuse for not hiding even the most innocuous user data. If you ever need to 'piggyback' information from one web page to another, whether it is within a POST or a GET parameter, you're passing clear information that anyone can sniff and that's a bad thing. If you're not going to use a session variable for storing end user information, you're most likely going to keep some sort of State by passing the information to a cookie or push it around with GET/POST parameters. If you're passing around any sort of ID or user information like their name, it's better to err on the side of caution and encrypt the information. GET Vs. POST A POST parameter keeps the information out of the URL, but it can still be sniffed quite easily as it passes in clear text across your network or the Internet. Using POST will keep the mere curious at bay, as the information is not contained in the URL - but this will not stop someone determined to snag out your data. A QueryString parameter passes information within the site's URL. Why would you even use a QueryString? Well, maybe you need to let your user bookmark a particular page, or maybe you have to refer directly to a page in a URL via a link - you can't do either if you're using POST. A QueryString puts data in the URL for the entire world to see, so if you don't know if the end user is malicious, I'd think hard about using a QueryString for anything but site-related information. Be smart and encrypt any and all data you're moving around from page to page, especially if that information could be used maliciously. You may trust your users, but you still need that extra level of security that clear text GET/POST data doesn't provide.

Sikkim Manipal University

Page No. 364

DOT Net Technologies

Unit 10

Imagine this scenario - you've been passing the customer's ID in the database around in a QueryString, in a URL that looks like this: http://yoursite.com?cust_id=29 You know what a user is going to do? Switch that 29 to a 30 or 12 or some other number, and if you're not checking for invalid requests, you'll be dishing up some other customer's data. Enter Encryption What I was looking for was a quick way to encrypt and decrypt parts of a QueryString - it had to be on the fly, quick and dirty. I chose Base64 because it wouldn't throw bizarre characters in my QueryString that I couldn't pass around Little did I know that I'd hit a snag while passing around my encrypted QueryString - Apparently, the Request.QueryString object interprets the '+' sign as a space! So, with a quick Replace function slapped on my decrypt string, no harm, no foul. Symmetric Key The whole trick to this working is that the QueryString is encrypted and decrypted with the same private key. This is the secret key - if anyone gets a hold of your key, they can decrypt the data themselves, so keep it a secret! We're going to use a hard-to-crack 8 byte key, !#$a54?3, to keep parts of our QueryString secret. Let's Walk through the C# portion of the code: Notice our two functions that abstract the dirty work that our Encryption64 class. The first, encryptQueryString, is used to encrypt the value of a QueryString. The second, decryptQueryString, is used to decrypt the value of an encrypted QueryString.

Sikkim Manipal University

Page No. 365

DOT Net Technologies

Unit 10

public string encryptQueryString(string strQueryString) { ExtractAndSerialize.Encryption64 oES = new ExtractAndSerialize.Encryption64(); return oES.Encrypt(strQueryString,"!#$a54?3"); } public string decryptQueryString(string strQueryString) { ExtractAndSerialize.Encryption64 oES = new ExtractAndSerialize.Encryption64(); return oES.Decrypt(strQueryString,"!#$a54?3"); }

If we want to encrypt our QueryString on our first page, we could do something like this: string strValues = "search term"; string strURL = "http://yoursite.com?search=" + encryptQueryString(strValues); Response.Redirect(strURL); Inside our code-behind in our second page, we pass the contents our QueryString to a variable named strScramble. After that, we replace the '+' signs that our wonderful Request.QueryString has replaced with a space. We pass that string into our function, decryptQueryString, and retrieve the decrypted string. string strScramble = Request.QueryString["search"]; string strdeCrypt = decryptQueryString( strScramble.Replace(" ", "+")); Now we've decrypted the value of the QueryString, 'search', and we can do whatever we want with it. The end user is going to see a URL that looks like: http://yoursite.com?search=da00992Lo39+343dw

Sikkim Manipal University

Page No. 366

DOT Net Technologies

Unit 10

They'll never be able to guess what's going on in your QueryString, and if they try to fool around with it, there's no way to crack the code without knowing the Symmetric key. VB.NET Code
Imports System Imports System.IO Imports System.Xml Imports System.Text Imports System.Security.Cryptography Public Class Encryption64 Private key() As Byte = {} Private IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HE F} Public Function Decrypt(ByVal stringToDecrypt As String, _ ByVal sEncryptionKey As String) As String Dim inputByteArray(stringToDecrypt.Length) As Byte Try key = System.Text.Encoding.UTF8.GetBytes(Left(sEncryptionKey, 8)) Dim des As New DESCryptoServiceProvider() inputByteArray = Convert.FromBase64String(stringToDecrypt) Dim ms As New MemoryStream() Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), _ CryptoStreamMode.Write) cs.Write(inputByteArray, 0, inputByteArray.Length) cs.FlushFinalBlock() Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8 Return encoding.GetString(ms.ToArray()) Catch e As Exception Return e.Message End Try End Function Public Function Encrypt(ByVal stringToEncrypt As String, _ ByVal SEncryptionKey As String) As String Try key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) Dim des As New DESCryptoServiceProvider() Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes( _ stringToEncrypt) Dim ms As New MemoryStream()

Sikkim Manipal University

Page No. 367

DOT Net Technologies

Unit 10

Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), _ CryptoStreamMode.Write) cs.Write(inputByteArray, 0, inputByteArray.Length) cs.FlushFinalBlock() Return Convert.ToBase64String(ms.ToArray()) Catch e As Exception Return e.Message End Try End Function End Class

10.6 Custom Membership Providers


Introduction to Membership ASP.NET membership gives you a built-in way to validate and store user credentials. ASP.NET membership therefore helps you manage user authentication in your Web sites. You can use ASP.NET membership with ASP.NET Forms authentication or with the ASP.NET login controls to create a complete system for authenticating users. ASP.NET membership supports facilities for: Creating new users and passwords. Storing membership information (user names, passwords, and

supporting data) in Microsoft SQL Server, Active Directory, or an alternative data store. Authenticating users who visit your site. You can authenticate users programmatically, or you can use the ASP.NET login controls to create a complete authentication system that requires little or no code. Managing passwords, which includes creating, changing, and resetting them . Depending on membership options you choose, the membership system can also provide an automated password-reset system that takes a user-supplied question and response.

Sikkim Manipal University

Page No. 368

DOT Net Technologies

Unit 10

Exposing a unique identification for authenticated users that you can use in your own applications and that also integrates with the ASP.NET personalization and role-management (authorization) systems.

Specifying a custom membership provider, which allows you to substitute your own code to manage membership and maintain membership data in a custom data store

Membership, Roles and the User Profile Although membership is a self-standing feature in ASP.NET for

authentication, it can be integrated with ASP.NET role management to provide authorization services for your site. Membership can also be integrated with the user profile to provide application-specific customization that can be tailored to individual users. How Membership Works? To use membership, you must first configure it for your site. In outline, you follow these steps: 1. Specify membership options as part of your Web site configuration. By default, membership is enabled. You can also specify what membership provider you want to use. (In practical terms, this means that you are specifying what type of database you want to keep membership information in.) The default provider uses a Microsoft SQL Server database. You can also choose to use Active Directory to store membership information, or you can specify a custom provider. 2. Configure your application to use Forms authentication (as distinct from Windows or Passport authentication). You typically specify that some pages or folders in your application are protected and are accessible only to authenticated users. 3. Define user accounts for membership. You can do this in a variety of ways. You can use the Web Site Administration Tool, which provides a wizard-like interface for creating new users. Alternatively, you can create
Sikkim Manipal University Page No. 369

DOT Net Technologies

Unit 10

a "new user" ASP.NET Web page where you collect a user name and password (and optionally an e-mail address), and then use a membership function named CreateUser to create a new user in the membership system. 4. You can now use membership to authenticate users in your application. Most often, you will provide a login form, which might be a separate page or a special area on your home page. You can create the login form by hand using ASP.NET TextBox controls, or you can use ASP.NET login controls. Because you have configured the application to use Forms authentication, ASP.NET will automatically display the login page if an unauthenticated user requests a protected page. If you use login controls, they will automatically use the membership system to validate a user. If you have created a login form by hand, you can prompt the user for a user name and password and then call the ValidateUser method to perform the validation. After the user is validated, information about the user can be persisted (for example, with an encrypted cookie if the user's browser accepts cookies) using Forms Authentication. The login controls perform this task automatically. If you have created a login form by hand, you can call methods of the FormsAuthentication class to create the cookie and write it to the user's computer. If a user has forgotten his or her password, the login page can call membership functions that help the user remember the password or create a new one. Each time the user requests another protected page, ASP.NET Forms authentication checks whether the user is authenticated and then either allows the user to view the page or redirects the user to the login page. By default, the authentication cookie remains valid for the user's session. After a user has been authenticated, the membership system makes available an object that contains information about the current user. For example, you can get properties of the membership user object to determine
Sikkim Manipal University Page No. 370

DOT Net Technologies

Unit 10

the user's name and e-mail address, when the user last logged into your application, and so on. An important aspect of the membership system is that you never need to explicitly perform any low-level database functions to get or set user information. For example, you create a new user by calling the membership CreateUser method. The membership system handles the details of creating the necessary database records to store the user information. When you call the ValidateUser method to check a user's credentials, the membership system does all the database lookup for you. Membership Configuration and Management You configure the membership system in your application's Web.config file. The easiest way to configure and manage membership is with the Web Site Administration Tool, which provides a wizard-based interface. As part of membership configuration, you specify: What membership provider to use. (This typically specifies what database to store membership information in.) Password options such as encryption and whether to support password recovery based on a user-specific question. Users and passwords. If you are using the Web Site Administration Tool, you can create and manage users directly. Otherwise, you must call membership functions to create and manage users programmatically.

10.7 Authorization and Roles


ASP.NET Authorization Authorization determines whether an identity should be granted access to a specific resource. In ASP.NET, there are two ways to authorize access to a given resource:

Sikkim Manipal University

Page No. 371

DOT Net Technologies

Unit 10

File

Authorization: File

authorization

is

performed

by

the

FileAuthorizationModule. It checks the access control list (ACL) of the .aspx or .asmx handler file to determine whether a user should have access to the file. ACL permissions are verified for the user's Windows identity (if Windows authentication is enabled) or for the Windows identity of the ASP.NET process. URL authorization: URL authorization is performed by the

UrlAuthorizationModule, which maps users and roles to URLs in ASP.NET applications. This module can be used to selectively allow or deny access to arbitrary parts of an application (typically directories) for specific users or roles. Using URL Authorization With URL authorization, you explicitly allow or deny access to a particular directory by user name or role. To do so, you create an authorization section in the configuration file for that directory. To enable URL authorization, you specify a list of users or roles in the allow or deny elements of the authorization section of a configuration file. The permissions established for a directory also apply to its subdirectories, unless configuration files in a subdirectory override them. The following shows the syntax for the authorization section:
<authorization> <[allow|deny] usersrolesverbs /> </authorization>

The allow or deny element is required. You must specify either the users or the roles attribute. Both can be included, but both are not required. The verbs attribute is optional. The allow and deny elements grant and revoke access, respectively. Each element supports the attributes shown in the following table:

Sikkim Manipal University

Page No. 372

DOT Net Technologies

Unit 10

Attribute users

Description Identifies the targeted identities (user accounts) for this element. Anonymous users are identified using a question mark (?). You can specify all authenticated users using an asterisk (*). Identifies a role (a RolePrincipal object) for the current request that is allowed or denied access to the resource. Defines the HTTP verbs to which the action applies, such as GET, HEAD, and POST. The default is "*", which specifies all verbs.

roles verbs

Rules are applied as follows: Rules contained in application-level configuration files take precedence over inherited rules. The system determines which rule takes precedence by constructing a merged list of all rules for a URL, with the most recent rules (those nearest in the hierarchy) at the head of the list. Given a set of merged rules for an application, ASP.NET starts at the head of the list and checks rules until the first match is found. The default configuration for ASP.NET contains an <allow users="*"> element, which authorizes all users. (By default, this rule is applied last.) If no other authorization rules match, the request is allowed. If a match is found and the match is a deny element, the request is returned with the 401 HTTP status code. If an allow element matches, the module allows the request to be processed further. In a configuration file, you can also create a location element to specify a particular file or directory to which settings in that the location element should apply. Using Roles for Client Authorization You use role-based security to establish an authorization policy, determining which client or clients to let in and with what authority. You are deciding who should be able to perform which actions and access which resources.

Sikkim Manipal University

Page No. 373

DOT Net Technologies

Unit 10

Roles facilitate this by acting as an access control mechanism invoked whenever a user attempts to access any application resource. A role is basically a list of users more precisely, a symbolic category of users that share the same security privilege. When you assign a role to an application resource, you are granting access permission for that resource to whoever is a member of that role. Therefore, you can define a very particular security privilege by declaring it as a role and then assigning the role to specific resources. When the application is deployed, the system administrator can populate the role with actual users and user groups. When the application runs, COM+ will enforce the policy by carrying out role checks. Fundamentally, roles help protect your code that is, the methods that can be called by clients of a COM+ application. Role membership is checked whenever a client attempts to call a method exposed by a component in an application. If the caller is in a role assigned to the called method, or resource, the call succeeds; otherwise, it fails. Declarative Role-Based Security With declarative role-based security, you administratively declare roles using either the Component Services administrative tool or the Administrative SDK functions and administratively assign them to application resources. Where and how you set declarative security will determine where security boundaries are drawn for your application. You can assign a given role to the entire application, to a particular component, to a particular interface in a component, or to a particular method on an interface. Role assignments are inherited down the natural chain of inclusion that is, if you assign a role to a component, it is implicitly assigned to every interface and method exposed by that component.

Sikkim Manipal University

Page No. 374

DOT Net Technologies

Unit 10

With the availability of method-level role assignments, you can effectively help protect components and interfaces that have not been designed with security in mind. However, if the methods themselves are not securable with declarative role assignments, you might need to do programmatic role checking. It is generally a good idea to keep security in mind when deciding how to factor business functionality through methods; otherwise, you could find yourself adding in security-related code at the last minute. Programmatic Security In some circumstances you may want to put security logic into components while still using role-based security. It might be that you're not able to or choose not to factor all access decisions through methods. For example, you might have a private application resource, perhaps a particular database, that you want to allow only some callers of a method to access while excluding others. Or you might have a single TransferMoney method and want to restrict some callers by limiting the amount they can transfer. In such circumstances, you can do role checking in code. A simple API is provided, enabling you to check whether security is turned on and whether a caller or a particular user is in a given role. This functionality is available only when role-based security is enabled. This means that you can still take advantage of declarative role-based security where it suffices, and then you can programmatically extend it to a finer level of granularity when necessary. Additionally, when you use role-based security, you have programmatic access to information regarding all upstream callers in the chain of calls to your component. This is especially useful when you want to keep a detailed audit trail.

Sikkim Manipal University

Page No. 375

DOT Net Technologies

Unit 10

Authorization vs. Authentication Meaningful authorization presupposes that you are confident that clients are actually who they say they are. The verification of client identity is handled separately by an authentication service. Without authentication, you are basically letting callers in on the honor system.

10.9 Summary
Sometimes there may be a need to build pages or sections of an application that are accessible to only a select group of your choosing. The Security measures indicated in this unit help protect the data behind your applications and the applications themselves from fraudulent use. This unit introduces the user to the ASP.NET security model. It demonstrates various From Authentication and Window Authentication measures,. It describes the Memberships, Authorization and roles in ASP.NET security model. It discusses the various cryptographic classes present in ASP.ENT. It also discusses the Custom membership providers in ASP.NET. Self Assessment Questions 1. ________ authenticates the caller by using Basic, Digest, Integrated (NTLM or Kerberos), or Certificate authentication. 2. If ASP.NET is configured for ______ authentication, no additional authentication occurs at this point. 3. The ______________ , a system provided HTTP module, uses authorization rules configured in Web.config (specifically, the <authorization> element) to ensure that the caller can access the requested file or folder. 4. The _______________ class only performs access checks against the requested file, and not for files accessed by the code in the requested page, although these are access checked by IIS. 5. __________ permission checks (performed by the PrincipalPermission Attribute class) allows you to control access to classes, methods, or individual code blocks based on the identity and group membership of
Sikkim Manipal University Page No. 376

DOT Net Technologies

Unit 10

individual users, as defined by the IPrincipal object attached to the current thread. 6. If you configure ASP.NET for_______________ , IIS performs user authentication by using the configured IIS authentication mechanism. 7. ___________ is used to achieve the goals of Confidentiality, Data Integrity, and Authentication. 8. The ________ type of encryption uses a public/private key pair to

encrypt and decrypt data. 9. The ________ .Net cryptographic class performs asymmetric encryption and decryption using the Cryptographic Application Programming Interfaces (CAPI) implementation of the Advanced Encryption Standard (AES) algorithm.

10.10 Terminal Questions


1. Discuss the ASP.NET Security Model (Refer to 10.1) 2. Discuss the following: Forms Authentication (Refer to 10.2) Windows Authentication (Refer to 10.4)

3. Discuss about the concept of Cryptography (Refer to 10.7)

10.11 Answers to Self Assessment Questions


1. IIS 2. Windows 3. UrlAuthorizationModule 4. FileAuthorizationModule 5. Principal 6. Windows authentication 7. Cryptography 8. Public-key encryption 9. AesCryptoServiceProvider
Sikkim Manipal University Page No. 377

DOT Net Technologies

Unit 10

References:

Sikkim Manipal University

Page No. 378

DOT Net Technologies

Unit 4

Unit 4
Structure: 4.1 Introducing the ASP.NET Architecture Objectives 4.2 4.3 4.4 Master Pages Themes & Control Skins Summary Self Assessment Questions 4.5 4.6 Terminal Questions Answers to Self Assessment Questions

ASP.NET

4.1 Introducing the ASP.NET Architecture


ASP.NET Server Controls ASP.NET Web Server controls are objects on ASP.NET Web pages that run when the page is requested and render markup to a browser. Many Web server controls are similar to familiar HTML elements, such as buttons and text boxes. Other controls encompass complex behavior, such as calendar controls, and controls that manage data connections. ASP.NET Web Server Controls Overview When you create ASP.NET Web pages, you can use these types of controls: HTML Server Controls: They are the HTML elements exposed to the server so you can program them. HTML server controls expose an object model that maps very closely to the HTML elements that they render. Web Server Controls: They are the Controls with more built-in features than HTML server controls. Web server controls include not only form controls such as buttons and text boxes, but also specialSikkim Manipal University Page No. 108

DOT Net Technologies

Unit 4

purpose controls such as a calendar, menus, and a tree view control. Web server controls are more abstract than HTML server controls in that their object model does not necessarily reflect HTML syntax. Validation Controls: They are the Controls that incorporate logic to enable you to what users enter for input controls such as the TextBox control. Validation controls enable you to check for a required field, to test against a specific value or pattern of characters, to verify that a value lies within a range, and so on. User Controls: They are the Controls that you create as ASP.NET

Web pages. You can embed ASP.NET user controls in other ASP.NET Web pages, which is an easy way to create toolbars and other reusable elements. HTML Server Controls HTML server controls are HTML elements (or elements in other supported markup, such as XHTML) containing attributes that make them

programmable in server code. By default, HTML elements on an ASP.NET Web page are not available to the server. Instead, they are treated as opaque text and passed through to the browser. However, by converting HTML elements to HTML server controls, you expose them as elements you can program on the server. The object model for HTML server controls maps closely to that of the corresponding elements. For example, HTML attributes are exposed in HTML server controls as properties. Any HTML element on a page can be converted to an HTML server control by adding the attribute runat="server". During parsing, the ASP.NET page framework creates instances of all elements containing the runat="server" attribute. If you want to refer to the control as a member within your code, you should also assign an id attribute to the control.
Sikkim Manipal University Page No. 109

DOT Net Technologies

Unit 4

The page framework provides predefined HTML server controls for the HTML elements most commonly used dynamically on a page: the form element, the input elements (text box, check box, Submit button), the select element, and so on. These predefined HTML server controls share the basic properties of the generic control, and in addition, each control typically provides its own set of properties and its own event. HTML Server Control Features: An object model that you can program against on the server using familiar object-oriented techniques. Each server control exposes properties that enable you to manipulate the control's markup attributes programmatically in server code. A set of events for which you can write event handlers in much the same way you would in a client-based form, except that the event is handled in server code. The ability to handle events in client script. Automatic maintenance of the control's state. When the page makes a round trip to the server, the values that the user entered into HTML server controls are automatically maintained and sent back to the browser. Interaction with ASP.NET validation controls so you can verify that a user has entered appropriate information into a control. Data binding to one or more properties of the control. Support for styles if the ASP.NET Web page is displayed in a browser that supports cascading style sheets. Pass-through of custom attributes. You can add any attributes you need to an HTML server control and the page framework will render them without any change in functionality. This enables you to add browserspecific attributes to your controls.

Sikkim Manipal University

Page No. 110

DOT Net Technologies

Unit 4

Working with Web Server Controls Web server controls are a second set of controls designed with a different emphasis. They do not necessarily map one-to-one to HTML server controls. Instead, they are defined as abstract controls in which the actual markup rendered by the control can be quite different from the model that you program against. For example, a RadioButtonList Web server control might be rendered in a table or as inline text with other markup. Web server controls include traditional form controls such as buttons and text boxes as well as complex controls such as tables. They also include controls that provide commonly used form functionality such as displaying data in a grid, choosing dates, displaying menus, and so on. The controls use syntax such as the following: <asp:button attributes runat="server" id="Button1" /> The attributes in this case are not those of HTML elements. Instead, they are properties of the Web control. When the ASP.NET Web page runs, the Web server control is rendered on the page using appropriate markup, which often depends not only on the browser type but also on settings that you have made for the control. For example, a TextBox control might render as an input tag or a textarea tag, depending on its properties. You add controls to an ASP.NET Web page much the same way you add any HTML element. You can either use a visual designer and add a control from the toolbox, or you can type the element representing the control into the page's markup. To add a Web server control using the designer 1. Switch to Design view.

Sikkim Manipal University

Page No. 111

DOT Net Technologies

Unit 4

2. From the Standard tab of the Toolbox, drag the control onto the page. A glyph ( ) appears on the control in Design view to indicate that it is a server-based control. At times it is more practical to create a control at run time than at design time. For example, imagine a search results page in which you want to display results in a table. Because you do not know how many items will be returned, you want to dynamically generate one table row for each returned item. Note: Existing controls can often provide the functionality you get from creating controls dynamically. For example, controls such as the Repeater, DataList, and RadioButtonList controls can dynamically create rows or other control elements when the page runs. In order to programmatically add a control to a page, there must be a container for the new control. For example, if you are creating table rows, the container is the table. If there is no obvious control to act as container, you can use a PlaceHolder or Panel Web server control. In some instances, you might want to create both static text and controls. To create static text, you can use either a Literal or a Label Web server control. You can then add these controls to the container as you would any other control. To add a control to an ASP.NET Web page programmatically 1. Create an instance of the control and set its properties, as shown in the following example:
C# Code Label myLabel = new Label(); myLabel.Text = "Sample Label";

Sikkim Manipal University

Page No. 112

DOT Net Technologies

Unit 4

2. Add the new control to the Controls collection of a container already on the page, as shown in the following example:
C# Code Panel Panel1= new Panel(); Panel1.Controls.Add(myLabel);

Note: Because the Controls property is a collection, you can use the AddAt method to place the new control at a specific location for example, in front of other controls. However, this can introduce errors into the page. The following code example shows the event handler for the

SelectedIndexChanged event of a control named DropDownList1. The handler creates as many label controls as the user has selected from the drop-down list. The container for the controls is a PlaceHolder Web server control named Placeholder1.
C# Code private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e) { DropDownList DropDownList1 = new DropDownList(); PlaceHolder PlaceHolder1 = new PlaceHolder();

// Get the number of labels to create. int numlabels = System.Convert.ToInt32(DropDownList1.SelectedItem.Text); for (int i=1; i<=numlabels; i++) { Label myLabel = new Label(); // Set the label's Text and ID properties. myLabel.Text = "Label" + i.ToString(); myLabel.ID = "Label" + i.ToString(); PlaceHolder1.Controls.Add(myLabel); // Add a spacer in the form of an HTML <br /> element. PlaceHolder1.Controls.Add(new LiteralControl("<br />")); }}

Sikkim Manipal University

Page No. 113

DOT Net Technologies

Unit 4

How to: Set ASP.NET Web Server Control Properties Setting a control's properties defines its appearance and behavior. This topic addresses how to set control properties declaratively. To set server controls properties In the ASP.NET Web page, set the attribute of the control declaration corresponding to the property you want. The exact attribute you set depends on the control and the property. For information about the properties for a specific control, search for the name of the control class (for example, "Button class

(System.Web.UI.WebControls)" in the Help index. The following example shows how to set the MaxLength property of a TextBox control:
<asp:textbox id="TextBox1" runat=server maxlength=20 />

Setting Server Control Properties Based on Simple Values or Enumerations If a Web server control property's data type is a primitive type, such as a String, Boolean, or numeric type, you can set the property value by simply assigning it to the property. Similarly, if the property's values are defined in an enumeration class, you can simply assign the enumeration to the property. To set a property value based on simple values

Assign the value as a literal or variable, as in the following example:


C# Syntax Label1.Text = "Hello"; DataGrid1.PageSize = 5;

Sikkim Manipal University

Page No. 114

DOT Net Technologies

Unit 4

Setting a property value based on an enumeration Assign the value using one of the enumeration values. ASP.NET can resolve the enumeration based on the property's type. The following code example illustrates setting a property using an enumeration:
C# Syntax // Uses TextBoxMode enumeration TextBox1.TextMode = TextBoxMode.SingleLine; // Uses ImageAlign enumeration Image1.ImageAlign = ImageAlign.Middle;

Setting HTML Server Control Properties Programmatically HTML server controls are of two slightly different types. The HTML elements most commonly used in forms are available as individual HTML server controls, such as HtmlInputText, HtmlInputButton, HtmlTable, and so on. These HTML server controls expose their own, control-specific properties that map directly to HTML attributes. However, any HTML element can be converted to a control. In that case, the element becomes an HtmlGenericControl with base class properties such as TagName, Visible, and InnerHTML. Setting properties of HTML server controls Get or set the property name as you would with any object. All properties are either strings or integers. The following example illustrates setting property names:
C# Syntax myAnchor.HRef = "http://www.microsoft.com"; Text1.MaxLength = 20; Text1.Text = string.Format("{0:$####}", TotalCost); Span1.InnerHtml = "You must enter a value for Email Address";

Sikkim Manipal University

Page No. 115

DOT Net Technologies

Unit 4

Setting Attributes All HTML server controls also support an Attributes collection, which gives you direct access to all the control's attributes. This is particularly useful for working with attributes that are not exposed as individual properties. Working with control attributes directly Use the properties and methods of a control's Attributes collection, such as Add, Remove, Clear, and Count. The Keys property returns a collection containing the names of all the attributes in the control. The following examples show various ways to use the Attributes collection:
C# Syntax // Adds a new attribute. Text1.Attributes.Add("bgcolor", "red"); // Removes one attribute. Text1.Attributes.Remove("maxlength");

C# Syntax // Adds a new attribute. Text1.Attributes.Add("bgcolor", "red"); // Removes one attribute. Text1.Attributes.Remove("maxlength"); // Removes all attributes, clearing all properties. Text1.Attributes.Clear(); // Creates comma-delimited list of defined attributes string strTemp = ""; foreach (string key in Text1.Attributes.Keys) { strTemp += Text1.Attributes[key] + ", "; }

User Controls The simple controls are so named because most emit only a few lines of HTML. Some return client-side script too, but only under special
Sikkim Manipal University Page No. 116

DOT Net Technologies

Unit 4

circumstances. Theyre exceedingly easy to use, and thus are a great starting point for an exploration of Web controls. TextBox Controls TextBox controls are the ASP.NET equivalent of <input type=text/password> and <textarea> tags in HTML. Their purpose? To create text input fields in Web forms. The statement <asp:TextBox ID="UserName" RunAt="server" /> creates a text input field in a Web form and assigns it the programmatic ID UserName. You can use a TextBoxs Text property to declaratively insert text into a TextBox and also to read and write TextBox text from a serverside script. The following statement creates a TextBox that initially contains the string Elmo: <asp:TextBox ID="UserName" Text="Elmo" RunAt="server" /> And the following server-side script reads the contents of the TextBox: string name = UserName.Text; Label Controls Label controls are among the simplest of all Web controls. They add programmable textual labels to Web forms. A Label controls Text property exposes the control text. The following statement adds Hello to a Web page: <asp:Label Text="Hello" RunAt="server" /> A Label control declared this way renders itself to the Web page as a <span> tag: <span>Hello</span> Spans are benign HTML tags that are used to group other HTML elements. Label controls frequently serve as placeholders for output written by serverside scripts.

Sikkim Manipal University

Page No. 117

DOT Net Technologies

Unit 4

HyperLink Controls HyperLink controls add hyperlinks to Web forms. HyperLink controls come in two forms: text hyperlinks and image hyperlinks. The following statement creates a hyperlink that renders itself as a text string and points to www.wintellect.com: <asp:HyperLink Text="Click here" NavigateUrl="http://www.wintellect.com" RunAt="server" /> A slight modification transforms the hyperlink into an image that targets the same URL: <asp:HyperLink ImageUrl="logo.jpg" NavigateUrl="http://www.wintellect.com" RunAt="server" /> Text hyperlinks render as <a href> tags; image hyperlinks render as <img> tags enclosed in <a href> tags. You normally include either a Text or an ImageUrl attribute in an <asp:HyperLink> tag, but not both. However, if you do specify both, the control uses the text you specify as a tool tip in supportive browsers. The HyperLink class exposes a Target property that can be used to control how the targeted Web page is displayed. For example, the statement <asp:HyperLink Text="Click here" Target="_new" NavigateUrl="http://www.wintellect.com" RunAt="server" /> opens the page in a new browser window. Any value thats valid for a Target attribute in an <a> tag is also valid in a HyperLink. Another use for Target attributes is to open pages in specific windows or frames. Image Controls Image controls add images to Web forms by emitting <img> tags. Images most important properties are ImageUrl, which specifies the URL of the image that the control renders; ImageAlign, which controls the alignment of

Sikkim Manipal University

Page No. 118

DOT Net Technologies

Unit 4

the image; and AlternateText, which specifies the images alternate text. Alternate text is displayed in place of the image in text-only browsers. The following statement declares an Image control in a Web form: <asp:Image ImageUrl="logo.jpg" AlternateText="Company Logo" RunAt="server" /> Image controls are perfect for displaying images whose URLs are assigned at run time, possibly in response to user input. For static images, you can reduce overhead by using conventional <img> tags instead. CheckBox Controls CheckBox controls place check boxes in Web forms. (Surprise!) A CheckBoxs Checked property determines whether the check box is checked (true) or unchecked (false), and its Text property controls the text displayed beside the check box. The following code declares a CheckBox control in a Web form: <asp:CheckBox ID="Confirm" Text="E-mail my confirmation" RunAt="server" /> And this server-side script determines whether the check box is checked when the form is submitted to the server:
if (Confirm.Checked) { // The box is checked } else { // The box is not checked }

On the off chance that youd like to reverse the positions of a check box and the text that normally appears to its right, include a TextAlign=Left attribute in the control tag.

Sikkim Manipal University

Page No. 119

DOT Net Technologies

Unit 4

CheckBox controls fire CheckedChanged events when theyre checked and unchecked. By default, a CheckedChanged event doesnt fire the moment the check box is clicked; it waits until the page posts back to the server. To respond immediately to changes in a check boxs state, set the controls AutoPostBack property to true to force postbacks:
<asp:CheckBox ID="Confirm" Text="E-mail my confirmation" AutoPostBack="true" OnCheckedChanged="DoItNow" RunAt="server" /> . . . <script language="C#" runat="server"> void DoItNow (Object sender, EventArgs e) { // The check box was just checked or unchecked; do something! } </script>

Dont set AutoPostBack to true unless you really need CheckedChanged events to fire immediately. One justification for setting AutoPostBack to true is to dynamically change the contents of the page each time the check box is clicked. RadioButton Controls RadioButton controls create radio buttons in Web forms. Radio buttons present users with mutually exclusive lists of choices. Clicking a radio button checks that radio button and unchecks other radio buttons in the group. RadioButton derives from CheckBox and therefore supports the same properties and events that CheckBox supports. It also adds a GroupName property for designating the group that a radio button belongs to. The following code declares five RadioButton controls and divides them into two groups: one group of three and another group of two. It also uses the RadioButton.Checked property to check the first radio button in each group:
Sikkim Manipal University Page No. 120

DOT Net Technologies

Unit 4

<asp:RadioButton Text="Red" ID="Button1" Checked="true" GroupName="Colors" RunAt="server" /><br> <asp:RadioButton Text="Green" ID="Button2" GroupName="Colors" RunAt="server" /><br> <asp:RadioButton Text="Blue" ID="Button3" GroupName="Colors" RunAt="server" /><br> <br> <asp:RadioButton Text="Circle" ID="Button4" Checked="true"

GroupName="Shape" RunAt="server" /><br> <asp:RadioButton Text="Square" ID="Button5" GroupName="Shape" RunAt="server" />

Grouping these controls by using the GroupName attribute is important because it tells the browser which radio buttons to uncheck when a radio button is checked. Figuring out which radio button in a group of radio buttons is checked from a server-side script requires checking each buttons Checked property one by one. A better way to add radio buttons to a Web page is to use a RadioButtonList. Its SelectedIndex property identifies the button thats checked. Table Controls Table controls add HTML tables to Web forms. They render a

combination of <table>, <tr>, and <td> tags to browsers. Heres one way to add a table to a Web form:
<table> <tr> <td>Row 1, Column 1</td> <td>Row 1, Column 2</td> </tr> <tr> <td>Row 2, Column 1</td> <td>Row 2, Column 2</td> </tr> </table> Sikkim Manipal University Page No. 121

DOT Net Technologies

Unit 4

And heres the equivalent table created with a Table control:


<asp:Table ID="MyTable" RunAt="server"> <asp:TableRow> <asp:TableCell>Row 1, Column 1</asp:TableCell> <asp:TableCell>Row 1, Column 2</asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell>Row 2, Column 1</asp:TableCell> <asp:TableCell>Row 2, Column 2</asp:TableCell> </asp:TableRow> </asp:Table>

Table controls add value to a Web form when you want to change a tables contents dynamically. By default, a Table controls borders are invisible. You can change that by setting the controls GridLines property to Horizontal, Vertical, or Both. Other useful Table properties include CellPadding and CellSpacing, which, like the HTML attributes of the same name, control the spacing within and between cells, and BackImageUrl, which identifies a background image. Tables are often used in Web pages to paint colored backgrounds. To change a Table objects background color, use the BackColor property that Table inherits from WebControl. Panel Controls Panel controls serve as containers for other controls. One use for Panel controls is to control the visibility of a group of controls. The following Web form toggles four Label controls on and off by setting a Panel controls Visible property to true or false each time a check box is clicked. Note the AutoPostBack=true attribute in the <asp:CheckBox> tag:

Sikkim Manipal University

Page No. 122

DOT Net Technologies

Unit 4

<html> <body> <form runat="server"><br> <asp:CheckBox ID="Toggle" Text="Show Labels" Checked="true" AutoPostBack="true" OnCheckedChanged="OnToggle" RunAt="server" /> <asp:Panel ID="MyPanel" RunAt="server"> <asp:Label Text="John" RunAt="server" /><br> <asp:Label Text="Paul" RunAt="server" /><br> <asp:Label Text="George" RunAt="server" /><br> <asp:Label Text="Ringo" RunAt="server" /><br> </asp:Panel> </form> </body> </html> <script language="C#" runat="server"> void OnToggle (Object sender, EventArgs e) { MyPanel.Visible = Toggle.Checked; } </script>

Another use for Panel controls is to specify horizontal alignment for a group of controls:
<asp:Panel HorizontalAlign="Center" ID="MyPanel" RunAt="server"> <asp:Label Text="John" RunAt="server" /><br> <asp:Label Text="Paul" RunAt="server" /><br> <asp:Label Text="George" RunAt="server" /><br> <asp:Label Text="Ringo" RunAt="server" /><br> </asp:Panel>

Panel controls render as HTML <div> tags. Therefore, its appropriate to use them any time you would ordinarily use a <div> tag but want to change the attributes of that tag dynamically.
Sikkim Manipal University Page No. 123

DOT Net Technologies

Unit 4

Button Controls The Web controls family includes three types of button controls: Button, LinkButton, and ImageButton. Functionally, all three do exactly the same thing: they submit the form that hosts them to the server. The difference lies in their physical appearance. A Button control looks like a push button, a LinkButton looks like a hyperlink, and an ImageButton renders itself using an image you supply. Nearly every Web form uses one or more buttons to enable the user to submit the form to the server. The following statements declare an instance of each control type in a Web form:
<asp:Button Text="Sort" RunAt="server" /> <asp:LinkButton Text="Sort" RunAt="server" /> <asp:ImageButton ImageUrl="sort.jpg" RunAt="server" />

The Text property specifies the text that appears on the face of a Button or LinkButton. ImageUrl identifies the image displayed by an ImageButton. All three button controls fire two kinds of events when clicked: a Click event and a Command event. An OnClick attribute in the control tag wires a button to a Click handler. Click handlers for Button and LinkButton controls are prototyped this way: void OnClick (Object sender, EventArgs e) { // Event handling code goes here } But Click handlers for ImageButton controls are prototyped like this: void OnClick (Object sender, ImageClickEventArgs e) { // Extract the click coordinates int x = e.X; int y = e.Y; }
Sikkim Manipal University Page No. 124

DOT Net Technologies

Unit 4

The ImageClickEventArgs passed to an ImageButtons Click handler contains public fields named X and Y that specify where in the image the click occurred. X and Y are measured in pixels and represent distances from the images upper left corner. List Controls The list controls family has four members: ListBox DropDownList CheckBoxList, and RadioButtonList.

All four have two important characteristics in common: they all derive from System.Web.UI.WebControls.ListControl, and theyre all designed to present a list of items to the user. ListBox and DropDownList controls display textual items that the user can select. Both render back to the browser as HTML <select> tags. CheckBoxList and RadioButtonList display arrays of check boxes and radio buttons and render as <input type=checkbox> and <input type=radio> tags, respectively. The <input> tags are optionally contained in an HTML table for alignment purposes. ListBox Control Items in a list control are represented by instances of ListItem. Instances of ListItem are declared with <asp:ListItem> tags. Inside a ListItem are string properties named Text and Value. Text exposes the text that represents the item in a list control; Value allows an arbitrary string to be associated with the item. ListItem also exposes a Boolean property named Selected that determines whether the item is selected. The following statements declare a ListBox control containing four items and select the second item:
<asp:ListBox ID="MyListBox" RunAt="server"> <asp:ListItem Text="John" RunAt="server" /> <asp:ListItem Text="Paul" Selected="true" RunAt="server" /> <asp:ListItem Text="George" RunAt="server" /> <asp:ListItem Text="Ringo" RunAt="server" /> </asp:ListBox>

Sikkim Manipal University

Page No. 125

DOT Net Technologies

Unit 4

A minor change to the code produces a DropDownList instead of a ListBox:


<asp:DropDownList ID="MyDropDownList" RunAt="server"> <asp:ListItem Text="John" RunAt="server" /> <asp:ListItem Text="Paul" Selected="true" RunAt="server" /> <asp:ListItem Text="George" RunAt="server" /> <asp:ListItem Text="Ringo" RunAt="server" /> </asp:DropDownList>

In a ListBox or DropDownList, a ListItems Selected property determines whether the item is selected (true) or not selected (false). In a CheckBoxList or RadioButtonList, the same property determines whether the

corresponding control is checked or unchecked. DropDownList Controls DropDownList controls display items in a drop-down list that resembles a Windows combo box. A classic use for DropDownList controls is to display a list of the 50 U.S. states in a form that solicits an address. The following code sample presents such a list and echoes the users choice to the Web page:
<html> <body> <form runat="server"> <asp:DropDownList ID="StateList" RunAt="server"> <asp:ListItem Text="AL" RunAt="server" /> <asp:ListItem Text="AK" RunAt="server" /> <asp:ListItem Text="AR" RunAt="server" /> </asp:DropDownList> <asp:Button Text="Submit" OnClick="OnSubmit" RunAt="server" /> <br> <asp:Label ID="Output" RunAt="server" /> </form> </body> </html>

Sikkim Manipal University

Page No. 126

DOT Net Technologies <script language="C#" runat="server"> void OnSubmit (Object sender, EventArgs e) { Output.Text = StateList.SelectedItem.Text; } </script>

Unit 4

CheckBoxList Controls The CheckBoxList control creates an array of check boxes. The following statements display four vertically stacked check boxes:
<asp:CheckBoxList ID="MyCheckBoxList" RunAt="server"> <asp:ListItem Text="John" RunAt="server" /> <asp:ListItem Text="Paul" RunAt="server" /> <asp:ListItem Text="George" RunAt="server" /> <asp:ListItem Text="Ringo" RunAt="server" /> </asp:CheckBoxList>

To determine whether a given check box is checked, read its Selected property from a server-side script:
// Is the third check box checked? if (MyCheckBoxList.Items[2].Selected) { // The check box is checked else { // The check box is not checked }

RadioButtonList Controls RadioButtonList simplifies the task of creating groups of radio buttons and finding out which radio button in a group is selected. The statements create
<asp:RadioButtonList ID="MyRadioButtonList" RunAt="server"> <asp:ListItem Text="John" Selected="true" RunAt="server" /> <asp:ListItem Text="Paul" RunAt="server" /> <asp:ListItem Text="George" RunAt="server" /> <asp:ListItem Text="Ringo" RunAt="server" /> </asp:RadioButtonList> Sikkim Manipal University Page No. 127

DOT Net Technologies

Unit 4

a column of radio buttons and check the first one. A server-side script can use RadioButtonList.SelectedIndex to determine which button the user selected: int index = MyRadioButtonList.SelectedIndex; Data-Bound Controls Speaking of data binding: the WebControls namespace includes three controls whose primary mission in life is to bind to data sources and display the results as HTML. The controls are Repeater, DataList, and DataGrid. Repeater Controls Repeater controls provide a flexible and easy-to-use mechanism for displaying repetitive lists of items. A repeater has no default user interface; you tell a Repeater what to display and how to display it. DataList Controls DataList controls are similar to Repeater controls, but they include features that Repeaters dont. Specifically, they add support for multicolumn formatting, item selection, and item editing. Multicolumn layouts are controlled with the RepeatColumns and RepeatDirection properties. Item selection is controlled with the SelectedIndex property, which holds the 0-based index of the item thats currently selected, and the SelectedItemStyle and SelectedItemTemplate properties, which govern the appearance of items that are in the selected state. To enable users to edit the items in a DataList, use the controls EditItemStyle and EditItemTemplate properties to define the appearance of the item thats being edited. The related EditItemIndex property specifies which item is currently being edited. DataGrid Controls DataGrid controls are the most complex of the data-bound Web controls for the simple reason that they offer the richest variety of options. The DataGrids purpose is to display tabular data. A single DataGrid control can

Sikkim Manipal University

Page No. 128

DOT Net Technologies

Unit 4

replace reams of old ASP code that queries a database and manually outputs a table using repeated calls to Response. Custom Controls In addition to creating user controls, which are essentially reusable small web pages, you can also create your own compiled custom controls. There are three ways to create custom controls: Create a derived custom control by deriving from an existing control. Create a composite control by grouping existing controls together into a new compiled control. Create a full custom control by deriving from System.Web.UI.WebControls.WebControl. Composite controls are most similar to user controls. The key difference is that composite controls are compiled into a DLL and used as you would any server control. To get started, you'll create a Web Control Library in which you'll create the various custom controls for this chapter. Open Visual Studio .NET and choose New Project. In the New Project Window, select either Visual C# Projects or Visual Basic Projects and create a Web Control Library called CustomControls, as shown in Figure 4.1 below:

Figure 4.1: Custom control New Project window Sikkim Manipal University Page No. 129

DOT Net Technologies

Unit 4

You'll notice that Visual Studio has created a complete custom control named WebCustomControl1. Before examining this control, create a Web Application to test it. From the File menu choose New Project (Ctrl-Shift-N) and create a project named CustomControlWebPage in the same directory. Be sure to choose the "Add to Solution" radio button, as shown in Figure 4.2 below:

Figure 4.2: Add custom control web page

You'll create a series of custom controls and test them from this application. Right-click on the CustomControls project to bring up the context menu, and choose Properties, as shown in Figure 4.3 below:

Figure 4.3: Choosing project properties Sikkim Manipal University Page No. 130

DOT Net Technologies

Unit 4

Choose the configuration properties and set the output path to the same directory as the test page, as shown in Figure 4.4 below:

Figure 4.4: Setting the output path

Normally, when you build a custom control you will copy the .DLL file to the \bin directory of the page that will test it. By setting the output to the \bin directory of your test page you will save that step and thus be able to test the control quickly. The Default (Full) Custom Control Visual Studio .NET has provided a custom control named WebCustomControl1, as we saw. This is a full custom control, derived from System.Web.UI.WebControls.WebControl. Even before you fully understand how this code works, you can test it in the test page you created. Open WebForm1.aspx and add a statement to register the new control:
<%@Register TagPrefix="abcd" Namespace="CustomControls" Assembly="CustomControls" %>

This registers the custom control with the web page, similar to how you registered the user control. Once again you use the @Register tag and provide a tag prefix abcd. Rather than providing a Tagname and src, however, you provide a Namespace and Assembly, which uniquely identify the control and the DLL that the page must use.
Sikkim Manipal University Page No. 131

DOT Net Technologies

Unit 4

You now add the control to the page. The two attributes you must set are the Runat attribute, which is needed for all server-side controls, and the Text attribute, which dictates how the control is displayed at runtime. The tag should appear as follows:
<abcd:WebCustomControl1 Runat="Server" Text="Hello World!" Id="WC1" />

When you view this page, the text you passed in is displayed, as shown in Figure 4.5 below:

Figure 4.5: Viewing the default custom control

The example below shows the C# version of the comple custom control provided by Visual Studio .NET Example: VS.NET default custom control (C#)
using System; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel; namespace CustomControls { [DefaultProperty("Text"), ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")] public class WebCustomControl1 : System.Web.UI.WebControls.WebControl { private string text; [Bindable(true), Category("Appearance"), DefaultValue("")] Sikkim Manipal University Page No. 132

DOT Net Technologies set { text = value; } public string Text { get { return text; }

Unit 4

This control contains a single property, Text, backed by a private string variable, text. Note that there are attributes provided both for the property and for the class. These attributes are used by Visual Studio .NET and are not required when creating custom controls. The most common attributes for custom controls are shown in the table 4.1 below:
protected override void Render(HtmlTextWriter output) Table 4.1: Common attributes for custom controls { output.Write(Text); Attribute Description } } Bindable Boolean. true indicates that VS .NET will display this control in the } databindings dialog box. Browsable Category DefaultValue Description Boolean. Is the property displayed in the designer? Determines in which category this control will be displayed when the Properties dialog is sorted by category. The default value. The text you provide is displayed in the description box in the Properties panel.

Objectives This unit introduces the architecture of ASP.NET environment. It talks about the server, user and custom controls found in ASP.NET. It also covers the concept of Master Pages, Themes, and Control Skins. It also covers the
Sikkim Manipal University Page No. 133

DOT Net Technologies

Unit 4

aspect of Forms authentication using ASP.NET. It gives a briefing of Security and encryption in ASP.NET.

4.2 Master Pages


Master Pages The Master Pages feature provides the ability to define common structure and interface elements for your site, such as a page header, footer, or navigation bar, in a common location called a "master page", to be shared by many pages in your site. This improves the maintainability of your site and avoids unnecessary duplication of code for shared site structure or behavior. Just as Themes and Skins allow you to factor out style definitions from your page code and maintain them in a common file, Master Pages do the same for page layout. A Master Page is a page that contains markup and controls that should be shared across multiple pages in your site. For example, if all of your pages should have the same header and footer banners or the same navigation menu, you could define this in a Master Page once, and then all pages associated to this Master Page would inherit those common elements. The advantage of defining the header, footer, and navigation in a Master Page is that these elements need only be defined once, instead of multiple times in duplicate code across the pages in your site. The Master Pages are an easy way to provide a template that can be used by any number of ASP.NET pages in your application. In working with Master Pages, the developer creates a Master File that is the template referenced by a subpage or Content Page. Master Pages use a .master file extension, whereas content pages use the .aspx file extension you are used to; but content pages are declared as such within the files page directive.

Sikkim Manipal University

Page No. 134

DOT Net Technologies

Unit 4

Master and Content Pages Defining a Master Page is just like defining a normal page. Master Pages can contain markup, controls, or code, or any combination of these elements. However, a Master Page can contain a special type of control, called a ContentPlaceHolder control. A ContentPlaceHolder defines a region of the master page rendering that can be substituted with content from a page associated to the master. A ContentPlaceHolder can also contain default content, just in case the derive page does not need to override this content. The syntax of a ContentPlaceHolder control is given below:
<%-- ContentPlaceHolder control --%> <asp:contentplaceholder id="FlowerText" runat="server"/> <%-- ContentPlaceHolder with default content --%> <asp:contentplaceholder id="FlowerText" runat="server"> <h3>Welcome to my florist website!</h3> </asp:contentplaceholder>

To differentiate a Master Page from a normal page, a Master Page is saved under the .master file extension. A page can derive from a Master Page by defining a MasterPageFile attribute on its Page directive, as demonstrated below. A page that is associated to a Master Page is called a Content Page.
<%@ Page MasterPageFile="Site.master" %>

A Content Page can declare Content controls that specifically override content placeholder sections in the Master Page. A Content control is associated to a particular ContentPlaceHolder control through its

ContentPlaceHolderID property. A Content Page may only contain markup and controls inside Content controls; it cannot have any top-level content of its own. It can, however, have directives or server-side code.

Sikkim Manipal University

Page No. 135

DOT Net Technologies

Unit 4

<%@ Page MasterPageFile="Site.master" %> <asp:content id="Content1" contentplaceholderid="FlowerText" runat="server"> With sunshine, water, and careful tending, roses will bloom several times in a season. </asp:content> <asp:content id="Content2" contentplaceholderid="FlowerPicture" runat="server"> <asp:Image id="image1" imageurl="~/images/rose.jpg" runat="server"/> </asp:content>

The following example demonstrates the relationship between Master and Content pages. The Master Page in this case defines two ContentPlaceHolder regions, named FlowerPicture and FlowerText, along with some default content for those regions. Individual content pages in the site inherit the common site layout and look-and-feel from the Master Page, but override the default content for the named ContentPlaceHolder regions with their own content. Note that the Default.aspx page in this site does not define any Content controls, and so it just inherits the default content from the Master Page.

Figure 4.6: A Sample Web Page

The source code for the above web page using C# is given below:
<%@ master language="C#" %> <html> <head> <link rel="stylesheet" href="StyleSheet.css" type="text/css" /> </head> <body> Sikkim Manipal University Page No. 136

DOT Net Technologies <form id="Form1" runat="server"> <div> <table class="main" cellspacing="0" cellpadding="2"> <tr class="header"> <td colspan="2" class="header"/> </tr> <tr valign="top"> <td class="sidebar" rowspan="2"> <a href="daffodil.aspx">Daffodil</a><br/> <a href="rose.aspx">Rose</a><br/> <a href="dahlia.aspx">Dahlia</a><br/> <a href="hydrangea.aspx">Hydrangea</a><br/> <a href="daisy.aspx">Daisy</a><br /> </td> <td class="body"> <asp:contentplaceholder id="FlowerText" runat="server"> <h3>Welcome to my florist website!</h3> We have an enormous selection of quality flowers and seeds, available for shipping to any location worldwide. Let us handle all you gardening needs! </asp:contentplaceholder> <br /><br /> <asp:contentplaceholder id="FlowerPicture" runat="server"> <img alt="water lilies" src="Images/waterlilies.jpg"/> </asp:contentplaceholder> <br /><br /> <asp:adrotator id="MyAdRotator" advertisementfile="Ads.xml" runat="server"/> </td> </tr> <tr> <td class="footer"> <asp:label id="Footer" font-italic="true" text="Copyright Microsoft 2003" runat="server" /> </td> </tr> </table> </div> </form> </body> </html>

Unit 4

Sikkim Manipal University

Page No. 137

DOT Net Technologies

Unit 4

The code for the internal web pages is given below:


Default.aspx <%@ page language="C#" masterpagefile="~/Site.master" %> Rose.aspx <%@ page language="C#" masterpagefile="~/Site.master" %> <asp:content id="Content1" contentplaceholderid="FlowerText" runat="server"> With sunshine, water, and careful tending, roses will bloom several times in a season. </asp:content> <asp:content id="Content2" contentplaceholderid="FlowerPicture" runat="server"> <img alt="rose" src="images/rose.jpg" /> </asp:content>

URL Rebasing in a Master Page One thing to notice about the preceding example is that there are several places in the Master Page that refer to URL resources like images or stylesheet or page references using a relative-path syntax, for example:
<head> <link rel="stylesheet" href="StyleSheet.css" type="text/css" /> </head> ... <a href="daffodil.aspx">Daffodil</a> ... <img alt="water lilies" src="Images/waterlilies.jpg"/>

This works fine when the Master Page and Content Page are in the same directory, but when the Content Page is in a physically separate location, the relative path will not be correct. To solve this problem, you may take one of the following approaches: Use absolute URL paths in the Master Page, for example <img src="/myapplication/images/banner.gif" />

Sikkim Manipal University

Page No. 138

DOT Net Technologies

Unit 4

Use relative or application-relative URLs in server controls instead of static markup, for example <asp:Image ImageUrl="~/images/banner.gif" runat="server" />

The following example demonstrates this technique. The Content Pages have been moved to a subdirectory "Pages" under the directory that contains the Master Page. The Master Page has been updated to use server controls in place of HTML:
<head runat="server"> <link rel="stylesheet" href="StyleSheet.css" type="text/css" /> </head> ... <a id="A1" href="pages/daffodil.aspx" runat="server">Daffodil</a/> ... <asp:Image ID="Image1" AlternateText="Water Lillies" ImageUrl="~/Images/Waterlilies.jpg" runat="server"/>

Accessing a Master Page from Code In addition to overriding content, it is possible for a Content Page to programmatically access its Master Page. A Content Page creates a strongly-typed reference to the Master Page using the <%@ MasterType %> directive, specifying the virtual path to the master page:
<%@ MasterType VirtualPath="Site.master" %>

The Content Page can then reference the Master Page using the Master property of the Page class:
C# Code Master.FooterText = "This is a custom footer"; AdRotator ad = (AdRotator)Master.FindControl("MyAdRotator"); Master.FooterText = "This is a custom footer" Dim ad As AdRotator = Master.FindControl("MyAdRotator");

Sikkim Manipal University

Page No. 139

DOT Net Technologies

Unit 4

In the code example above, FooterText is a public property exposed on the Master Page, while MyAdRotator is a control on the Master Page. Nesting Master Pages Content Pages can also be Master Pages. That is, it is possible to derive a Master page from another Master Page. For example, you might have a toplevel Master Page that represents the overall site header/footer and navigation of your site, and then separate Master Pages that derive from this Master in order to define different looks for the various sub-sections within your site. Content Pages would then derive from the appropriate section master for the section the Content Page belongs to. The following example demonstrates this idea, dividing the Florist example site into two sections, Annuals and Perrennials.

Figure 4.7: Nesting Master Pages

Sikkim Manipal University

Page No. 140

DOT Net Technologies

Unit 4

The following is the code for the Home Page of the Nested Pages:
<%@ page language="C#" MasterPageFile="~/Site4.master" %>

4.3 Themes & Control Skins


Creating Themes Themes and Skins: The Themes and Skins feature of ASP.NET allows you to factor style and layout information into a separate group of files, collectively called a Theme. A Theme can then be applied to any site to affect the look and feel of pages and controls within the site. Style changes to a site can then be easily maintained by making changes to the Theme, without having to edit the individual pages in your site. Themes can also be shared with other developers. When you build a web application, it usually has a similar look-and-feel across all its pages. Not too many applications are designed with each page dramatically different from each other. In general, your applications use similar fonts, colors, and server control styles across all the pages within the application. You can apply these common styles individually to each and every server control or objects on each page, or you can use a capability provided by ASP.NET to centrally specify these styles. All pages or parts of pages in the application can then access them. Themes are the text-based style definitions in ASP.NET. You create .skin files in the Theme folder. A .skin file can contain one or more control skins for one or more control types. You can define skins in a separate file for each control or define all the skins for a theme in a single file.
Sikkim Manipal University Page No. 141

DOT Net Technologies

Unit 4

There are two types of control skins, default skins and named skins: A Default Skin automatically applies to all controls of the same type when a theme is applied to a page. A Control Skin is a default skin if it does not have a SkinID attribute. For example, if you create a default skin for a Calendar control, the control skin applies to all Calendar controls on pages that use the theme. (Default skins are matched exactly by control type, so that a Button control skin applies to all Button controls, but not to LinkButton controls or to controls that derive from the Button object.) A Named Skin is a control skin with a SkinID property set. Named skins do not automatically apply to controls by type. Instead, you explicitly apply a named skin to a control by setting the control's SkinID property. Creating named skins allows you to set different skins for different instances of the same control in an application. Cascading Style Sheets A theme can also include a cascading style sheet (.css file). When you put a .css file in the theme folder, the style sheet is applied automatically as part of the theme. You define a style sheet using the file name extension .css in the theme folder. The following are the uses of ASP.NET Themes: They enable you to define visual styles for your Web Pages They also allow you to apply styles, graphics They allow you to apply the CSS files themselves to the pages of an application They can be applied at the application, page, or server control level.

Sikkim Manipal University

Page No. 142

DOT Net Technologies

Unit 4

Example: This example demonstrates the application of themes to a sample ASP.NET web page:
An ASP Page that does not use themes <% Page Language = VB %> <html xmlns = http://www.w3.org/1999/xhtml> <head runat = server> <title>STLNET</title> </head> <body> <form id = form1 runat = server> <h1> St. Louis .NET User Group</h1><br /> <asp:Textbox ID = Textbox1 runat = server/> <br /> <br /> <asp:Calendar ID = Calendar1 runat = server/> <br /> <asp:Button ID = Button1 runat = server Text = Button /> </form> </body> </html>

This simple page shows some default server controls, but which you can change with one of these new ASP.NET themes. You can instantly change the appearance of this page without changing the style of each server control on the page. From within the Page directive, you simply apply an ASP.NET theme that you have either built or downloaded from the Internet: <%@ Page Language = VB Theme = SmokeAndGlass %> Adding the Them attribute changes the appearance of everything on the page that is defined in an example SmokeAndGlass theme file. If you have multiple pages, you do not have to think about applying styles to everything you do as you build because the styles are already defined centrally for you. Applying a Theme to an Entire Application You can apply a Theme to your entire application using the web.config file.

Sikkim Manipal University

Page No. 143

DOT Net Technologies

Unit 4

Example: Applying a Theme to an Entire Application


<?xml Version = 1.0> <configuration> <system.web> <pages theme = SmokeAndGlass> </ system.web> </configuration>

By specifying the Theme in your web.config file, you need not define the theme again in the Page directive of your ASP.NET pages. This theme is applied automatically to each and every page within your application. In order to apply the theme to only a specific part of an application, make use of the <location/> element to specify the areas of the application for which the theme should be applied. Removing Themes from the Server Controls Some times you want an alternative to the theme that has already been defined. As an example, to change the text box server control that you have been already working with by making its background black and using white text: <asp:Textbox ID = TextBox1 runat = server BackColor = #000000 ForeColor = #ffffff /> To apply a theme to your ASP.NET page but not to the Textbox control, use the EnableTheming property of the Textbox Server Control: <asp:Textbox ID = TextBox1 runat = server BackColor = #000000 ForeColor = #ffffff EnableTheming = false /> To turn off the theming property for multiple controls within a page, consider using the Panel Control (or any Container Control) to encapsulate a collection of controls and then set the EnableTheming attribute of the
Sikkim Manipal University Page No. 144

DOT Net Technologies

Unit 4

Control Panel to false. This disables the theming for each and every control within the panel. Removing Themes from Web pages Suppose that you have set the theme for the entire application using web.config file, and you want to exclude a single ASP.NET page; which could be made possible by removing a theme setting at the page level. The Page directive for every ASP.NET web page includes an

EnableTheming Attribute that can be used to remove theming from your ASP.NET pages. To remove the theme that would be applied by the theme setting in the web.config file, you simply construct your corresponding Page directive as follows: <%@ Page Language =VB EnableTheming = False %> This statement constructs the theme setting to nothing and removes any settings specified in the web.config file for that particular page.
Note: The .skin files are used to define styles for ASP.NET server controls

If the themes are disabled by setting the EnableTheming attribute is set to False at the page level, we can still enable theming for specific controls on that page by setting EnableTheming for those specific controls to true and applying a specific theme at the same time as shown in the example given below:
<asp:Textbox ID = TextBox1 runat = server BackColor = #000000 ForeColor = #ffffff EnableTheming = true SkinID = mySkin/>

Usage of Themes with Master Pages The ASP.NET applications that use Master pages have both the Page and Master page directives that contain an EnableTheming attribute.
Sikkim Manipal University Page No. 145

DOT Net Technologies

Unit 4

If this is the case, what is the behavior of any content pages using the master page? If the content page that is using this master page does not make any specification on theming (it does not use the EnableTheming attribute), what is specified in the master page naturally takes precedence and no theme is utilized as required by the false setting. Even if you have set the EnableTheming attributes value in the content page, any value specified in the master page takes precedence. That is, if the theming is set to false in the master page and set to true in the content page, the page is constructed with the value provided from the master page, which in this case is false. Even if the value is set to false in the master page, you can override this setting at the control level rather than doing it in the Page directive of the content page. Creation of User-Defined Themes Users can define their own themes to the pages they would create within an application. These themes created can be applied at the following levels within an application: Application Level Page Level Server Control Level

Themes are a way of applying a consistent look and feel across entire application. To create your own themes at first, you have to create a proper folder structure in your application. Step1: Right click the project and add a new folder Step 2: Name the folder appropriately (for example: App_Themes)

Sikkim Manipal University

Page No. 146

DOT Net Technologies

Unit 4

Step 3: You can also create this folder by right clicking on your project in Visual Studio and selecting Add ASP.NET Folder Theme. Note: When you execute step3 of above, the theme folder within the App_Themes folder does not have the typical folder icon next to it, instead it has a folder icon that includes a paint brush as shown below: Within the existing (or newly created) themes folder, we can create an additional theme folder for each and every theme that you can use in your application. For Example: If you are going to have four themes Summer, Fall, Winter, and Spring then you create four folders that are named appropriately. Each theme folder must contain the elements of the theme, that can include the following: A single skin file CSS Files Images Adding a CSS to your Themes In addition to the server control definitions that can be created from within a .skin file, we can make further definitions using Cascading Style Sheets (CSS). With a .skin file, we could define only the styles associated with server controls and nothing else. For a theme that goes beyond the server controls, we must further define the theme style so that HTML server controls, HTML, and raw text are all changed in accordance with the theme. This can be done by including a CSS file within your theme folder. It is an easy task to create CSS files for your themes with Visual Studio 2008.

Sikkim Manipal University

Page No. 147

DOT Net Technologies

Unit 4

Example: Right click the Summer theme folder and select Add New Item. In the list of options, select the option Style Sheet and name it Summer.css. The Summer.css file should be sitting right next to your Summer.skin file. This creates an empty .css file for your theme. To create comprehensive theme with this dialog, you define each HTML element that might appear in the ASP.NET page or you make use of class names or element IDs. Example: Creation of a simple CSS file that changes some of the nonserver control items on a ASP.NET page. The sample code for this file creation is shown below:
body { font size: x-small; font family: Verdana; color: #004000; } a: link { color: Blue; text-decoration: none; } a: visited { color: Blue; text-decoration: none; } a: hover { color: Red; text-decoration: underline overline; }

Sikkim Manipal University

Page No. 148

DOT Net Technologies

Unit 4

In this CSS file four things are defined: You define the text that is found within the <body> tag of the page (basically all the text). In general, plenty of text can appear in a typical ASP.NET page that is not placed inside an <asp:Label> or <asp:Literal> tag. Therefore you can define how your text should appear in the CSS file; otherwise your web page may appear quite odd at times. In this case, a definition is in place for the size, the font family, and the color of the text. The next three definitions in the CSS file revolve around the <a> (anchor tag element used for hyperlinks). The A: link definition defines the look of a hyperlink on a web page. The A: visited definition defines the look of the link of a web page already visited by the user previously. The A: hover definition defines the appearance of the hyperlink when the end user hovers on a hyper-link. Skin Creation: A skin is a definition of styles applied to the server controls in your ASP.NET page. Skins can work in conjunction with CSS files or images. To create a theme to use in your ASP.NET application, you use a single skin file in the theme folder. The skin file can have any name, but it must have a .skin file extension. Example: Creation of the Summer theme Right click the Summer folder, select Add New Item, and select Skin. Name the file Summer.skin.

Sikkim Manipal University

Page No. 149

DOT Net Technologies

Unit 4

The listing for the Summer.skin file is shown below:


The Summer.skin file <asp:Label runat = server Forecolor = #004000 Font-Names = Verdana Font-Size = X-Small /> <asp:Textbox runat = server Forecolor = #004000 Font-Names = Verdana Font-Size = X-Small BorderStyle=Solid BorderWidth = 1px BorderColor = #004000 Font-Bold = True /> <asp:Button runat = server Forecolor = #004000 Font-Names = Verdana Font-Size = X-Small BorderStyle=Solid BorderWidth = 1px BorderColor = #004000 Font-Bold = True BackColor = #FFE0C0 />

To use the above listing in a real application, you should actually make a definition for each and every server control option. If you specify the runat = server attribute in the skinned version of the control, you also include it in the server control you put on an .aspx page that uses this theme.
Using the Summer theme in an ASP.NET page

Using C# Language <%@ Page Language = C# Theme = Summer %> <script runat = server> protected void Button1_Click(object sender, System.EventArgs e) { Label1.Text = Hello + TextBox1.Text.ToString(); } </script>

Sikkim Manipal University

Page No. 150

DOT Net Technologies

Unit 4

Figure 4.8: Page with No Theme Applied

Figure 4.9: Page with theme applied:

Sikkim Manipal University

Page No. 151

DOT Net Technologies

Unit 4

The App_Themes Folder Themes reside in the App_Themes folder directly under the application root directory. A Theme consists of a named subdirectory under this folder that contains a collection of one or more Skin files, named with the .skin extension. A Theme can also contain a CSS file and/or subdirectories for static files like images. The figure below shows an App_Themes directory with two Themes defined, named "Default" and "White", each of which has a single skin file and CSS file.

Figure 4.10: App_Themes Folder

Observe in the previous example that the contents of a skin file are simply control definitions as they might appear in a page. A skin file can contain multiple control definitions, for example one definition for each control type. The properties of controls defined in the theme automatically override the local property value for a control of the same type in the target page with the Theme applied. For example, a <asp:Calendar Font-Name="Verdana" runat="server"/> control definition in a skin file will cause all Calendar controls in pages with the Theme applied to use the Verdana font. A local value for this property on the control will be overridden by the Theme. Note that it is an error to specify an ID property value for a control definition in a skin file.

Sikkim Manipal University

Page No. 152

DOT Net Technologies

Unit 4

Global and Application Themes A Theme can reside at the application-level or machine-level (globally available to all applications). Application-level Themes are placed in the App_Themes directory under the application root directory, as described above. Global Themes are placed in a "Themes" directory under an ASP.NETClientFiles folder under the ASP.NET installation directory, for example %WINDIR%\Microsoft.NET\Framework\<version>\ASP.NETClientFiles\The mes. The location of global themes is Inetpub\ wwwroot\aspnet_ client\system_web\<version>\Themes for IIS web sites. Assigning a Theme to a Page An individual page can be assigned a Theme by setting the <%@ Page Theme="..." %> directive to the name of a global or application-level Theme (the name of a folder under the Themes or App_Themes directory). A page can only have one Theme applied, but there may be multiple skin files in the theme that apply style settings to controls in the page.

4.4 Summary
This unit provides the reader with an overview of ASP.NET. It introduces the ASP.NET architecture and various controls of ASP.NET used in the web page application development. It provides the user with the basics of developing Master Pages, Content Pages, and Nested Pages using ASP.NET. It also gives the development of Themes and Control Skins using ASP.NET. Self Assessment Questions 1. The ______ server controls are HTML elements (or elements in other supported markup, such as XHTML) containing attributes that make them programmable in server code.
Sikkim Manipal University Page No. 153

DOT Net Technologies

Unit 4

2. The ______ controls do not necessarily map one-to-one to HTML server controls. Instead, they are defined as abstract controls in which the actual markup rendered by the control can be quite different from the model that you program against. 3. In order to programmatically add a control to a page, there must be a ______ for the new control. 4. Because the Controls property is a collection, you can use the ______ method to place the new control at a specific location. 5. All HTML server controls also support a ______ collection, which gives you direct access to all the control's attributes. 6. The ______________________________ statement creates a text input field in a Web form and assigns it the programmatic ID UserName. 7. The ______ are benign HTML tags that are used to group other HTML elements.

4.5 Terminal Questions


1. With a labeled diagram, explain the ASP.NET Architecture. (Refer to 4.1) 2. Explain the concept of Master Pages with appropriate examples. (Refer to 4.2) 3. Explain the different ways of adding Web Controls to .Net Applications. (Refer to 4.1) 4. With the help of appropriate code examples, explain the family of List Controls. (Refer to 4.1) 5. Describe the process of adding custom controls to a web page. (Refer to 4.1) 6. Describe the usage of themes in Web pages. (Refer to 4.3)

Sikkim Manipal University

Page No. 154

DOT Net Technologies

Unit 4

4.6 Answers to Self Assessment Questions


1. HTML 2. Web server controls 3. container 4. AddAt() 5. Attributes 6. <asp:TextBox ID="UserName" RunAt="server" /> 7. Spans

Sikkim Manipal University

Page No. 155

DOT Net Technologies

Unit 5

Unit 5
Structure: 5.1

ASP.NET Applications

Anatomy of an ASP.NET Application Objectives

5.2 5.3 5.4

The Web.config File The Global.asax Application File Summary Self Assessment Questions

5.5 5.6

Terminal Questions Answers to Self Assessment Questions

5.1 Anatomy of ASP.NET Application


To participate in the Web application world, Microsoft developed Active Server Pages (ASP). ASP was a quick and easy way to develop web pages. ASP Pages consisted of a single page that contained a mix of markup and languages. The power of ASP is that you can include VBScript or Jscript code instruction in the page executed on the Web Server before the page was sent to the end users Web browser. This is an easy way to create dynamic Web pages customized based on instructions dictated by the developer. ASP used scripts between brackets and percentage signs - <% %> - to control server-side behaviors. A developer could then build an ASP page by starting with a set of static HTML. Any dynamic element needed by the page was defined using a scripting language. When a user requested the page from the server by using a browser, the asp.dll (an ISAPI application that provides a bridge between the scripting language and the Web server) would take hold of the page and define all the dynamic aspects of the page on-the-fly based on the programming logic specified in the script. After all the dynamic aspects of the page were
Sikkim Manipal University Page No. 156

DOT Net Technologies

Unit 5

defined, the result was an HTML page output to the browser of the requesting client. Before the introduction of .NET, the model that classic ASP provided and what developed in Visual Basic were so different that few VB developers also developed Web applications and few Web application developers also developed the thick client applications of the VB world. There was a great divide. ASP.NET bridged this gap. ASP.NET brought a Visual Basic style eventing model to Web application development, providing much needed state management techniques over stateless HTTP. Its model is much like the earlier VB model in that a developer can drag and drop a control onto a design surface or form, manipulate the controls properties, and even work with the code behind these controls to act on certain events that occur during their lifecycles. What ASP.NET created is best of both models. Goals of ASP.NET ASP.NET is a major release of the product and builds upon the core .NET framework 2.0 with additional classes and capabilities. This release of the framework was code named Orcas internally at Microsoft. ASP.NET 3.5 continues on a path to make ASP.NET developers the most productive developers in the Web space. Ever since the release of ASP.NET 2.0, the Microsoft team has had the goals focused around developer productivity, administration, and management, as well as performance and scalability. New Developer Infrastructures: An exciting aspect of ASP.NET 3.5 is that there are infrastructures in place for you to use in your applications. The ASP.NET team selected some of the most common programming operations performed with Web applications to be built directly into ASP.NET. This saves you considerable time and coding.

Sikkim Manipal University

Page No. 157

DOT Net Technologies

Unit 5

ASP.NET Compilation System The mechanics of the compilation system actually begin with how a page is structured in ASP.NET 3.5. ASP.NET 3.5 offers a different code behind model than the 1.0 / 1.1 because the .NET Framework 3.5 has the capability to work with partial classes (also called partial types). Upon compilation, the separate files are combined into a single offering. This gives you much cleaner code-behind pages. The code that was part of the Web Form Designer Generated section of your classes is separated from the code-behind classes that you create yourself. ASP.NET 3.5 applications can include a \App_Code directory where you place your classs source. Any class placed here is dynamically compiled and reflected in the application. This is just a save and hit deployment model like the one in classic ASP 3.0. Visual Studio 2008 automatically provides IntelliSense for any objects that are placed in the \App_Code directory, whether you are working with the code behind model or are coding inline. ASP.NET 3.5 also provides you with tools that enable you to precompile your ASP.NET applications both the .aspx pages and code behind so that no page within your application has latency when it is retrieved for the first time. Doing this is also a great way to discover any errors in the pages without invoking every page. As you precompile your entire application, you also receive error notifications if any errors are found anywhere within it. Precompilation also enables you to deliver only the created assembly to the deployment server, thereby protecting your code from snooping, unwanted changes, and tampering after deployment.

Sikkim Manipal University

Page No. 158

DOT Net Technologies

Unit 5

ASP.NET Web Pages You use ASP.NET Web pages as the programmable user interface for your Web application. An ASP.NET Web page presents information to the user in any browser or client device and implements application logic using serverside code. ASP.NET Web pages are: Based on Microsoft ASP.NET technology, in which code that runs on the server dynamically generates Web page output to the browser or client device. Compatible with any browser or mobile device. An ASP.NET Web page automatically renders the correct browser-compliant HTML for features such as styles, layout, and so on. Alternatively, you can design your ASP.NET Web pages to run on a specific browser such as Microsoft Internet Explorer 6 and take advantage of browser-specific features. Compatible with any language supported by the .NET common language runtime, including Microsoft Visual Basic, Microsoft Visual C#, Microsoft J#, and Microsoft JScript .NET. Built on the Microsoft .NET Framework. This provides all the benefits of the framework, including a managed environment, type safety, and inheritance. Flexible because you can add user-created and third party controls to them. Components of ASP.NET Web Pages In ASP.NET Web pages, user interface programming is divided into two pieces: the visual component and the logic. If you have worked with tools like Visual Basic and Visual C++ in the past, you will recognize this division between the visible portion of a page and the code behind the page that interacts with it.

Sikkim Manipal University

Page No. 159

DOT Net Technologies

Unit 5

The visual element consists of a file containing static markup such as HTML or ASP.NET server controls or both. The ASP.NET Web page works as a container for the static text and controls you want to display. The logic for the ASP.NET Web page consists of code that you create to interact with the page. The code can reside either in a script block in the page or in a separate class. If the code is in a separate class file, this file is referred to as the code-behind file. The code in the code-behind file can be written in Visual Basic, Visual C#, Visual J#, or JScript .NET. ASP.NET Web pages are compiled into a dynamic-link library (.dll) file. The first time a user browses to the .aspx page, ASP.NET automatically generates a .NET class file that represents the page and then compiles it. The .dll file runs on the server and dynamically produces the HTML output for your page What ASP.NET Web Pages Help You Accomplish? Web application programming presents challenges that do not typically arise when programming traditional client-based applications. Among the challenges are: Implementing a rich Web user interface: It can be difficult and tedious to design and implement a user interface using basic HTML facilities, especially if the page has a complex layout, a large amount of dynamic content, and full-featured user-interactive objects. Separation of client and server: In a Web application, the client (browser) and server are different programs often running on different computers (and even on different operating systems). Consequently, the two halves of the application share very little information; they can communicate, but typically exchange only small chunks of simple information.

Sikkim Manipal University

Page No. 160

DOT Net Technologies

Unit 5

Stateless execution: When a Web server receives a request for a page, it finds the page, processes it, sends it to the browser, and then discards all page information. If the user requests the same page again, the server repeats the entire sequence, reprocessing the page from scratch. Put another way, a server has no memory of pages that it has processedpage are stateless. Therefore, if an application needs to maintain information about a page, its stateless nature can become a problem.

Unknown client capabilities:

In many cases, Web applications are

accessible to many users using different browsers. Browsers have different capabilities, making it difficult to create an application that will run equally well on all of them. Complications with data access: Reading from and writing to a data source in traditional Web applications can be complicated and resourceintensive. Complications with scalability: In many cases Web applications designed with existing methods fail to meet scalability goals due to the lack of compatibility between the various components of the application. This is often a common failure point for applications under a heavy growth cycle. Meeting these challenges for Web applications can require substantial time and effort. ASP.NET Web pages and the ASP.NET page framework address these challenges in the following ways: Intuitive, consistent object mode: The ASP.NET page framework presents an object model that enables you to think of your forms as a unit, not as separate client and server pieces. In this model, you can program the page in a more intuitive way than in traditional Web applications, including the ability to set properties for page elements and
Sikkim Manipal University Page No. 161

DOT Net Technologies

Unit 5

respond to events. In addition, ASP.NET server controls are an abstraction from the physical contents of an HTML page and from the direct interaction between browser and server. In general, you can use server controls the way you might work with controls in a client application and not have to think about how to create the HTML to present and process the controls and their contents. Event-driven programming model: ASP.NET Web pages bring to Web applications the familiar model of writing event handlers for events that occur on either the client or server. The ASP.NET page framework abstracts this model in such a way that the underlying mechanism of capturing an event on the client, transmitting it to the server, and calling the appropriate method is all automatic and invisible to you. The result is a clear, easily written code structure that supports event-driven development. Intuitive state management: The ASP.NET page framework

automatically handles the task of maintaining the state of your page and its controls, and it provides you with explicit ways to maintain the state of application-specific information. This is accomplished without heavy use of server resources and can be implemented with or without sending cookies to the browser. Browser-independent applications: The ASP.NET page framework enables you to create all application logic on the server, eliminating the need to explicitly code for differences in browsers. However, it still enables you to take advantage of browser-specific features by writing client-side code to provide improved performance and a richer client experience. .NET Framework common language runtime support: The

ASP.NET page framework is built on the .NET Framework, so the entire framework is available to any ASP.NET application. Your applications
Sikkim Manipal University Page No. 162

DOT Net Technologies

Unit 5

can be written in any language that is compatible that is with the runtime. In addition, data access is simplified using the data access infrastructure provided by the .NET Framework, including ADO.NET.

.NET Framework scalable server performance The ASP.NET page framework enables you to scale your Web application from one computer with a single processor to a multi-computer Web farm cleanly and without complicated changes to the application's logic.

Structure of an ASP.NET Application A logical way to begin a chapter on ASP.NET applications is to define the term ASP.NET application. An ASP.NET application consists of all the files in a virtual directory and its subdirectories. If your Web server has a subdirectory named MyApp and MyApp is a virtual directory, all the files in MyApp and any subdirectories that stem from it make up an ASP.NET application. Typically, an application includes one or more of the following file types: ASPX files containing Web forms ASCX files containing user controls Web.config files containing configuration settings A Global.asax file containing global application elements DLLs containing custom types employed by the application

An application can contain an unlimited number of ASPX and ASCX files, each representing a different Web page or portion of a page. Only one Global.asax file is permitted. The number of Web.config files isnt restricted, but each must reside in a different directory. ASP.NET places no limit on the number of DLLs an application uses. DLLs are normally found in the application roots bin directory.

Sikkim Manipal University

Page No. 163

DOT Net Technologies

Unit 5

Figure below shows the physical structure of a very simple ASP.NET application that consists of a single Web form in an ASPX file. The directory containing the ASPX file has been transformed into a virtual directory with the IIS configuration manager and is therefore URL-addressable on the server.

ASPX

Figure 5.1 A Simple ASP.NET application

Figure 5.2: A more complex ASP.NET application

Objectives This unit provides an overview of ASP.Net Applications and their development in Visual Studio environment. At the end of this unit, the student would be able to: Discuss the anatomy of an ASP.NET application

Sikkim Manipal University

Page No. 164

DOT Net Technologies

Unit 5

Discuss the usage of Web.config file in a Web Application Discuss the usage of Global.asax file in a Web Application

5.2 The Web.config File


One of the goals of the Microsoft .NET Framework from the outset was to support XCOPY installsthat is, the ability to install applications by copying them to a directory on your hard disk and uninstall them by deleting files and directories. Having this ability means, among other things, that managed applications dont store configuration settings in the registry as traditional Windows applications do. Instead, they store them in text-based XML files. Web.config is the XML file in which ASP.NET applications store configuration data. Heres the general structure of a typical Web.config file:
<configuration> <appSettings> <!-- appSettings values go here --> </appSettings> <system.web> <!-- ASP.NET configuration settings go here --> </system.web> </configuration>

This file is partitioned into two sections: an appSettings section that holds
application-specific data items such as database connection strings, and a system.web section that holds ASP.NET configuration settings. These sections arent the only ones that can appear in a Web.config file, but they are the most common. Web.configs architecture is extensible, enabling developers to define custom sections when circumstances warrant. <appSettings>

Sikkim Manipal University

Page No. 165

DOT Net Technologies

Unit 5

The appSettings section of Web.config holds application-specific values (strings) that are keyed by other strings. Its purpose is to parameterize an applications behavior, and to allow that behavior to be modified without changing any source code. Suppose you coded the following statements into a Page_Load handler:
SqlDataAdapter adapter = new SqlDataAdapter ("select * from titles where price != 0", "server=hawkeye;database=pubs;uid=sa;pwd="); DataSet ds = new DataSet (); adapter.Fill (ds);

The only problem with this code is that if the database connection string changes if the database moves to another machine, for example, or if the user name or password changes you have to modify the code to update the database connection string. If you work in a big company, code modifications probably trigger a mountain of paperwork and require all or part of the application to be retested and reapproved. A better solution to encoding connection strings and other data thats subject to change over the lifetime of an application is to put it in the appSettings section of Web.config. The following Web.config file declares a connection string and assigns it the name MyConnectionString:
<configuration> <appSettings> <add key="MyConnectionString" value="server=hawkeye;database=pubs;uid=sa;pwd=" /> </appSettings> </configuration>

Sikkim Manipal University

Page No. 166

DOT Net Technologies

Unit 5

Page_Load can be rewritten to extract the connection string from Web.config:


string conn = ConfigurationSettings.AppSettings["MyConnectio nString"]; SqlDataAdapter adapter = new SqlDataAdapter ("select * from titles where price != 0", conn); DataSet ds = new DataSet (); adapter.Fill (ds);

AppSettings is a static method belonging to the ConfigurationSettings class in the FCLs System.Configuration namespace. It retrieves values by name from the appSettings section of Web.config. The benefit to doing it this way? Storing the database connection string in Web.config enables you to change it without touching any actual program code. Its analogous to storing program settings in the registry in a Windows application, and it comes with all the perks but none of the drawbacks. <system.web> The system.web section of Web.config holds configuration settings used by ASP.NET. Its content is categorized by subsections. Although the type and number of subsections that can appear is technically unlimitedas developers are free to define custom subsectionsthe ones listed in the following table are supported by default and can be used without writing custom configuration handlers. <system.web> Subsections

5.3 The Global.asax Application File


Global.asax is a text file that houses application-level event handlers, declarations that pertain to all parts of the application, and other global application elements. ASP.NET applications dont have to include Global.asax files, but most do. An application can have only one Global.asax file. That file must be located in the applications virtual root directory.
Sikkim Manipal University Page No. 167

DOT Net Technologies

Unit 5

Whats inside a Global.asax file? Global.asax supports three element types: Global directives Global event handlers Global object tags

Of the three, the first two are used more often. Global event handlers are particularly important and are the number one reason why developers include Global.asax files in their applications. Well discuss global directives first and global event handlers second. Then, for completeness, well talk about global object tags, too. Global Directives Global directives, also known as application directives, provide applicationwide instructions to the ASP.NET compilation engine. A Global.asax file supports three types of global directives: @ Application directives @ Import directives @ Assembly directives

Global.asax can contain just one @ Application directive, but it places no limit on the number of @ Import and @ Assembly directives. The @ Application Directive @ Application directives serve two purposes: they enable developers to add descriptive text to applications, and they facilitate code-behind programming in Global.asax files. An @ Application directive accompanied by a Description attribute adds descriptive text, as in <%@ Application Description="My First ASP.NET Application" %> ASP.NET ignores Description attributes, so descriptions declared with it are visible only to those persons with access to your Global.asax files. The @ Application directive also supports an Inherits attribute that enables code to be removed from Global.asax and packaged in a separate DLL.

Sikkim Manipal University

Page No. 168

DOT Net Technologies

Unit 5

Suppose, for example, you included the following Global.asax file in an application: <%@ Import Namespace="System.Data" %>
<script language="C#" runat="server"> void Application_Start () { DataSet ds = new DataSet (); ds.ReadXml (Server.MapPath ("GlobalData.xml")); Application["GlobalData"] = ds; } </script>

Coded this way, Application_Start, which is an event handler that fires each time the application starts up, is compiled the first time Global.asax is accessed by ASP.NET. To avoid run-time compilation, you can remove Application_Start from Global.asax and code it into a class that derives from System.Web.HttpApplication:
using System.Web; using System.Data; public class MyApp : HttpApplication { public void Application_Start () { DataSet ds = new DataSet (); ds.ReadXml ("GlobalData.xml"); Application["GlobalData"] = ds; }}

Then you compile the CS file into a DLL, place the DLL in the application roots bin directory, and reduce Global.asax to one simple statement: <%@ Application Inherits="MyApp" %> Code-behind offers the same benefits to Global.asax that it offers to ASPX files: it catches compilation errors before the application is deployed, and it

Sikkim Manipal University

Page No. 169

DOT Net Technologies

Unit 5

enables developers to code handlers in C++ and other languages that ASP.NET doesnt explicitly support. A look behind the scenes reveals why code-behind classes used by Global.asax files derive from HttpApplication. ASP.NET starts an application running when the very first request for that application arrives. Starting an application involves launching a process named Aspnet_wp.exe (commonly referred to as the ASP.NET worker process) if it isnt already running and creating a new application domain in that process to host the application and segregate it from other running ASP.NET applications. In the absence of code-behind, startup also involves parsing Global.asax and placing any content found there into a temporary file containing a class derived from HttpApplication, compiling the temporary file into a DLL, and instantiating the derived class. The resulting HttpApplication object handles the request that prompted the application to start up. As a performance optimization, ASP.NET maintains a pool of such objects and uses them to service incoming requests. One implication of this design is that any code you include in Global.asax executes in the context of an HttpApplication object. That means you can call HttpApplication instance methods and access HttpApplication instance properties from anywhere in Global.asax. It also explains why using codebehind in Global.asax means deriving from System.Web.HttpApplication rather than System.Web.UI.Page. Because the system places Global.asax code in an HttpApplication-derived class, you must do the same if you want to get your code out of Global.asax and into a DLL. The @ Import Directive The @ Import directive serves the same purpose in Global.asax that it serves in ASPX files: it imports namespaces that ASP.NET doesnt import by default. For example, lets say you include the following <script> block in Global.asax:

Sikkim Manipal University

Page No. 170

DOT Net Technologies

Unit 5

<script language="C#" runat="server"> void Application_Start () { DataSet ds = new DataSet (); ds.ReadXml (Server.MapPath ("GlobalData.xml")); Application["GlobalData"] = ds; } </script>

Because DataSet is defined in the System.Data namespace and System.Data isnt imported by default, you must either fully qualify all references to DataSet by including the namespace name or place the following directive at the top of Global.asax: <%@ Import Namespace="System.Data" %> @ Import directives in Global.asax pertain only to code in Global.asax. They do not import namespaces into other of the applications files. The @ Assembly Directive The @ Assembly directive does for Global.asax what @ Assembly does for ASPX files: it identifies assemblies Global.asax uses that ASP.NET doesnt link to by default. (As an example, suppose your Global.asax file uses classes in the System.DirectoryServices namespace. Because that namespace isnt imported by default and because the types that belong to that namespace live in System.DirectoryServices.dll, which ASP.NET doesnt link to by default, you need to include the following statements in Global.asax: <%@ Import Namespace="System.DirectoryServices" %> <%@ Assembly Name="System.DirectoryServices" %> If you dont, ASP.NET will greet you with an error message the moment the application starts up.

Sikkim Manipal University

Page No. 171

DOT Net Technologies

Unit 5

Global Event Handlers The most common reason for including Global.asax files in ASP.NET applications is to handle global events events that arent specific to a particular page but that apply to the application as a whole. Some global events are fired by the HttpApplication instances that process individual requests. Others are fired by HTTP modules plug-in components that provide services such as authentication and output caching to ASP.NET. Some events fire on every request. Others fire at predictable junctures in an applications lifetime, such as when the application starts or stops. Still others fire conditionally for example, when an unhandled exception occurs. Regardless of when a global event fires or who fires it, you can process it by including a handler in Global.asax. Start and End Events ASP.NET fires global events named Start and End when an application starts and stops. To process these events, include handlers named Application_Start and Application_End in Global.asax:
<script language="C#" runat="server"> void Application_Start () { ... } void Application_End () { ... } </script>

Application_Start is called when the application receives its first request. This handler is frequently used to initialize application state or the ASP.NET application cache (both of which are introduced later in this chapter) with
Sikkim Manipal University Page No. 172

DOT Net Technologies

Unit 5

data that is global to the application that is, shared by all of its users. Application_End is called when the application shuts down. Typically, that happens when the application has run for 20 minutes without receiving an HTTP request. Application_End isnt used all that often because ASP.NET applications dont have to clean up after themselves by deleting objects created in Application_Start, but its sometimes used to write data to a persistent storage medium prior to shutdown so that the data can be reloaded the next time the application starts and to dispose of objects that encapsulate unmanaged resources such as database connections. Later in this chapter, youll learn about ASP.NET session state. Session state is a mechanism for storing per-user information (such as shopping carts) in Web applications and preserving it across requests. Session state services are provided by an HTTP module named SessionStateModule, which fires a Start event each time it creates a session and an End event each time a session ends. You can process these events by including handlers named Session_Start and Session_End in Global.asax:
<script language="C#" runat="server"> void Session_Start () { ... } void Session_End () { ... } </script>

Session_Start is called when a user visits your site who hasnt been there recently (usually in the last 20 minutes). Session_End is typically called when a session times out, which by default happens 20 minutes after the
Sikkim Manipal University Page No. 173

DOT Net Technologies

Unit 5

last request is received from the user for whom the session was created. The most common use for Session_Start is to initialize session state with data that is unique to each user. Per-Request Events Global.asax can also include handlers for events fired by HttpApplication instances. If present in Global.asax, the following methods are called in every request in response to HttpApplication events. Theyre listed in the order in which theyre called.
Method Application_Begin Request Application_Authenticate Request Application_AuthorizeRequest Application_ResolveRequest Cache Application_AcquireRequest State Application_PreRequestHandler Execute Application_PostRequestHandler Execute Application_ReleaseRequest State Application_UpdateRequest Cache Application_EndRequest Description Called at the beginning of each request Called to authenticate the caller Called to determine whether the caller is authorized to access the requested resource Called to resolve the current request by providing content from a cache Called to associate the current request with a session and populate session state Called to prepend content to the HTTP response Called to append content to the HTTP response Called to release (store) associated with this session any state

Called to update a cache with content returned in the response Called at the end of each request

These handlers let you customize ASP.NET by plugging into the request processing pipeline. For example, Application_ResolveRequestCache and Application_UpdateRequestCache could be used to implement a custom output cache. Application_AuthenticateRequest and Application_Authorize Request provide hooks for modifying ASP.NETs security apparatus. The
Sikkim Manipal University Page No. 174

DOT Net Technologies

Unit 5

event handlers Application_PreRequestHandler Execute and Application_ PostRequestHandlerExecute enable HTTP responses to be modified before theyre returned to clients. The following Global.asax file uses the latter of these two methods to place a copyright notice at the bottom of each and every page (assuming, of course, that your pages use HTML flow layout rather than absolute positioning): <script language="C#" runat="server">
void Application_PostRequestHandlerExecute (Object sender, EventArgs e) { HttpApplication app = (HttpApplication) sender; app.Context.Response.Write ("<hr><center><i>" + "Copyright 2002 by Me, Myself, and I</i></center>"); } </script>

Outputting a copyright notice this way rather than duplicating it in every ASPX file lets you change it in one place to modify it everywhere it shows up. Error Events The events listed above fire in each and every request. HttpApplication also defines an Error event that fires if ASP.NET throws an unhandled exception. You can process Error events by including an Application_Error handler in Global.asax. Heres a Global.asax file that logs unhandled exceptions in the NT event log. It uses the FCLs System.Diagnostics.EventLog class to write to the event log:

Sikkim Manipal University

Page No. 175

DOT Net Technologies

Unit 5

<%@ Import Namespace="System.Diagnostics" %>


<script language="C#" runat="server"> void Application_Error (Object sender, EventArgs e) { // Formulate a message to write to the event log string msg = "Error accessing " + Request.Path + "\n" + Server.GetLastError ().ToString (); // Write an entry to the event log EventLog log = new EventLog (); log.Source = "My ASP.NET Application"; log.WriteEntry (msg, EventLogEntryType.Error); } </script>

Its not unwise to include a handler like this one in every ASP.NET application so that you can detect unhandled exceptions by periodically checking the NT event log. You could even modify the handler to send an email message to a system administrator to apprise him or her of unhandled exceptions (a sure sign of a sick or buggy application) the moment they occur. Dont be surprised if you encounter a Global.asax file containing an event handler thats not mentioned here. HttpApplication fires a few other events that I havent listed because theyre rarely used or used internally by ASP.NET. Plus, ASP.NET can be extended with HTTP modules that fire global events of their own. HTTP modules can also sink global events, which is precisely how the HTTP modules built into ASP.NET work much of their magic.

Sikkim Manipal University

Page No. 176

DOT Net Technologies

Unit 5

Global Object Tags Global object tags create object instances declaratively. Suppose you want a new instance of ShoppingCart created for each user that visits your site. Rather than do this:
<script> void Session_Start () { Session["MyShoppingCart"] = new ShoppingCart (); } </script>

you can do this: <object id="MyShoppingCart" class="ShoppingCart" scope="session" Runat="server" /> Assuming ShoppingCart has an Add method, a Web form could add an item to a users shopping cart by doing this: MyShoppingCart.Add (...); This code might not make a lot of sense right now, but itll make plenty of sense by the end of the chapter. An <object> tags Scope attribute assigns a scope to the object instances it creates. Scope=Application creates one object instance, which is shared by all users of the application. Scope=Session creates one object instance per session (that is, per user). Scope=Pipeline creates a unique instance of the object for each and every request. ASP.NET doesnt create objects declared with <object> tags unless it has tothat is, until theyre requested for the first time. Lazy instantiation prevents objects from being created unnecessarily if the application doesnt use them.

Sikkim Manipal University

Page No. 177

DOT Net Technologies

Unit 5

5.4 Summary
This unit introduces the reader with Anatomy of ASP.NET applications including the compilation system, web pages, components of web pages and so on. It demonstrates the various applications that can be developed with ASP.NET. It gices the structure of an ASP.NET application. It demonstrates the configuration file usage of web,.config and global.asax application files. Self Assessment Questions 1. ASP uses ____ between brackets and percentage signs - <% %> - to control server-side behaviors. 2. The _______ file is an ISAPI application that provides a bridge between the scripting language and the Web server. 3. ASP.NET 3.5 applications can include a _______ directory where you place your classs source. 4. In ASP.NET Web pages, the ______ programming is divided into two pieces: the visual component and the logic. 5. A ______ file contains global application elements in ASP.NET. 6. The Global.asax file contains an _______ section that holds applicationspecific data items such as database connection strings

5.5 Terminal Questions


1. Discuss the following: ASP.NET Compilation system Components of ASP.NET Web pages (Refer to 5.1)

2. Describe the applications of ASP.NET Web Pages. (Refer to 5.1) 3. Discuss the following: Web.config file (Refer to 5.2) Global.asax Application File (Refer to 5.3)

Sikkim Manipal University

Page No. 178

DOT Net Technologies

Unit 5

5.6 Answers to Self Assessment Questions


1. scripts 2. asp.dll 3. \App_Code 4. user interface 5. Global.asax 6. appSettings

Sikkim Manipal University

Page No. 179

DOT Net Technologies

Unit 6

Unit 6
Structure: 6.1 6.2 6.3 6.4 6.5

State Management using ASP.Net

ASP.NET State Management Cookies in ASP.NET Session State Application State Summary Self Assessment Questions

6.6 6.7

Terminal Questions Answers to Self Assessment Questions

6.1 ASP.NET State Management Overview


The most important aspect of client / server design is that the client is always connected to the server. HTTP is a stateless protocol. For the most part, a connection is built up and torn down each time a call is made to a remote server. HTTP 1.1 includes q keep-alive technique that provides optimizations at the TCP level. Even with this optimization, the server has no way to determine that subsequent connections came from the same client. Although the web has richness of DHTML and Ajax, JavaScript, and HTML 4.0 on the client side, the average high-powered Intel Core Duo with a few gigabytes of RAM is still being used only to render the HTML. Its quite Ironic that such powerful computers on the client side are still so vastly under utilized when it comes to storing state. The ASP.NET concept of a Session that is maintained over the statelessness of HTTP is not a new one, and it existed even before classic ASP. It is a very effective and elegant way to maintain state. The Session

Sikkim Manipal University

Page No. 180

DOT Net Technologies

Unit 6

object remains as before, but the option to plug in your own session state provider is available in ASP.NET 3.5. State management is the process by which you maintain state and page information over multiple requests for the same or different pages. As is true for any HTTP-based technology, Web Forms pages are stateless, which means that they do not automatically indicate whether the requests in a sequence are all from the same client or even whether a single browser instance is still actively viewing a page or site. Furthermore, pages are destroyed and re-created with each round trip to the server; therefore, page information will not exist beyond the life cycle of a single page. For more information about server round trips and the life cycle of Web Forms pages ASP.NET provides multiple ways to maintain state between server round trips. Which of these options you choose depends heavily upon your application, and it should be based on the following criteria: How much information do you need to store? Does the client accept persistent or in-memory cookies? Do you want to store the information on the client or on the server? Is the information sensitive? What performance and bandwidth criteria do you have for your application? What are the capabilities of the browsers and devices that you are targeting? Do you need to store information per user? How long do you need to store the information? Do you have a Web farm (multiple servers), a Web garden (multiple processes on one machine), or a single process that serves the application?

Sikkim Manipal University

Page No. 181

DOT Net Technologies

Unit 6

A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server. To overcome this inherent limitation of traditional Web programming, ASP.NET includes several options that help you preserve data on both a per-page basis and an application-wide basis. These features are as follows: View state Control state Hidden fields Cookies Query strings Application state Session state Profile Properties

View state, control state, hidden fields, cookies, and query strings all involve storing data on the client in various ways. However, application state, session state, and profile properties all store data in memory on the server. Each option has distinct advantages and disadvantages, depending on the scenario. Client - Based State Management Options The following sections describe options for state management that involve storing information either in the page or on the client computer. For these options, no information is maintained on the server between round trips.

Sikkim Manipal University

Page No. 182

DOT Net Technologies

Unit 6

(a) View State The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips. When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page. You can store values in view state as well. (b) Control State Sometimes you need to store control-state data in order for a control to work properly. For example, if you have written a custom control that has different tabs that show different information, in order for that control to work as expected, the control needs to know which tab is selected between round trips. The ViewState property can be used for this purpose, but view state can be turned off at a page level by developers, effectively breaking your control. To solve this, the ASP.NET page framework exposes a feature in ASP.NET called control state. The ControlState property allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property. (c) Hidden Fields ASP.NET allows you to store information in a HiddenField control, which renders as a standard HTML hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a
Sikkim Manipal University Page No. 183

DOT Net Technologies

Unit 6

hidden field is sent in the HTTP form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you want to store directly in the page. Note: It is easy for a malicious user to see and modify the contents of a hidden field. Do not store any information in a hidden field that is sensitive or that your application relies on to work properly. A HiddenField control stores a single variable in its Value property and must be explicitly added to the page. In order for hidden-field values to be available during page processing, you must submit the page using an HTTP POST command. If you use hidden fields and a page is processed in response to a link or an HTTP GET command, the hidden fields will not be available. (d) Cookies A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains sitespecific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent. You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application. Note: The browser can only send the data back to the server that originally created the cookie. However, malicious users have ways to access cookies and read their contents. It is recommended that you do not store sensitive
Sikkim Manipal University Page No. 184

DOT Net Technologies

Unit 6

information, such as a user name or password, in a cookie. Instead, store a token in the cookie that identifies the user, and then use the token to look up the sensitive information on the server. (e) Query Strings A query string is information that is appended to the end of a page URL. A typical query string might look like the following example:
http://www.contoso.com/listwidgets.aspx?category=basic&price=100

In the URL path above, the query string starts with a question mark (?) and includes two attribute/value pairs, one called "category" and the other called "price." Query strings provide a simple but limited way to maintain state information. For example, they are an easy way to pass information from one page to another, such as passing a product number from one page to another page where it will be processed. However, some browsers and client devices impose a 2083-character limit on the length of the URL. Note: Information that is passed in a query string can be tampered with by a malicious user. Do not rely on query strings to convey important or sensitive data. Additionally, a user can bookmark the URL or send the URL to other users, thereby passing that information along with it. In order for query string values to be available during page processing, you must submit the page using an HTTP GET command. That is, you cannot take advantage of a query string if a page is processed in response to an HTTP POST command. Server-Based State Management Options ASP.NET offers you a variety of ways to maintain state information on the server, rather than persisting information on the client. With server-based
Sikkim Manipal University Page No. 185

DOT Net Technologies

Unit 6

state management, you can decrease the amount of information sent to the client in order to preserve state, however it can use costly resources on the server. The following sections describe three server-based state

management features: application state, session state, and profile properties. (f) Application State ASP.NET allows you to save values using application state which is an instance of the HttpApplicationState class for each active Web application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages. Application state is stored in a key/value dictionary that is created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests. Once you add your application-specific information to application state, the server manages it. (g) Session State ASP.NET allows you to save values by using session state which is an instance of the HttpSessionState class for each active Web-application session. Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session will have a different session state. In addition, if a user leaves your application and then returns later, the second user session will have a different session state from the first.

Sikkim Manipal University

Page No. 186

DOT Net Technologies

Unit 6

Session state is structured as a key/value dictionary for storing sessionspecific information that needs to be maintained between server round trips and between requests for pages. You can use session state to accomplish the following tasks: Uniquely identify browser or client-device requests and map them to an individual session instance on the server. Store session-specific data on the server for use across multiple browser or client-device requests within the same session. Raise appropriate session management events. In addition, you can write application code leveraging these events. Once you add your application-specific information to session state, the server manages this object. Depending on which options you specify, session information can be stored in cookies, on an out-of-process server, or on a computer running Microsoft SQL Server. (h) Profile Properties ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. The profileproperties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner.

Sikkim Manipal University

Page No. 187

DOT Net Technologies

Unit 6

To use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a custom format and to a custom storage mechanism such as an XML file, or even to a web service. Because data that is placed in profile properties is not stored in application memory, it is preserved through Internet Information Services (IIS) restarts and worker-process restarts without losing data. Additionally, profile properties can be persisted across multiple processes such as in a Web farm or a Web garden. Objectives: At the end of this unit the reader would be able to: Discuss the importance of ASP.NET state management Usage and applications of Cookies in ASP.NET Describe the Session and Application states in the process of state management

6.2 Cookies in ASP.NET


Introduction: Cookies provide a means in Web applications to store user-specific information. For example, when a user visits your site, you can use cookies to store user preferences or other information. When the user visits your Web site another time, the application can retrieve the information it stored earlier. A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.

Sikkim Manipal University

Page No. 188

DOT Net Technologies

Unit 6

For example, if a user requests a page from your site and your application sends not just a page, but also a cookie containing the date and time, when the user's browser gets the page, the browser also gets the cookie, which it stores in a folder on the user's hard disk. Later, if user requests a page from your site again, when the user enters the URL the browser looks on the local hard disk for a cookie associated with the URL. If the cookie exists, the browser sends the cookie to your site along with the page request. Your application can then determine the date and time that the user last visited the site. You might use the information to display a message to the user or check an expiration date. Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange cookie information no matter what page the user requests from your site. As the user visits different sites, each site might send a cookie to the user's browser as well; the browser stores all the cookies separately. Cookies help Web sites store information about visitors. Generally, cookies are one way of maintaining continuity in a Web applicationthat is, of performing state management. Except for the brief time when they are actually exchanging information, the browser and Web server are disconnected. Each request a user makes to a Web server is treated independently of any other request. Many times, however, it's useful for the Web server to recognize users when they request a page. For example, the Web server on a shopping site keeps track of individual shoppers so the site can manage shopping carts and other user-specific information. A cookie therefore acts as a kind of calling card, presenting pertinent identification that helps an application know how to proceed. Cookies are used for many purposes, all relating to helping the Web site remember users. For example, a site conducting a poll might use a cookie
Sikkim Manipal University Page No. 189

DOT Net Technologies

Unit 6

simply as a Boolean value to indicate whether a user's browser has already participated in voting so that the user cannot vote twice. A site that asks a user to log on might use a cookie to record that the user already logged on so that the user does not have to keep entering credentials. Cookie Limitations Most browsers support cookies of up to 4096 bytes. Because of this small limit, cookies are best used to store small amounts of data, or better yet, an identifier such as a user ID. The user ID can then be used to identify the user and read user information from a database or other data store. (See the section "Cookies and Security" below for information about security implications of storing user information.) Browsers also impose limitations on how many cookies your site can store on the user's computer. Most browsers allow only 20 cookies per site; if you try to store more, the oldest cookies are discarded. Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined. A cookie limitation that you might encounter is that users can set their browser to refuse cookies. If you define a P3P privacy policy and place it in the root of your Web site, more browsers will accept cookies from your site. However, you might have to avoid cookies altogether and use a different mechanism to store user-specific information. A common method for storing user information is session state, but session state depends on cookies, as explained later in the section "Cookies and Session State." Although cookies can be very useful in your application, the application should not depend on being able to store cookies. Do not use cookies to support critical features. If your application must rely on cookies, you can test to see whether the browser will accept cookies.

Sikkim Manipal University

Page No. 190

DOT Net Technologies

Unit 6

Writing Cookies The browser is responsible for managing cookies on a user system. Cookies are sent to the browser via the HttpResponse object that exposes a collection called cookies. You can access the HttpResponse object as the Response property of your Page class. Any cookies that you want to send to the browser must be added to this collection. When creating a cookie, you specify a Name and Value. Each cookie must have a unique name so that it can be identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will cause one to be overwritten. You can also set a cookie's date and time expiration. Expired cookies are deleted by the browser when a user visits the site that has written the cookies. The expiration of a cookie should be set for as long as your application considers the cookie value to be valid. For a cookie to effectively never expire, you can set the expiration date to be 50 years from now. If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded. A non-persistent cookie like this is useful for information that needs to be stored for only a short time or that for security reasons should not be written to disk on the client computer. For example, nonpersistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk.

Sikkim Manipal University

Page No. 191

DOT Net Technologies

Unit 6

You can add cookies to the Cookies collection in a number of ways. The following example shows the method using C# code to write cookies:
Response.Cookies["userName"].Value = "patrick"; Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1); HttpCookie aCookie = new HttpCookie("lastVisit"); aCookie.Value = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(aCookie);

The example adds two cookies to the Cookies collection, one named userName and the other named lastVisit. For the first cookie, the values of the Cookies collection are set directly. You can add values to the collection this way because Cookies derives from a specialized collection of type NameObjectCollectionBase. For the second cookie, the code creates an instance of an object of type HttpCookie, sets its properties, and then adds it to the Cookies collection via the Add method. When you instantiate an HttpCookie object, you must pass the cookie name as part of the constructor. Both examples accomplish the same task, writing a cookie to the browser. In both methods, the expiration value must be of type DateTime. However, the lastVisited value is also a date-time value. Because all cookie values are stored as strings, the date-time value has to be converted to a String. Cookies with More Than One Value You can store one value in a cookie, such as user name and last visit. You can also store multiple name-value pairs in a single cookie. The namevalue pairs are referred to as subkeys. (Subkeys are laid out much like a query string in a URL.) For example, instead of creating two separate cookies named userName and lastVisit, you can create a single cookie named userInfo that has the subkeys userName and lastVisit.

Sikkim Manipal University

Page No. 192

DOT Net Technologies

Unit 6

You might use subkeys for several reasons. First, it is convenient to put related or similar information into a single cookie. In addition, because all the information is in a single cookie, cookie attributes such as expiration apply to all the information. (Conversely, if you want to assign different expiration dates to different types of information, you should store the information in separate cookies.) A cookie with subkeys also helps you limit the size of cookie files. As noted earlier in the "Cookie Limitations" section, cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site. By using a single cookie with subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50 characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the separate cookies and can save around 200 bytes.

6.3 Session State


ASP.NET session state enables you to store and retrieve values for a user as the user navigates the different ASP.NET pages that make up a Web application. HTTP is a stateless protocol, meaning that your Web server treats each HTTP request for a page as an independent request; by default, the server retains no knowledge of variable values used during previous requests. As a result, building Web applications that need to maintain some cross-request state information (applications that implement shopping carts, data scrolling, and so on) can be a challenge. ASP.NET session state identifies requests received from the same browser during a limited period of time as a session, and provides the ability to persist variable values for the duration of that session.

Sikkim Manipal University

Page No. 193

DOT Net Technologies

Unit 6

ASP.NET session state is enabled by default for all ASP.NET applications. ASP.NET session-state variables are easily set and retrieved using the Session property, which stores session variable values as a collection indexed by name. For example, the following code example creates the session variables FirstName and LastName to represent the first name and last name of a user, and sets them to values retrieved from TextBox controls. C# Code Session["FirstName"] = FirstNameTextBox.Text; Session["LastName"] = LastNameTextBox.Text; ASP.NET stores session information in the memory space of the ASP.NET application by default. You can, optionally, store session information using a stand-alone service so that session information is preserved if the ASP.NET application is restarted, in a SQL Server so that session information is available to multiple Web servers in a Web farm (and also persists if the ASP.NET application is restarted), or in a custom data store. ASP.NET also provides several other options for persisting data within an application besides session state. ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.

Sikkim Manipal University

Page No. 194

DOT Net Technologies

Unit 6

Session Variables Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext:Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object. The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection. The following example shows how to create session variables in an ASP.NET page for the first and last name of a user, and set them to values retrieved from TextBox controls. Session variables can be any valid .NET Framework type. C# Code Session["FirstName"] = FirstNameTextBox.Text; Session["LastName"] = LastNameTextBox.Text;

Session Identifiers Sessions are identified by a unique identifier that can be read by using the SessionID property. When session state is enabled for an ASP.NET application, each request for a page in the application is examined for a SessionID value sent from the browser. If no SessionID value is supplied, ASP.NET starts a new session and the SessionID value for that session is sent to the browser with the response. By default, SessionID values are stored in a cookie. However, you can also configure the application to store SessionID values in the URL for a "cookieless" session. A session is considered active as long as requests continue to be made with the same SessionID value. If the time between requests for a particular
Sikkim Manipal University Page No. 195

DOT Net Technologies

Unit 6

session exceeds the specified time-out value in minutes, the session is considered expired. Requests made with an expired SessionID value result in a new session. Cookieless SessionIDs By default, the SessionID value is stored in a non-expiring session cookie in the browser. However, you can specify that session identifiers should not be stored in a cookie by setting the cookieless attribute to true in the sessionState section of the Web.config file. The following example shows a Web.config file that configures an ASP.NET application to use cookieless session identifiers. <configuration> <system.web> <sessionState cookieless="true" regenerateExpiredSessionId="true" /> </system.web> </configuration> ASP.NET maintains cookieless session state by automatically inserting a unique session ID into the page's URL. When ASP.NET sends a page to the browser, it modifies any links in the page that use an application-relative path by embedding a session ID value in the links. (Links with absolute paths are not modified.) Session state is maintained as long as the user clicks links that have been modified in this manner. However, if the client rewrites a URL that is supplied by the application, ASP.NET may not be able to resolve the session ID and associate the request with an existing session. In that case, a new session is started for the request. The session ID is embedded in the URL after the slash that follows the application name and before any remaining file or virtual directory identifier.

Sikkim Manipal University

Page No. 196

DOT Net Technologies

Unit 6

This enables ASP.NET to resolve the application name before involving the SessionStateModule in the request. Note: To improve the security of your application, you should allow users to log out of your application, at which point the application should call the Abandon method. This reduces the potential for a malicious user to get the unique identifier in the URL and use it to retrieve private user data stored in the session. Session Modes ASP.NET session state supports several storage options for session variables. Each option is identified as a session-state Mode type. The default behavior is to store session variables in the memory space of the ASP.NET worker process. However, you can also specify that session state should be stored in a separate process, in a SQL Server database, or in a custom data source. If you do not want session state enabled for your application, you can set the session mode to Off. Session Events ASP.NET provides two events that help you manage user sessions. The Session_OnStart event is raised when a new session starts, and the Session_OnEnd event is raised when a session is abandoned or expires. Session events are specified in the Global.asax file for an ASP.NET application. The Session_OnEnd event is not supported if the session Mode property is set to a value other than InProc, which is the default mode. Note: If the Global.asax file or Web.config file for an ASP.NET application is modified, the application will be restarted and any values stored in application state or session state will be lost. Be aware that some anti-virus software can update the last-modified date and time of the Global.asax or Web.config file for an application.
Sikkim Manipal University Page No. 197

DOT Net Technologies

Unit 6

Configuring Session State Session state is configured by using the sessionState element of the system.web configuration section. You can also configure session state by using the EnableSessionState value in the @ Page directive. The sessionState element enables you to specify the following options: The mode in which the session will store data. The way in which session identifier values are sent between the client and the server. The session Timeout value. Supporting values that are based on the session Mode setting.

The following example shows a sessionState element that configures an application for SQLServer session mode. It sets the Timeout value to 30 minutes, and specifies that session identifiers are stored in the URL.
<sessionState mode="SQLServer" cookieless="true " regenerateExpiredSessionId="true " timeout="30" sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;" stateNetworkTimeout="30"/>

You can disable session state for an application by setting the session-state mode to Off. If you want to disable session state for only a particular page of an application, you can set the EnableSessionState value in the @ Page directive to false. The EnableSessionState value can also be set to ReadOnly to provide read-only access to session variables. Concurrent Requests and Session State Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each
Sikkim Manipal University Page No. 198

DOT Net Technologies

Unit 6

separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear. The following table lists key classes that relate to session state are in the SessionState namespace:
Member SessionIDManager SessionStateItemCollection Description Manages unique identifiers for ASP.NET session state. Used to store session state variables.

6.4 Application State


Application state is a data repository available to all classes in an ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and all sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another. The topics in this section provide information on how application state works and how to use it.

Sikkim Manipal University

Page No. 199

DOT Net Technologies

Unit 6

Using Application State Application state is stored in an instance of the HttpApplicationState class. This class exposes a key-value dictionary of objects. The HttpApplicationState instance is created the first time a user accesses any URL resource in an application. The HttpApplicationState class is most often accessed through the Application property of the HttpContext class. You can use application state in two ways. You can add, access, or remove values from the Contents collection directly through code. The

HttpApplicationState class can be accessed at any time during the life of an application. However, it is often useful to load application state data when the application starts. To do so, you can put code to load application state into the Application_Start method in the Global.asax file. For more information see ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0. Alternatively, you can add objects to the StaticObjects collection via an <object runat="server"> declaration in your Web application's Global.asax file. Application state defined in this way can then be accessed from code anywhere in your application. The following example shows an object declaration for an application state value: <object runat="server" scope="application" ID="MyInfo" PROGID="MSWC.MYINFO"> </object> You can add objects to the StaticObjects collection only in the Global.asax file. The collection throws a NotSupportedException if you attempt to add objects directly through code. You can access members of objects stored in application state without having to reference the Application collection. The following code example

Sikkim Manipal University

Page No. 200

DOT Net Technologies

Unit 6

shows how to reference a member of an object defined in the StaticObjects collection of application state: C# Code protected void Page_Load(Object sender, EventArgs e) Label1.Text = MyInfo.Title; End Sub Application State Considerations When using application state, you must be aware of the following important considerations: 1. Resources: Because it is stored in memory, application state is very fast compared to saving data to disk or a database. However, storing large blocks of data in application state can fill up server memory, causing the server to page memory to disk. As an alternative to using application state, you can use the ASP.NET cache mechanism for storing large amounts of application data. The ASP.NET cache also stores data in memory and is therefore very fast; however, ASP.NET actively manages the cache and will remove items when memory becomes scarce. For more information see ASP.NET Caching Overview. 2. Volatility: As the application state is stored in server memory, it is lost whenever the application is stopped or restarted. For example, if the Web.config file is changed, the application is restarted and all application state is lost unless application state values have been written to a nonvolatile storage medium such as a database. 3. Scalability: Application state is not shared among multiple servers serving the same application, as in a Web farm, or among multiple worker processes serving the same application on the same server, as in a Web garden. Your application therefore cannot rely on application state
Sikkim Manipal University Page No. 201

DOT Net Technologies

Unit 6

containing the same data for application state across different servers or processes. If your application runs in multi-processor or multi-server environments, consider using a more scalable option, such as a database, for data that must preserve fidelity across the application. 4. Concurrency: Application state is free-threaded, which means that application state data can be accessed simultaneously by many threads. Therefore, it is important to ensure that when you update application state data, you do so in a thread-safe manner by including built-in synchronization support. You can use the Lock and UnLock methods to ensure data integrity by locking the data for writing by only one source at a time. You can also reduce the likelihood of concurrency problems by initializing application state values in the Application_Start method in the Global.asax file.

6.5 Summary
This unit highlights the features of state management in ASP.NET. It tells the usage of cookies in ASP.NET. It also highlights the two basic states in which an ASP.NET Session State. Self Assessment Questions 1. ________ is the process by which you maintain state and page information over multiple requests for the same or different pages. 2. Web Forms pages are______, which means that they do not automatically indicate whether the requests in a sequence are all from the same client or even whether a single browser instance is still actively viewing a page or site. 3. The _______ property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.
Sikkim Manipal University Page No. 202

application could be in: The Application State and

DOT Net Technologies

Unit 6

4. A ___________ does not render visibly in the browser, but you can set its properties just as you can with a standard control. 5. The ______ contains site-specific information that the server sends to the client along with page output which can be temporary (with specific expiration times and dates) or persistent. 6. The ______ provide a simple but limited ways to maintain state information. 7. The name-value pairs in a Cookie are referred to as __________.

6.6 Terminal Questions


1. Discuss about State management in ASP.Net (Refer to 6.1) 2. Describe the following states in ASP.NET: Session State (Refer to 6.3) Application State (Refer to 6.4)

6.7 Answers to Self Assessment Questions


1. State management 2. Stateless 3. ViewState 4. Hidden field 5. Cookies 6. Query strings 7. Subkeys

Sikkim Manipal University

Page No. 203

DOT Net Technologies

Unit 7

Unit 7
Structure: 7.1 Introduction Objectives 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 7.10 Connecting to a Data Source using ADO.NET Connection Strings using ADO.NET Connection String Builders (ADO.NET) Building Connection Strings from Configuration Files Basic ADO.NET Features ADO.NET Namespaces and Classes Fetching the data: DataAdapter XML & ADO.NET Summary Self Assessment Questions 7.11 7.12 Terminal Questions Answers to Self Assessment Questions

ADO.NET

7.1 Introduction
What is ADO.NET? The ADO.NET has been developed to enhance the creation of powerful and scalable web applications, by working with data in a disconnected way under the .Net frameworks stateless distributed web model. It has been specifically designed to operate in a 3-tier environment. As the ADO.NET operates in a disconnected way, no longer remaining connected to the data server while performing positional updates, there is a far great scope for data manipulation. ADO.NET was first introduced in version 1.0 of the .NET framework, that provided an extensive array of features to handle live data in a connected
Sikkim Manipal University Page No. 204

DOT Net Technologies

Unit 7

mode or data that is disconnected from its underlying data store. Today with the explosion of the Internet as a means of data communication, a new data technology is required to make data accessible and updateable in a disconnected architecture. Data Access Scenarios: 1. The most popular data access scenario in the Internet is the one in which a user must locate a collection of data and iterate through this data a single time. When a request for data from a Web page that you have created is received, you can simply fill a table with data from a data store. In this case, you go to the data store, grab the data that you want, send the data across the wire, and then populate the table. In this scenario the goal is to get the data as fast as possible. 2. The second way to work with data in a disconnected architecture is to grab a collection of data and use this data separately from the data store itself. This data could be either on the client machine or the server machine. Even though the data is disconnected, you want the ability to keep the data (with all of its tables and relations in place) on the client side. ADO.NET is a reflection of the data store itself, with tables, columns, rows, and relations all in place. When completed working on the client side copy of the data, the changes done to the data could be made persistent back into the data store from where the data was retrieved. The technology that enables the user or the programmer to perform this task is the DataSet. Like their counterparts in the unmanaged world, managed applications can and often do utilize industrial-strength databases such as Microsoft SQL Server and Oracle 8i. Thats why Microsoft created ADO.NET, an elegant, easy-to-use database API for managed applications. ADO.NET is exposed
Sikkim Manipal University Page No. 205

DOT Net Technologies

Unit 7

as a set of classes in the .NET Framework class librarys System.Data namespace and its descendants. Unlike ADO and OLE DB, its immediate predecessors, ADO.NET was designed from the outset to work in the connectionless world of the Web. It also integrates effortlessly with XML, bridging the gap between relational data and XML and simplifying the task of moving back and forth between them. If youre like most developers, you believe that the last thing the world needs is another database access API. Why, when we already have ODBC, DAO, ADO, RDO, OLE DB, and others, do we need yet another API? The short answer is that the world has changed, and none of the existing data access technologies maps very well to a world that revolves around that stateless, text-based protocol called HTTP. In addition, managed applications need an efficient and intuitive way to talk to databases. Thats ADO.NET in a nutshellthe database language spoken by managed applications. ADO.NET is an essential component of the .NET Framework. Lets see how it works. ADO.NET looks very similar to ADO, its predecessor. The key difference is that ADO.NET is a disconnected data architecture. What is Disconnected Architecture? In this architecture, data is retrieved from a database and cached on your local machine. You manipulate the data on your local computer and connect to the database only when you wish to alter records or acquire new data. Advantage of Disconnected Architecture: The biggest advantage with this architecture is that you avoid many of the problems associated with connected data objects that do not scale very well. Database connections are resource-intensive, and it is difficult to have thousands (or hundreds of thousands) of simultaneous continuous connections. A disconnected architecture is resource-frugal.
Sikkim Manipal University Page No. 206

DOT Net Technologies

Unit 7

ADO.NET connects to the database to retrieve data, and connects again to update data when you've made changes. Most applications spend most of their time simply reading through data and displaying it; ADO.NET provides a disconnected subset of the data for your use while reading and displaying. Disconnected data objects work in a mode similar to that of the Web. All web sessions are disconnected, and state is not preserved between web pages. ADO.NET separates data access from data manipulation into discrete components that can be used separately or in tandem. ADO.NET includes .NET Framework data providers for connecting to a database, executing commands, and retrieving results. Those results are either processed directly, placed in an ADO.NET DataSet object in order to be exposed to the user in an ad hoc manner, combined with data from multiple sources, or passed between tiers. The DataSet object can also be used independently of a .NET Framework data provider to manage data local to the application or sourced from XML. The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in System.Xml.dll. .Net Data Providers A .NET Framework data provider is used for connecting to a database, executing commands, and retrieving results. Those results are either processed directly, placed in a DataSet in order to be exposed to the user as needed, combined with data from multiple sources, or remoted between tiers. .NET Framework data providers are lightweight, creating a minimal layer between the data source and code, increasing performance without sacrificing functionality.

Sikkim Manipal University

Page No. 207

DOT Net Technologies

Unit 7

The following table lists the data providers that are included in the .NET Framework.
.NET Framework data provider .NET Framework Data Provider for SQL Server .NET Framework Data Provider for OLE DB .NET Framework Data Provider for ODBC .NET Framework Data Provider for Oracle Description Provides data access for Microsoft SQL Server version 7.0 or later versions. Uses the System.Data.SqlClient namespace. For data sources exposed by using OLE DB. Uses the System.Data.OleDb namespace. For data sources exposed by using ODBC. Uses the System.Data.Odbc namespace. For Oracle data sources. The .NET Framework Data Provider for Oracle supports Oracle client software version 8.1.7 and later, and uses the System.Data.OracleClient namespace.

Core Objects of .NET Framework Data Providers The following table outlines the four core objects that make up a .NET Framework data provider.
Object Connection Command Description Establishes a connection to a specific data source. The base class for all Connection objects is the DbConnection class. Executes a command against a data source. Exposes Parameters and can execute in the scope of a Transaction from a Connection. The base class for all Command objects is the DbCommand class. Reads a forward-only, read-only stream of data from a data source. The base class for all DataReader objects is the DbDataReader class. Populates a DataSet and resolves updates with the data source. The base class for all DataAdapter objects is the DbDataAdapter class.

DataReader

DataAdapter

Sikkim Manipal University

Page No. 208

DOT Net Technologies

Unit 7

In addition to the core classes listed in the table earlier in this document, a .NET Framework data provider also contains the classes listed in the following table.
Object Transaction Description Enlists commands in transactions at the data source. The base class for all Transaction objects is the DbTransaction class. ADO.NET also provides support for transactions using classes in the System.Transactions namespace. A helper object that automatically generates command properties of a DataAdapter or derives parameter information from a stored procedure and populates the Parameters collection of a Command object. The base class for all CommandBuilder objects is the DbCommandBuilder class. A helper object that provides a simple way to create and manage the contents of connection strings used by the Connection objects. The base class for all ConnectionStringBuilder objects is the DbConnectionStringBuilder class. Defines input, output, and return value parameters for commands and stored procedures. The base class for all Parameter objects is the DbParameter class. Returned when an error is encountered at the data source. For an error encountered at the client, .NET Framework data providers throw a .NET Framework exception. The base class for all Exception objects is the DbException class. Exposes the information from a warning or error returned by a data source. Provided for .NET Framework data provider code access security attributes. The base class for all ClientPermission objects is the DBData Permission class.

CommandBuilder

ConnectionStringBuilder

Parameter

Exception

Error ClientPermission

The .NET Framework Data Provider for SQL Server The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. It is lightweight and performs well because it
Sikkim Manipal University Page No. 209

DOT Net Technologies

Unit 7

is optimized to access a SQL Server directly without adding an OLE DB or Open Database Connectivity (ODBC) layer. The following illustration contrasts the .NET Framework Data Provider for SQL Server with the .NET Framework Data Provider for OLE DB. The .NET Framework Data Provider for OLE DB communicates to an OLE DB data source through both the OLE DB Service component, which provides connection pooling and transaction services, and the OLE DB provider for the data source. Note: The .NET Framework Data Provider for ODBC has a similar architecture to the .NET Framework Data Provider for OLE DB; for example, it calls into an ODBC Service Component. The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. It is lightweight and performs well because it is optimized to access a SQL Server directly without adding an OLE DB or Open Database Connectivity (ODBC) layer. The following illustration contrasts the .NET Framework Data Provider for SQL Server with the .NET Framework Data Provider for OLE DB. The .NET Framework Data Provider for OLE DB communicates to an OLE DB Data source through both the OLE DB Service component, which provides connection pooling and transaction services, and the OLE DB provider for the data source. Note: The .NET Framework Data Provider for ODBC has a similar architecture to the .NET Framework Data Provider for OLE DB; for example, it calls into an ODBC Service Component. To use the .NET Framework Data Provider for SQL Server, you must have access to SQL Server 7.0 or later versions. The.NET Framework Data Provider for SQL Server classes are located in the System. Data.SqlClient namespace. For earlier versions of SQL Server, use the .NET Framework Data Provider for OLE DB with the SQL Server OLE DB provider System. Data.OleDb.
Sikkim Manipal University Page No. 210

DOT Net Technologies

Unit 7

The .NET Framework Data Provider for SQL Server supports both local and distributed transactions. For distributed transactions, the .NET Framework Data Provider for SQL Server, by default, automatically enlists in a transaction and obtains transaction details from Windows Component Services or System.Transactions. The following code example shows how to include the

System.Data.SqlClient namespace in your applications. using System.Data.SqlClient; The .NET Framework Data Provider for OLE DB The .NET Framework Data Provider for OLE DB uses native OLE DB through COM interoperability to enable Data access. The .NET Framework Data Provider for OLE DB supports both local and distributed transactions. For distributed transactions, the .NET Framework Data Provider for OLE DB, by default, automatically enlists in a transaction and obtains transaction details from Windows 2000 Component Services. The following table shows the providers that have been tested with ADO.NET.
Driver SQLOLEDB MSDAORA Microsoft.Jet.OLEDB.4.0 Provider Microsoft OLE DB provider for SQL Server Microsoft OLE DB provider for Oracle OLE DB provider for Microsoft Jet

The.NET Framework Data Provider for OLE DB does not support OLE DB version 2.5 interfaces. OLE DB Providers that require support for OLE DB 2.5 interfaces will not function correctly with the .NET Framework Data Provider for OLE DB. This includes the Microsoft OLE DB provider for Exchange and the Microsoft OLE DB provider for Internet Publishing.

Sikkim Manipal University

Page No. 211

DOT Net Technologies

Unit 7

The .NET Framework Data Provider for OLE DB does not work with the OLE DB provider for ODBC (MSDASQL). To access an ODBC data source using ADO.NET, use the .NET Framework Data Provider for ODBC. .NET Framework Data Provider for OLE DB classes are located in the System. Data.OleDb namespace. The following code example shows how to include the System.Data.OleDb namespace in your applications. C# Code using System.Data.OleDb;

The .NET Framework Data Provider for ODBC The .NET Framework Data Provider for ODBC uses the native ODBC Driver Manager (DM) to enable data access. The ODBC data provider supports both local and distributed transactions. For distributed transactions, the ODBC data provider, by default, automatically enlists in a transaction and obtains transaction details from Windows 2000 Component Services. The following table shows the ODBC drivers tested with ADO.NET.
Driver SQL Server Microsoft ODBC for Oracle Microsoft Access Driver (*.mdb)

.NET Framework Data Provider for ODBC classes are located in the System.Data.Odbc namespace. The following code example shows how to include the System.Data.Odbc namespace in your applications. C# Code using System.Data.Odbc;

Sikkim Manipal University

Page No. 212

DOT Net Technologies

Unit 7

The .NET Framework Data Provider for Oracle The .NET Framework Data Provider for Oracle enables data access to Oracle data sources through Oracle client connectivity software. The data provider supports Oracle client software version 8.1.7 or a later version. The data provider supports both local and distributed transactions. The .NET Framework Data Provider for Oracle requires Oracle client software (version 8.1.7 or a later version) on the system before you can connect to an Oracle data source. .NET Framework Data Provider for Oracle classes are located in the System.Data.OracleClient namespace and are contained in the System.Data.OracleClient.dll assembly. You must reference both the System.Data.dll and the System.Data.OracleClient.dll when you compile an application that uses the data provider. The following code example shows how to include the

System.Data.OracleClient namespace in your applications. C# Code using System.Data; using System.Data.OracleClient;

Choosing a .NET Framework Data Provider Depending on the design and data source for your application, your choice of .NET Framework data provider can improve the performance, capability, and integrity of your application. The following table discusses the advantages and limitations of each .NET Framework data provider.

Sikkim Manipal University

Page No. 213

DOT Net Technologies

Unit 7

Provider .NET Framework Data Provider for SQL Server

Notes Recommended for middle-tier applications that use Microsoft SQL Server 7.0 or a later version. Recommended for single-tier applications that use Microsoft Database Engine (MSDE) or SQL Server 7.0 or a later version. Recommended over use of the OLE DB provider for SQL Server (SQLOLEDB) with the .NET Framework Data Provider for OLE DB. For SQL Server 6.5 and earlier, you must use the OLE DB provider for SQL Server with the .NET Framework Data Provider for OLE DB. Recommended for middle-tier applications that use SQL Server 6.5 or earlier. For SQL Server 7.0 or a later version, the .NET Framework Data Provider for SQL Server is recommended. Also recommended for single-tier applications that use Microsoft Access databases. Use of an Access database for a middle-tier application is not recommended. Recommended for middle and single-tier applications that use ODBC data sources. Recommended for middle and single-tier applications that use Oracle data sources.

.NET Framework Data Provider for OLE DB

.NET Framework Data Provider for ODBC .NET Framework Data Provider for Oracle

Objectives This unit provides with an overview of the features of ADO.NET. At the end of this unit the reader would be able to: Understand the concepts of database development using ADO.NET Describe various ways to connect to different data sources using built in features of ADO.NET Understand the usage of strings and stringbuilders in ADO.NET Describe the concepts of namespaces and classes The Usage of DataAdapters in fetching the data from a source Describe the usage of XML data in ADO.NET
Page No. 214

Sikkim Manipal University

DOT Net Technologies

Unit 7

7.2 Connecting to a Data Source using ADO.NET


In ADO.NET you use a Connection object to connect to a specific data source by supplying necessary authentication information in a connection string. The Connection object you use depends on the type of data source. Each .NET Framework data provider included with the .NET Framework has a Connection object: the .NET Framework Data Provider for OLE DB includes an OleDbConnection object, the .NET Framework Data Provider for SQL Server includes a SqlConnection object, the .NET Framework Data Provider for ODBC includes an OdbcConnection object, and the .NET Framework Data Provider for Oracle includes an OracleConnection object. To connect to Microsoft SQL Server 7.0 or later, use the SqlConnection object of the .NET Framework Data Provider for SQL Server. To connect to an OLE DB data source, or to Microsoft SQL Server 6.x or earlier, use the OleDbConnection object of the .NET Framework Data Provider for OLE DB. To connect to an ODBC data source, use the OdbcConnection object of the .NET Framework Data Provider for ODBC. To connect to an Oracle data source, use the OracleConnection object of the .NET Framework Data Provider for Oracle. Closing Connections We recommend that you always close the connection when you are finished using it, so that the connection can be returned to the pool. The Using block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception. You can also use the Close or Dispose methods of the connection object for the provider that you are using. Connections that are not explicitly closed might not be added or returned to the pool. For example, a connection that has gone out of scope but that has not been explicitly closed will only be

Sikkim Manipal University

Page No. 215

DOT Net Technologies

Unit 7

returned to the connection pool if the maximum pool size has been reached and the connection is still valid. Note: Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the Finalize method of your class. In a finalizer, only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a Finalize method in your class definition. Connecting to SQL Server The .NET Framework Data Provider for SQL Server supports a connection string format that is similar to the OLE DB (ADO) connection string format. For valid string format names and values, see the ConnectionString property of the SqlConnection object. You can also use the

SqlConnectionStringBuilder class to create syntactically valid connection strings at run time. The following code example demonstrates how to create and open a connection to a SQL Server 7.0 or later database.
C# Code // Assumes connectionString is a valid connection string. using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // Do work here. }

Connecting to an OLE DB Data Source The .NET Framework Data Provider for OLE DB provides connectivity to data sources exposed using OLE DB and to Microsoft SQL Server 6.x or
Sikkim Manipal University Page No. 216

DOT Net Technologies

Unit 7

earlier (through SQLOLEDB, the OLE DB Provider for SQL Server), using the OleDbConnection object. For the .NET Framework Data Provider for OLE DB, the connection string format is identical to the connection string format used in ADO, with the following exceptions: The Provider keyword is required. The URL, Remote Provider, and Remote Server keywords are not supported. The following code example demonstrates how to create and open a connection to an OLE DB data source. C# Code // Assumes connectionString is a valid connection string. using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); // Do work here. }

Connecting to an ODBC Data Source The .NET Framework Data Provider for ODBC provides connectivity to data sources exposed using ODBC using the OdbcConnection object. For the .NET Framework Data Provider for ODBC, the connection string format is designed to match the ODBC connection string format as closely as possible. You may also supply an ODBC data source name (DSN). The following code example demonstrates how to create and open a connection to an ODBC data source.

Sikkim Manipal University

Page No. 217

DOT Net Technologies

Unit 7

C# Code // Assumes connectionString is a valid connection string. using (OdbcConnection connection = new OdbcConnection(connectionString)) { connection.Open(); // Do work here. }

Connecting to an Oracle Data Source The .NET Framework Data Provider for Oracle provides connectivity to Oracle data sources using the OracleConnection object. For the .NET Framework Data Provider for Oracle, the connection string format is designed to match the OLE DB Provider for Oracle (MSDAORA) connection string format as closely as possible. The following code example demonstrates how to create and open a connection to an Oracle data source. C# Code // Assumes connectionString is a valid connection string. using (OracleConnection connection = new OracleConnection(connectionString)) { connection.Open(); // Do work here. } OracleConnection nwindConn = new OracleConnection("Data

Source=MyOracleServer;Integrated Security=yes;"); nwindConn.Open();

Sikkim Manipal University

Page No. 218

DOT Net Technologies

Unit 7

7.3 Connection Strings using ADO.NET


The .NET Framework 2.0 provides new capabilities for working with connection strings, including the introduction of new keywords to the connection string builder classes, which facilitate creating valid connection strings at run time. A connection string contains initialization information that is passed as a parameter from a data provider to a data source. The syntax depends on the data provider, and the connection string is parsed during the attempt to open a connection. Syntax errors generate a run-time exception, but other errors occur only after the data source receives connection information. Once validated, the data source applies the options specified in the connection string and opens the connection. The format of a connection string is a semicolon-delimited list of key/value parameter pairs: keyword1=value; keyword2=value; Keywords are not case sensitive, and spaces between key/value pairs are ignored. However, values may be case sensitive, depending on the data source. Any values containing a semicolon, single quotation marks, or double quotation marks must be enclosed in double quotation marks. Valid connection string syntax depends on the provider, and has evolved over the years from earlier APIs like ODBC. The .NET Framework Data Provider for SQL Server incorporates many elements from older syntax and is generally more flexible with common connection string syntax. There are frequently equally valid synonyms for connection string syntax elements, but some syntax and spelling errors can cause problems. For example, "Integrated Security=true" is valid, whereas "IntegratedSecurity=true" causes an error. In addition, connection strings constructed at run time from

Sikkim Manipal University

Page No. 219

DOT Net Technologies

Unit 7

unvalidated user input can lead to string injection attacks, jeopardizing security at the data source. To address these problems, ADO.NET 2.0 introduces new connection string builders for each .NET Framework data provider. Keywords are exposed as properties, enabling connection string syntax to be validated before submission to the data source. There are also new classes that simplify storing and retrieving connection strings in configuration files and encrypting them using protected configuration.

7.4 Connection String Builders (ADO.NET)


In previous versions of ADO.NET, compile-time checking of connection strings with concatenated string values did not occur, so at run time, an incorrect keyword would generate an ArgumentException. Each of the .NET Framework data providers supports different syntax for connection string keywords, making constructing valid connection strings difficult if done manually. To address this problem, ADO.NET 2.0 introduces new connection string builders for each .NET Framework data provider. Each data provider provides a strongly typed connection string builder class that inherits from DbConnectionStringBuilder. The following table lists the .NET Framework data providers and their associated connection string builder classes.
Provider System.Data.SqlClient System.Data.OleDb System.Data.Odbc System.Data.OracleClient ConnectionStringBuilder class SqlConnectionStringBuilder OleDbConnectionStringBuilder OdbcConnectionStringBuilder OracleConnectionStringBuilder

Sikkim Manipal University

Page No. 220

DOT Net Technologies

Unit 7

7.5 Building Connection Strings from Configuration Files


If certain elements of a connection string are known ahead of time, they can be stored in a configuration file and retrieved at run time to construct a complete connection string. For example, the name of the database might be known in advance, but not the name of the server. Or you might want a user to supply a name and password at run time without being able to inject other values into the connection string. One of the overloaded constructors for a connection string builder takes a String as an argument, which allows you to supply a partial connection string which can then be completed from user input. The partial connection string can be stored in a configuration file and retrieved at run time. Example This example demonstrates retrieving a partial connection string from a configuration file and completing it by setting the DataSource, UserID, and Password properties of the SqlConnectionStringBuilder. The configuration file is defined as follows. <connectionStrings> <clear/> <add name="partialConnectString" connectionString="Initial Catalog=Northwind;" providerName="System.Data.SqlClient" /> </connectionStrings>

Note: You must set a reference to the System.Configuration.dll in your project in order for the code to run.

Sikkim Manipal University

Page No. 221

DOT Net Technologies

Unit 7

private static void BuildConnectionString(string dataSource, string userName, string userPassword) { // Retrieve the partial connection string named databaseConnection // from the application's app.config or web.config file. ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["partialConnectString"]; if (null != settings) { // Retrieve the partial connection string. string connectString = settings.ConnectionString; Console.WriteLine("Original: {0}", connectString); // Create a new SqlConnectionStringBuilder based on the // partial connection string retrieved from the config file. SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);

// Supply the additional values. builder.DataSource = dataSource; builder.UserID = userName; builder.Password = userPassword; Console.WriteLine("Modified: {0}"builder.ConnectionString); } }

7.6 Basic ADO.NET Features


The following examples make use of Northwind.mdf SQL Server Express Database File. To get this database, search for Northwind and pubs sample databases for SQL Server 2000. Selecting Data After the connection to the data source is open and ready to use, u probably want to read the data from the data source. If you do not want to manipulate the data, but simply to read it or transfer it from one spot to another, you use the DataReader class.
Sikkim Manipal University Page No. 222

DOT Net Technologies

Unit 7

In the following example, you use the GetCompanyData() function to provide a list of company names from the SQL Northwind database.

List<string> returnData = new List<string>(); myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); while(myReader.Read()) { returnData.Add(myReader[CompanyName].ToString()); } return returnData; } }

In this example, you create an instance of both the SqlConnection and the SqlCommand classes. Then, before you open the connection, you simply pass the SqlCommand class a SQL command selecting specific data from the Northwind Database. After your connection is opened you create a DataReader. To read the data from the database, you iterate through the data with the DataReader by using the myReader.Read() method. After the List object is built, the connection is closed, and the object is returned from the function.
Sikkim Manipal University Page No. 223

DOT Net Technologies

Unit 7

Data Insertion This data may have been passed to you by the end user through the XML Web Service, or it may be data that you generated within the logic of your class.

Insertion of specific values into specific columns is done using the SQL command string. The actual insertion is initiated using the

cmd.ExecuteNonQuery() command. This executes a command on the data when you do not want anything in return. Data Updation Updation is the process of performing operations on existing rows of data in a table. In the following example, we update an employee by putting a value in the emp_bonus column if the employee has been at the company for a time period of minimum 5 years or more.

Sikkim Manipal University

Page No. 224

DOT Net Technologies

Unit 7

The update function iterates through all the employees in the table and changes the value of the emp_bonus field to 1000 if an employee has been within the company for more than five years. Deletion of Data This operation deletes the data from the data source specified. This operation is done using the SQL command string and the method ExecuteNonQuery(). An example code for performing this operation is shown below:

Sikkim Manipal University

Page No. 225

DOT Net Technologies

Unit 7

We assign the ExecuteNonQuery() command to an integer variable to return the number of records deleted after execution.

7.7 ADO.NET Namespaces and Classes


There are six core ADO.NET namespaces. In addition to these namespaces, each new data provider can have its own namespace. For example, the Oracle.NET data provider adds a namespace of System.Data.OracleClient (A Microsoft built Oracle Data Provider).
Namespace System.Data Description This is the core namespace of ADO.NET. It contains classes used by all data providers. It contains classes to represent tables, columns, rows, and the DataSet class. It also contains some useful interfaces such as IDbCommand, IDbConnection, and IDbDataAdapter. These interfaces are used by all managed providers, enabling them to plug into the core of ADO.NET. It defines the common classes used as base classes for data providers. All data providers share theses classes. Example: DbConnection and DbDataAdapter. It defines classes that work with OLE-DB data sources using the .NET OleDb data provider. It contains classes such as OleDbConnection and OleDbCommand. It define classes that work with ODBC data sources using the .NET ODBC data provider. It contains classes such as OdbcConnection and OdbcCommand It defines a data provider for SQL server 7.0 or higher databases. It contains classes such as SqlConnection and SqlCommand. It defines a few classes that represent specific data types for the SQL Server database.

System.Data.Common

System.Data.OleDb

System.Data.Odbc

System.Data.SqlClient

System.Data.SqlTypes

Sikkim Manipal University

Page No. 226

DOT Net Technologies

Unit 7

ADO.NET has the following three distinct types of classes: 1. Disconnected Classes: These classes provide the basic structure for ADO.NET framework. Example: DataTable class. The objects of this class are capable of storing data without any dependency on a specific data provider. 2. Shared Classes: They form the base classes for data providers and are shared commonly among all the data providers. 3. Data Provider Classes: They are meant to work with different kinds of data sources. They are used to perform all data-management operations on specific databases. For example, the SqlClient data provider works only with SQL server database. A Data Provider contains the following objects: 1. Connection 2. Command 3. DataReader The following are the basic steps in creation and execution of database query operations in ADO.NET: Step-1: First create the Connection object and provide it with necessary information such as the connection string. Step-2: Create a command object and provide it with the details of the SQL command that is to be executed. Step-3: Decide whether the command returns a result set. If the command does not return a result set, you can simply execute the command by calling one of its several Execute methods. If the command returns a result set, you must make a decision about whether you want to retain the result set for future use without maintaining the connection to the database. If you want to retain the result set, you must
Sikkim Manipal University Page No. 227

DOT Net Technologies

Unit 7

create a DataAdapter and use it to fill a Database object and use it to fill a DataSet or a DataTable object. These objects are capable of maintaining their information in a disconnected mode. If you do not want to retain the result set, but rather simply process the command, you can use the Command object to create a DataReader object. The DataReader object needs a live connection to the database, and it works as a forward-only, read-only cursor. Connection Object It creates a link (or connection) to a specified data source. This object must contain the necessary information to discover the specified data source and to log in to it properly using a defined user name and password combination. This information is provided via a single string called Connection String. The data provider for working with a SQL data store includes a SqlConnection class that performs the connection operation. The

SqlConnection object is a class that is specific to the SqlClient provider. The properties for the SqlConnection class are shown in the following table:
Property ConnectionString Database DataSource Description This property allows you to read or provide the connection string that should be used by the SqlConnection Object A read-only property that returns the name of the database to use after the connection is opened A read-only property that returns the name of the instance of the SQL Server database used by the SqlConnection object A read-only property that returns the current state of the connection. The possible values are Broken, Closed, Connecting, Executing, Fetching, and Open.

State

Sikkim Manipal University

Page No. 228

DOT Net Technologies

Unit 7

Figure: Connection to a SQL Database

To make this connection work, make sure that proper namespaces are imported before you start using any of the classes that work with SQL. The first step in making a connection is to create an instance of the SqlConnection class and assign it to the con instance. The SqlConnection class is initialized after you pass in the connection string as a parameter to the class. The second way of making a connection is to put the connection string within the applications web.config file and then to make a reference to the web.config file. To define the connection string within the web.config file, you are going to make use of the <connectionString> section. From this section, you can place an <add> element within it to define your connection. Figure: Coding the Connection String within the web.config file

Sikkim Manipal University

Page No. 229

DOT Net Technologies

Unit 7

Now that you have a connection string within the web.config file, you can then make use of that connection string directly in your code by using the ConnectionManager object as shown in the listing below:

For this line of code to work, we have to make a reference to the System.Configuration namespace. When you complete your connection to the data source, be sure that you explicitly close the connection by using con.close(). The .NET framework does not implicitly release the connections when they fall out of scope.

7.8 Fetching the data: DataAdapter


A DataAdapter is used to retrieve data from a data source and populate tables within a DataSet. The DataAdapter also resolves changes made to the DataSet back to the data source. The DataAdapter uses the Connection object of the .NET Framework data provider to connect to a data source, and it uses Command objects to retrieve data from and resolve changes to the data source. Each .NET Framework data provider included with the .NET Framework has a DataAdapter object: the .NET Framework Data Provider for OLE DB includes an OleDbDataAdapter object, the .NET Framework Data Provider for SQL Server includes a SqlDataAdapter object, the .NET Framework Data Provider for ODBC includes an OdbcDataAdapter object, and the .NET Framework Data Provider for Oracle includes an OracleDataAdapter object. DataAdapter Members Represents a set of SQL commands and a database connection that are used to fill the DataSet and update the data source.
Sikkim Manipal University Page No. 230

DOT Net Technologies

Unit 7

The DataAdapter type exposes the following members. Constructors


Name DataAdapter Description Overloaded. Initializes a new instance of a DataAdapter class

Methods
Name CloneInternals CreateObjRef Description Obsolete. Creates a copy of this instance of DataAdapter. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) Creates a new DataTableMappingCollection. Overloaded. Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Overloaded. Adds or refreshes rows in the DataSet to match those in the data source. Overloaded. Adds a DataTable to the specified DataSet. Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.) Gets the parameters set by the user when executing an SQL SELECT statement. Serves as a hash function for a particular type. (Inherited from Object.) Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.) Gets the Type of the current instance. (Inherited from Object.) Indicates whether a DataTableMappingCollection has been created.

CreateTableMappings Dispose Equals Fill FillSchema Finalize

GetFillParameters GetHashCode GetLifetimeService

GetService

GetType HasTableMappings

Sikkim Manipal University

Page No. 231

DOT Net Technologies

Unit 7

InitializeLifetimeService

Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Overloaded. Invoked when an error occurs during a Fill. Resets FillLoadOption to its default state and causes DataAdapter.Fill to honor AcceptChangesDuringFill. Determines whether the AcceptChanges DuringFill property should be persisted. Determines whether the property should be persisted. FillLoadOption

MemberwiseClone OnFillError ResetFillLoadOption

ShouldSerializeAcceptChangesDuringFill ShouldSerializeFillLoadOption ShouldSerializeTableMappings

Determines whether one or more Data TableMapping objects exist and they should be persisted. Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.) In .NET Compact Framework 3.5, this member is inherited from Object.ToString(). In XNA Framework 1.0, this member is inherited from Object.ToString(). Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified DataSet from a DataTable named "Table."

ToString

Update

Properties
Name AcceptChangesDuringFill Description Gets or sets a value indicating whether AcceptChanges is called on a DataRow after it is added to the DataTable during any of the Fill operations. Gets or sets whether AcceptChanges is called during a Update. Gets a value indicating whether the component can raise an event. (Inherited from Component.) Gets the IContainer that contains the Component. (Inherited from Component.) Gets or sets a value that specifies whether to generate an exception when an error is encountered during a row update.

AcceptChangesDuringUpdate CanRaiseEvents

Container ContinueUpdateOnError

Sikkim Manipal University

Page No. 232

DOT Net Technologies

Unit 7

DesignMode

Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.) Gets the list of event handlers that are attached to this Component. (Inherited from Component.) Gets or sets the LoadOption that determines how the adapter fills the DataTable from the DbDataReader. Determines the action to take when incoming data does not have a matching table or column. Determines the action to take when existing DataSet schema does not match incoming data. Gets or sets whether the Fill method should return provider-specific values or common CLS-compliant values. Gets or sets the ISite of the Component. (Inherited from Component.) Gets a collection that provides the master mapping between a source table and a DataTable.

Events

FillLoadOption

MissingMappingAction

MissingSchemaAction

ReturnProviderSpecificTypes

Site TableMappings

Events
Name Disposed FillError Description Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.) Returned when an error occurs during a fill operation.

The Common Behavior: IDbConnection Represents an open connection to a data source, and is implemented by .NET Framework data providers that access relational databases. Namespace: System.Data Assembly: System.Data (in System.Data.dll) Syntax: In C# public interface IDbConnection: IDisposable
Sikkim Manipal University Page No. 233

DOT Net Technologies

Unit 7

The IDbConnection interface enables an inheriting class to implement a Connection class, which represents a unique session with a data source (for example, a network connection to a server). For more information about Connection classes, see Connecting to a Data Source (ADO.NET). An application does not create an instance of the IDbConnection interface directly, but creates an instance of a class that inherits IDbConnection. Classes that inherit IDbConnection must implement all inherited members, and typically define additional members to add provider-specific

functionality. For example, the IDbConnection interface defines the ConnectionTimeout property. In turn, the SqlConnection class inherits this property, and also defines the PacketSize property. Notes to Implementers: To promote consistency among .NET Framework data providers, name the inheriting class in the form PrvClassname where Prv is the uniform prefix given to all classes in a specific .NET Framework data provider namespace. For example, Sql is the prefix of the SqlConnection class in the System.Data.SqlClient namespace. When you inherit from the IDbConnection interface, you should implement the following constructors:
Item PrvConnection() PrvConnection(string connectionString) Description Initializes a new instance of the PrvConnection class. Initializes a new instance of the PrvConnection class when given a string containing the connection string.

Examples The following example creates instances of the derived classes, SqlCommand and SqlConnection. The SqlConnection is opened and set as the Connection for the SqlCommand. The example then calls

ExecuteNonQuery, and closes the connection. To accomplish this, the


Sikkim Manipal University Page No. 234

DOT Net Technologies

Unit 7

ExecuteNonQuery is passed a connection string and a query string that is a Transact-SQL INSERT statement.

IDbConnection Members Represents an open connection to a data source, and is implemented by .NET Framework data providers that access relational databases. The IDbConnection type exposes the following members. Methods
Name BeginTransaction ChangeDatabase Close CreateCommand Dispose Description Overloaded. Begins a database transaction. Changes the current Connection object. database for an open

Closes the connection to the database. Creates and returns a Command object associated with the connection. Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. (Inherited from IDisposable.) Opens a database connection with the settings specified by the ConnectionString property of the provider-specific Connection object.

Open

Sikkim Manipal University

Page No. 235

DOT Net Technologies

Unit 7

Properties
Name ConnectionString ConnectionTimeout Description Gets or sets the string used to open a database. Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error. Gets the name of the current database or the database to be used after a connection is opened. Gets the current state of the connection.

Database State

The Common Logic: DbConnection The DbConnection Class Represents a connection to a database. Namespace: System.Data.Common Assembly: System.Data (in System.Data.dll) Syntax:

DbConnection Members The DbConnection type exposes the following members. Constructors
Name DbConnection Description Initializes a new instance of the DbConnection class.

Sikkim Manipal University

Page No. 236

DOT Net Technologies

Unit 7

Methods
Name BeginDbTransaction BeginTransaction ChangeDatabase Close CreateCommand CreateDbCommand CreateObjRef Description Starts a database transaction. Overloaded. Starts a database transaction. Changes the connection. current database for an open

Closes the connection to the database. This is the preferred method of closing any open connection. Creates and returns a DbCommand associated with the current connection. Creates and returns a DbCommand associated with the current connection. object object

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) Overloaded. Enlists in the specified transaction. Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.) Serves as a hash function for a particular type. (Inherited from Object.) Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Overloaded. Returns schema information for the data source of this DbConnection. Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.) Gets the Type of the current instance. (Inherited from Object.) Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Overloaded. Page No. 237

Dispose EnlistTransaction Equals Finalize

GetHashCode GetLifetimeService

GetSchema GetService

GetType InitializeLifetimeService

MemberwiseClone Sikkim Manipal University

DOT Net Technologies

Unit 7

OnStateChange Open ToString

Raises the StateChange event. Opens a database connection with the settings specified by the ConnectionString. Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.) In .NET Compact Framework 3.5, this member is inherited from Object.ToString(). In XNA Framework 1.0, this member is inherited from Object.ToString().

Properties
Name CanRaiseEvents ConnectionString ConnectionTimeout Container Database Description Gets a value indicating whether the component can raise an event. (Inherited from Component.) Gets or sets the string used to open the connection. Gets the time to wait while establishing a connection before terminating the attempt and generating an error. Gets the IContainer that contains the Component. (Inherited from Component.) Gets the name of the current database after a connection is opened, or the database name specified in the connection string before the connection is opened. Gets the name of the database server to which to connect. Gets the DbProviderFactory for this DbConnection. Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.) Gets the list of event handlers that are attached to this Component. (Inherited from Component.) Gets a string that represents the version of the server to which the object is connected. Gets or sets the ISite of the Component. (Inherited from Component.) Gets a string that describes the state of the connection.

DataSource DbProviderFactory DesignMode Events ServerVersion Site State

Sikkim Manipal University

Page No. 238

DOT Net Technologies

Unit 7

Events
Name Disposed StateChange Description Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.) Occurs when the state of the event changes.

Explicit Interface Implementations


Name IDbConnection.BeginTransaction Description Begins a database transaction. 1. BeginTransaction():Begins a database transaction. 2. BeginTransaction(IsolationLevel): Begins a database transaction with the specified IsolationLevel value.

IDbConnection.BeginTransaction IDbConnection.CreateCommand

Connection Pooling Connection pooling enables an application to use a connection from a pool of connections that do not need to be reestablished for each use. Once a connection has been created and placed in a pool, an application can reuse that connection without performing the complete connection process. Using a pooled connection can result in significant performance gains, because applications can save the overhead involved in making a connection. This can be particularly significant for middle-tier applications that connect over a network or for applications that repeatedly connect and disconnect, such as Internet applications. In addition to performance gains, the connection pooling architecture enables an environment and its associated connections to be used by multiple components in a single process. This means that stand-alone components in the same process can interact with each other without being aware of each other. A connection in a connection pool can be used repeatedly by multiple components.
Sikkim Manipal University Page No. 239

DOT Net Technologies

Unit 7

Note: Connection pooling can be used by an ODBC application exhibiting ODBC 2.x behavior, as long as the application can call SQLSetEnvAttr. When using connection pooling, the application must not execute SQL statements that change the database or the context of the database, such as changing the <database name>, which changes the catalog used by a data source. An ODBC driver must be fully thread-safe, and connections must not have thread affinity to support connection pooling. This means the driver is able to handle a call on any thread at any time and is able to connect on one thread, to use the connection on another thread, and to disconnect on a third thread. The connection pool is maintained by the Driver Manager. Connections are drawn from the pool when the application calls SQLConnect or SQLDriverConnect and are returned to the pool when the application calls SQLDisconnect. The size of the pool grows dynamically, based on the requested resource allocations. It shrinks based on the inactivity timeout: If a connection is inactive for a period of time (it has not been used in a connection), it is removed from the pool. The size of the pool is limited only by memory constraints and limits on the server. The Driver Manager determines whether a specific connection in a pool should be used according to the arguments passed in SQLConnect or SQLDriverConnect, and according to the connection attributes set after the connection was allocated. When the Driver Manager is pooling connections, it needs to be able to determine if a connection is still working before handing out the connection. Otherwise, the Driver Manager keeps on handing out the dead connection to the application whenever a transient network failure occurs. A new connection attribute has been defined in ODBC 3.x: SQL_ATTR_CONNECTION_DEAD. This is a read-only connection attribute that returns either SQL_CD_TRUE or SQL_CD_FALSE. The value
Sikkim Manipal University Page No. 240

DOT Net Technologies

Unit 7

SQL_CD_TRUE means that the connection has been lost, while the value SQL_CD_FALSE means that the connection is still active. (Drivers conforming to earlier versions of ODBC can also support this attribute.) A driver must implement this option efficiently or it will impair the connection pooling performance. Specifically, a call to get this connection attribute should not cause a round trip to the server. Instead, a driver should just return the last known state of the connection. The connection is dead if the last trip to the server failed, and not dead if the last trip succeeded. In order to prevent unwanted repeated attempts by the Driver Manager to reestablish a connection when connection pooling is enabled, you can set ODBCGetTryWaitValue. ODBCSetTryWaitValue saves the information in the registry at the following location: HKEY_LOCAL_MACHINE\Software\Odbc\Odbcinst.ini\ODBC Connection Pooling\Retry Wait

7.9 XML & ADO.NET


With ADO.NET you can fill a DataSet from an XML stream or document. You can use the XML stream or document to supply to the DataSet either data, schema information, or both. The information supplied from the XML stream or document can be combined with existing data or schema information already present in the DataSet. ADO.NET also allows you to create an XML representation of a DataSet, with or without its schema, in order to transport the DataSet across HTTP for use by another application or XML-enabled platform. In an XML representation of a DataSet, the data is written in XML and the schema, if it is included inline in the representation, is written using the XML Schema definition language (XSD). XML and XML Schema provide a convenient format for transferring the contents of a DataSet to and from remote clients.

Sikkim Manipal University

Page No. 241

DOT Net Technologies

Unit 7

Loading a DataSet from XML The contents of an ADO.NET DataSet can be created from an XML stream or document. In addition, with the .NET Framework you have great flexibility over what information is loaded from XML, and how the schema or relational structure of the DataSet is created. To fill a DataSet with data from XML, use the ReadXml method of the DataSet object. The ReadXml method reads from a file, a stream, or an XmlReader, and takes as arguments the source of the XML plus an optional XmlReadMode argument. The ReadXml method reads the contents of the XML stream or document and loads the DataSet with data. It will also create the relational schema of the DataSet depending on the XmlReadMode specified and whether or not a relational schema already exists. The following table describes the options for the XmlReadMode argument.
Option Auto Description This is the default. Examines the XML and chooses the most appropriate option in the following order: If the XML is a DiffGram, DiffGram is used. If the DataSet contains a schema or the XML contains an inline schema, ReadSchema is used. If the DataSet does not contain a schema and the XML does not contain an inline schema, InferSchema is used. If you know the format of the XML being read, for best performance it is recommended that you set an explicit XmlReadMode, rather than accept the Auto default. Reads any inline schema and loads the data and schema. If the DataSet already contains a schema, new tables are added from the inline schema to the existing schema in the DataSet. If any tables in the inline schema already exist in the DataSet, an exception is thrown. You will not be able to modify the schema of an existing table using XmlReadMode.ReadSchema. If the DataSet does not contain a schema, and there is no inline schema, no data is read. Inline schema can be defined using XML Schema definition language (XSD) schema.

ReadSchema

Sikkim Manipal University

Page No. 242

DOT Net Technologies

Unit 7

IgnoreSchema

Ignores any inline schema and loads the data into the existing DataSet schema. Any data that does not match the existing schema is discarded. If no schema exists in the DataSet, no data is loaded. If the data is a DiffGram, IgnoreSchema has the same functionality as DiffGram. Ignores any inline schema and infers the schema per the structure of the XML data, then loads the data. If the DataSet already contains a schema, the current schema is extended by adding columns to existing tables. Extra tables will not be added if there are not existing tables. An exception is thrown if an inferred table already exists with a different namespace, or if any inferred columns conflict with existing columns. Reads a DiffGram and adds the data to the current schema. DiffGram merges new rows with existing rows where the unique identifier values match. Continues reading multiple XML fragments until the end of the stream is reached. Fragments that match the DataSet schema are appended to the appropriate tables. Fragments that do not match the DataSet schema are discarded.

InferSchema

DiffGram

Fragment

DTD Entities If your XML contains entities defined in a document type definition (DTD) schema, an exception will be thrown if you attempt to load a DataSet by passing a file name, stream, or non-validating XmlReader to ReadXml. Instead, you must create an XmlValidatingReader, with EntityHandling set to EntityHandling.ExpandEntities, and pass your XmlValidatingReader to ReadXml. The XmlValidatingReader will expand the entities prior to being read by the DataSet. The following code examples show how to load a DataSet from an XML stream. The first example shows a file name being passed to the ReadXml method. The second example shows a string that contains XML being loaded using a StringReader.
C# Code DataSet dataSet = new DataSet(); dataSet.ReadXml("input.xml", XmlReadMode.ReadSchema); Sikkim Manipal University Page No. 243

DOT Net Technologies

Unit 7

If you call ReadXml to load a very large file, you may encounter slow performance. To ensure best performance for ReadXml, on a large file, call the BeginLoadData method for each table in the DataSet, and then call ReadXml. Finally, call EndLoadData for each table in the DataSet, as shown in the following example.

If the XSD schema for your DataSet includes a targetNamespace, data may not be read, and you may encounter exceptions, when calling ReadXml to load the DataSet with XML that contains elements with no
Sikkim Manipal University Page No. 244

DOT Net Technologies

Unit 7

qualifying namespace. To read unqualified elements in this case, set elementFormDefault equal to "qualified" in your XSD schema. For example: <xsd:schema id="customDataSet" elementFormDefault="qualified" targetNamespace="http://www.tempuri.org/customDataSet.xsd" xmlns="http://www.tempuri.org/customDataSet.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> </xsd:schema>

Merging Data from XML If the DataSet already contains data, the new data from the XML is added to the data already present in the DataSet. ReadXml does not merge from the XML into the DataSet any row information with matching primary keys. To overwrite existing row information with new information from XML, use ReadXml to create a new DataSet, and then Merge the new DataSet into the existing DataSet. Note that loading a DiffGram using ReadXML with an XmlReadMode of DiffGram will merge rows that have the same unique identifier. Deriving DataSet Relational Structure from XML Schema (XSD) This section provides an overview of how the relational schema of a DataSet is built from an XML Schema definition language (XSD) schema document. In general, for each complexType child element of a schema element, a table is generated in the DataSet. The table structure is determined by the definition of the complex type. Tables are created in the DataSet for top-level elements in the schema. However, a table is only created for a top-level complexType element when the complexType element is nested inside another complexType element, in which case the
Sikkim Manipal University Page No. 245

DOT Net Technologies

Unit 7

nested complexType element is mapped to a DataTable within the DataSet. The following example demonstrates an XML Schema where customers is the child element of the MyDataSet element, which is a DataSet element. <xs:schema id="SomeID" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="MyDataSet" msdata:IsDataSet="true"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="customers" > <xs:complexType > <xs:sequence> <xs:element name="CustomerID" type="xs:integer" minOccurs="0" />

<xs:element name="CompanyName" type="xs:string" minOccurs="0" /> <xs:element name="Phone" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> In the preceding example, the element customers is a complex type element. Therefore, the complex type definition is parsed, and the mapping process creates the following table. Customers (CustomerID , CompanyName, Phone)

Sikkim Manipal University

Page No. 246

DOT Net Technologies

Unit 7

The data type of each column in the table is derived from the XML Schema type of the corresponding element or attribute specified. Note: If the element customers is of a simple XML Schema data type such as integer, no table is generated. Tables are only created for the top-level elements that are complex types. In the following XML Schema, the Schema element has two element children, InStateCustomers and OutOfStateCustomers. <xs:schema id="SomeID" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="InStateCustomers" type="customerType" /> <xs:element name="OutOfStateCustomers" type="customerType" /> <xs:complexType name="customerType" > </xs:complexType> <xs:element name="MyDataSet" msdata:IsDataSet="true"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element ref="customers" /> </xs:choice> </xs:complexType> </xs:element> </xs:schema> Both the InStateCustomers and the OutOfStateCustomers child elements are complex type elements (customerType). Therefore, the mapping process generates the following two identical tables in the DataSet InStateCustomers (CustomerID , CompanyName, Phone) OutOfStateCustomers (CustomerID , CompanyName, Phone) Mapping XML Schema (XSD) Constraints to DataSet Constraints The XML Schema definition language (XSD) allows constraints to be specified on the elements and attributes it defines. When mapping an XML
Sikkim Manipal University Page No. 247

DOT Net Technologies

Unit 7

Schema to relational schema in a DataSet, XML Schema constraints are mapped to appropriate relational constraints on the tables and columns within the DataSet. This section discusses the mapping of the following XML Schema constraints: The uniqueness constraint specified using the unique element. The key constraint specified using the key element. The keyref constraint specified using the keyref element.

By using a constraint on an element or attribute, you specify certain restrictions on the values of the element in any instance of the document. For example, a key constraint on a CustomerID child element of a Customer element in the schema indicates that the values of the CustomerID child element must be unique in any document instance, and that null values are not allowed. Constraints can also be specified between elements and attributes in a document, in order to establish a relationship within the document. The key and keyref constraints are used in the schema to specify the constraints within the document, resulting in a relationship between document elements and attributes. The mapping process converts these schema constraints into appropriate constraints on the tables created within the DataSet. Map unique XML Schema (XSD) Constraints to DataSet Constraints In an XML Schema definition language (XSD) schema, the unique element specifies the uniqueness constraint on an element or attribute. In the process of translating an XML Schema into a relational schema, the unique constraint specified on an element or attribute in the XML Schema is mapped to a unique constraint in the DataTable in the corresponding DataSet that is generated.
Sikkim Manipal University Page No. 248

DOT Net Technologies

Unit 7

The following table outlines the msdata attributes that you can specify in the unique element.
Attribute name msdata:ConstraintName Description If this attribute is specified, its value is used as the constraint name. Otherwise, the name attribute provides the value of the constraint name. If PrimaryKey="true" is present in the unique element, a unique constraint is created with the IsPrimaryKey property set to true.

msdata:PrimaryKey

The following example shows an XML Schema that uses the unique element to specify a uniqueness constraint.

</xs:complexType> <xs:unique msdata:ConstraintName="UCustID" name="UniqueCustIDConstr" > <xs:selector xpath=".//Customers" /> <xs:field xpath="CustomerID" /> </xs:unique> </xs:element> </xs:schema> The unique element in the schema specifies that for all Customers elements in a document instance, the value of the CustomerID child element must be unique. In building the DataSet, the mapping process reads this schema and generates the following table:
Sikkim Manipal University Page No. 249

DOT Net Technologies

Unit 7

Customers (CustomerID, CompanyName, Phone) The mapping process also creates a unique constraint on the CustomerID column, as shown in the following DataSet. (For simplicity, only relevant properties are shown.) DataSetName: MyDataSet TableName: Customers ColumnName: CustomerID AllowDBNull: True Unique: True ConstraintName: UcustID Type: UniqueConstraint Table: Customers Columns: CustomerID IsPrimaryKey: False

In the DataSet that is generated, the IsPrimaryKey property is set to False for the unique constraint. The unique property on the column indicates that the CustomerID column values must be unique (but they can be a null reference, as specified by the AllowDBNull property of the column). If you modify the schema and set the optional msdata:PrimaryKey attribute value to True, the unique constraint is created on the table. The AllowDBNull column property is set to False, and the IsPrimaryKey property of the constraint set to True, thus making the CustomerID column a primary key column. You can specify a unique constraint on a combination of elements or attributes in the XML Schema. The following example demonstrates how to specify that a combination of CustomerID and CompanyName values must be unique for all Customers in any instance, by adding another xs:field element in the schema.

Sikkim Manipal University

Page No. 250

DOT Net Technologies

Unit 7

<xs:unique msdata:ConstraintName="SomeName" name="UniqueCustIDConstr" > <xs:selector xpath=".//Customers" /> <xs:field xpath="CustomerID" /> <xs:field xpath="CompanyName" /> </xs:unique> This is the constraint that is created in the resulting DataSet. ConstraintName: SomeName Table: Customers Columns: CustomerID CompanyName IsPrimaryKey: False Generating DataSet Relations from XML Schema (XSD) In a DataSet, you form an association between two or more columns by creating a parent-child relation. There are three ways to represent a DataSet relation within an XML Schema definition language (XSD) schema: Specify nested complex types. Use the msdata:Relationship annotation. Specify an xs:keyref without the msdata:ConstraintOnly annotation.

Nested Complex Types Nested complex type definitions in a schema indicate the parent-child relationships of the elements. The following XML Schema fragment shows that OrderDetail is a child element of the Order element. <xs:element name="Order"> <xs:complexType> <xs:sequence> <xs:element name="OrderDetail" /> <xs:complexType> </xs:complexType> </xs:sequence> </xs:complexType> </xs:element>

Sikkim Manipal University

Page No. 251

DOT Net Technologies

Unit 7

msdata:Relationship Annotation The msdata:Relationship annotation allows you to explicitly specify parentchild relationships between elements in the schema that are not nested. The following example shows the structure of the Relationship element. <msdata:Relationship name="CustOrderRelationship" msdata:parent="" msdata:child="" msdata:parentkey="" msdata:childkey="" /> <xs:element name="MyDataSet" msdata:IsDataSet="true"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="OrderDetail"> <xs:complexType> </xs:complexType> </xs:element> <xs:element name="Order"> <xs:complexType> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> <xs:annotation> <xs:appinfo> <msdata:Relationship name="OrdOrdDetailRelation" msdata:parent="Order">

The mapping process uses the Relationship element to create a parentchild relationship between the OrderNumber column in the Order table and the OrderNo column in the OrderDetail table in the DataSet. The mapping process only specifies the relationship; it does not automatically specify any constraints on the values in these columns, as do the primary key/foreign key constraints in relational databases.

Sikkim Manipal University

Page No. 252

DOT Net Technologies

Unit 7

7.10 Summary
This unit provides with an overview of the features of ADO.NET. It makes the user comfortable with developing database applications in a disconnected architecture. It also introduces the user with various ways of connecting to a data source using ADO.NET. It introduces the concept of connection strings and connection string builders in ADO.NET. It then takes the user through the concepts of namespaces and classes in ADO.NET. It demonstrates the usage of the feature DataAdapter in fetching the data from any database using ADO.NET. It then demonstrates how XML data can be used with ADO.NET.

Self Assessment Questions 1. The _____ was first introduced in version 1.0 of the .NET framework, that provided an extensive array of features to handle live data in a connected mode or data that is disconnected from its underlying data store. 2. ADO.NET is the database language spoken by ______ applications. 3. In __________ architecture, data is retrieved from a database and cached on your local machine. You manipulate the data on your local computer and connect to the database only when you wish to alter records or acquire new data. 4. The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in ________. 5. The .NET Framework Data Provider for OLE DB uses the ____________ namespace. 6. The ______ is a helper object that automatically generates command properties of a DataAdapter or derives parameter information from a stored procedure and populates the Parameters collection of a Command object.
Sikkim Manipal University Page No. 253

DOT Net Technologies

Unit 7

7. The _______ driver is the Microsoft OLE DB provider for Oracle. 8. The _____ block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception.

7.11 Terminal Questions


1. Describe the process of connection establishment to a data source using ADO.NET. (Refer to 7.2) 2. Discuss about Connection String Builders in ADO.NET (Refer to 7.4) 3. Write the basic features of ADO.NET (Refer to 7.6) 4. Write about the combined usage of XML and ADO.NET (Refer to 7.9)

7.12 Answers to Self Assessment Questions


1. ADO.NET 2. managed 3. disconnected 4. System.Xml.dll 5. System.Data.OleDb 6. CommandBuilder 7. MSDAORA 8. Using

Sikkim Manipal University

Page No. 254

DOT Net Technologies

Unit 8

Unit 8
Structure: 8.1 Introduction to Web Services Objectives 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9 8.10 8.11 8.12 8.13 Your First Web Service Testing a Web Service Web Services and Code-Behind

Web Services

The Web Services Description Language (WSDL) Web Services and Complex Data Types Web Service Discovery DISCO Web Service Discovery UDDI Web Service Clients Web Service Proxies A Simple Web Service Client A brief overview of Web Service Standards Summary Self Assessment Questions

8.14 8.15

Terminal Questions Answers to Self Assessment Questions

8.1 Introduction to Web Services


Read any book, paper, or magazine article about Microsoft .NET and youll encounter one term over and over: XML Web services. XML Web services, or simply Web services as they are more often called, are the cornerstone of the Microsoft .NET initiative. Theyre the key to Microsofts vision of a world in which computers talk to each other over the Web using HTTP and other universally supported protocols. And theyre the number one reason that the Microsoft .NET Framework which exists in the first place to make

Sikkim Manipal University

Page No. 255

DOT Net Technologies

Unit 8

it as easy as humanly possible to build Web services and Web service clients. A Web service is a different kind of Web application. It doesnt have a user interface as does a traditional Web application. Instead, it exposes callable API functions, better known as Web methods, over the Internet. Its not designed to serve end users as traditional Web applications are. Its designed to provide services to other applications, be they Web applications, GUI applications, or even command-line applications. What kinds of services do Web services provide? Thats up to the implementer. A Web service could provide real-time stock quotes to interested parties. It could validate credit cards or provide current information about the weather. Like traditional applications, Web services are as diverse as their creators imaginations. Microsoft, Sun, IBM, and others foresee a world in which all sorts of interesting information is made available via Web services. To the extent that developers embrace that vision, Web services will one day be the backbone of a highly programmable Internet an Internet that doesnt just serve end users, but one that allows servers to communicate with each other and applications to be freed from the bonds of the platforms on which they run. An application that speaks the language of Web services has access to a universe of services that is just now emerging. Already, companies all over the world are exposing content and business logic through Web services. As one of this chapters sample programs demonstrates, its easy to build a Web service client that takes city and state names as input and fetches satellite images of said cities, thanks to Microsoft TerraService, which is a front end to a massive database of satellite images, aerial photographs, and topo maps of much of Earths surface and is freely available to anyone who wants to use it. In the future, youll see applications that use Web services to check the status of overnight packages or display the soup of the day at
Sikkim Manipal University Page No. 256

DOT Net Technologies

Unit 8

your favorite restaurant. Web services have the potential to change the world as few technologies ever have. And Microsoft .NET will play a huge role in that change, primarily because the .NET Framework makes writing Web services and Web service clients so incredibly easy. Web services are not the property of Microsoft. Theyre an industry standard built on open protocols such as HTTP and the Simple Object Access Protocol (SOAP). Many of the Web services in operation today run on UNIX servers. You dont need the .NET Framework to write Web services or Web service clients, but you want the framework because it makes writing Web services and Web service clients easy. A few button clicks in Visual Studio .NET creates a Web service and exposes Web methods to anyone that you provide a URL to. Creating a Web service client requires equally little effort. You dont even have to use Visual Studio .NET. You can write powerful Web services with Notepad, which is precisely what well do in this chapter to introduce the brave new world of Web services and applications that use them. A great place to begin an exploration of Web services is to define precisely what a Web service is. A Web service is an application that:

Runs on a Web server Exposes Web methods to interested callers Listens for HTTP requests representing commands to invoke Web methods

Executes Web methods and returns the results

Definition-2: Web Services. A Web service is a network accessible interface to application functionality, built using standard Internet

technologies.

Sikkim Manipal University

Page No. 257

DOT Net Technologies

Unit 8

Figure 8.1: A web service allows access to application code using standard Internet technologies

In other words, if an application can be accessed over a network using a combination of protocols like HTTP, XML, SMTP, or Jabber, then it is a web service. Despite all the media hype around web services, it really is that simple. Web services are nothing new. Rather, they represent the evolution of principles that have guided the Internet for years. A web service is an interface positioned between the application code and the user of that code. It acts as an abstraction layer, separating the platform and programming-language-specific details of how the application code is actually invoked. This standardized layer means that any language that supports the web service can access the application's functionality.

Figure 8.2: Web services provide an abstraction layer between the application client and the application code

The web services that we see deployed on the Internet today are HTML web sites. In these, the application services the mechanisms for publishing, managing, searching, and retrieving content are accessed through the use of standard protocols and data formats: HTTP and HTML. Client

Sikkim Manipal University

Page No. 258

DOT Net Technologies

Unit 8

applications (web browsers) that understand these standards can interact with the application services to perform tasks like ordering books, sending greeting cards, or reading news. Because of the abstraction provided by the standards-based interfaces, it does not matter whether the application services are written in Java and the browser written in C++, or the application services deployed on a Unix box while the browser is deployed on Windows. Web services allow for crossplatform interoperability in a way that makes the platform irrelevant. Interoperability is one of the key benefits gained from implementing web services. Java and Microsoft Windows-based solutions have typically been difficult to integrate, but a web services layer between application and client can greatly remove friction. Web services are a messaging framework. The only requirement placed on a web service is that it must be capable of sending and receiving messages using some combination of standard Internet protocols. The most common form of web services is to call procedures running on a server, in which case the messages encode "Call this subroutine with these arguments," and "Here are the results of the subroutine call." Figure 8.3 shows the pieces of a web service. The application code holds all the business logic and code for actually doing things (listing books, adding a book to a shopping cart, paying for books, etc.). The Service Listener speaks the transport protocol (HTTP, SOAP, Jabber, etc.) and receives incoming requests. The Service Proxy decodes those requests into calls into the application code. The Service Proxy may then encode a response for the Service Listener to reply with, but it is possible to omit this step.

Sikkim Manipal University

Page No. 259

DOT Net Technologies

Unit 8

Figure 8.3: A web service consists of several key components

The Service Proxy and Service Listener components may either be standalone applications (a TCP-server or HTTP-server daemon, for instance) or may run within the context of some other type of application server. As an example, IBM's WebSphere Application Server includes builtin support for receiving a SOAP message over HTTP and using that to invoke Java applications deployed within WebSphere. Keep in mind, however, that web services do not require a server environment to run. Web services may be deployed anywhere that the standard Internet technologies can be used. This means that web services may be hosted or used by anything from an Application Service Provider's vast server farm to a PDA. Web services do not require that applications conform to a traditional clientserver (where the server holds the data and does the processing) or n-tier development model (where data storage is separated from business logic that is separated from the user interface), although they are certainly being heavily deployed within those environments. Web services may take any form, may be used anywhere, and may serve any purpose. For instance, there are strong crossovers between peer-to-peer systems (with

decentralized data or processing) and web services where peers use standard Internet protocols to provide services to one another.

Sikkim Manipal University

Page No. 260

DOT Net Technologies

Unit 8

Once you understand the basic web services outlined earlier, the next step is to add Just-In-Time Integration. That is, the dynamic integration of application services based not on the technology platform the services are implemented in, but upon the business requirements of what needs to get done. Just-In-Time Integration recasts the Internet application development model around a new framework called the web services architecture (Figure 8.4).

Figure 8.4: The Web Services Architecture

In the web services architecture, the service provider publishes a description of the service(s) it offers via the service registry. The service consumer searches the service registry to find a service that meets their needs. The service consumer could be a person or a program. Binding refers to a service consumer actually using the service offered by a service provider. The key to Just-in-Time integration is that this can happen at any time, particularly at runtime. That is, a client might not know which procedures it will be calling until it is running, searches the registry, and identifies a suitable candidate. This is analogous to late binding in objectoriented programming. Imagine a purchasing web service, where consumers requisition products from a service provider. If the client program has hard-coded the server it talks to, then the service is bound at compile-time. If the client program searches for a suitable server and binds to that, then the service is bound at
Sikkim Manipal University Page No. 261

DOT Net Technologies

Unit 8

runtime. The latter is an example of Just-In-Time integration between services. Most Web services expect their Web methods to be invoked using HTTP requests containing SOAP messages. SOAP is an XML-based vocabulary for performing remote procedure calls using HTTP and other protocols. You can read all about it at http://www.w3.org/TR/SOAP. Suppose you write a Web service that publishes Web methods named Add and Subtract that callers can use to add and subtract simple integers. If the services URL is www.wintellect.com/calc.asmx, heres how a client would invoke the Add method by transmitting a SOAP envelope in an HTTP request. This example adds 2 and 2:

Sikkim Manipal University

Page No. 262

DOT Net Technologies

Unit 8

And heres how the Web service would respond:


HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: 353 <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <AddResponse xmlns="http://tempuri.org/"> <AddResult>4</AddResult> </AddResponse> </soap:Body> </soap:Envelope>

The Web services job is to parse the SOAP envelope containing the inputs, add 2 and 2, formulate a SOAP envelope containing the sum of 2 and 2, and return it to the client in the body of the HTTP response. This, at the most elemental level, is what Web services are all about. Web services written with the .NET Framework also allow their Web methods to be invoked using ordinary HTTP GET and POST commands. The following GET command adds 2 and 2 by invoking the Web services Add method: GET /calc.asmx/Add?a=2&b=2 HTTP/1.1 Host: www.wintellect.com The Web service responds as follows:
HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: 80 <?xml version="1.0" encoding="utf-8"?> <int xmlns="http://tempuri.org/">4</int> Sikkim Manipal University Page No. 263

DOT Net Technologies

Unit 8

Heres a POST command that adds 2 and 2: POST /calc.asmx/Add HTTP/1.1 Host: www.wintellect.com Content-Type: application/x-www-form-urlencoded Content-Length: 7 a=2&b=2

And heres the Web services response: HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: 80 <?xml version="1.0" encoding="utf-8"?> <int xmlns="http://tempuri.org/">4</int> As you can imagine, the hard part of writing a Web service is parsing HTTP requests and generating HTTP responses. But as youll see in the next section and throughout the remainder of this chapter, the .NET Framework insulates developers from the low-level details of HTTP, SOAP, and XML and provides a high-level framework for writing Web services and Web service clients alike. There are many ways to write Web services. You can write Web services by hand. You can use SOAP toolkits from Microsoft, IBM, and other companies. And you can use the .NET Framework. Because this book is about Microsoft .NET, this chapter is about the latter. Writing Web services with the .NET Framework offers two advantages over all the other methods: The .NET Framework makes writing Web services extremely easy. Web services written with the .NET Framework are managed applications, which means you shouldnt have to worry about memory

Sikkim Manipal University

Page No. 264

DOT Net Technologies

Unit 8

leaks, stray pointers, and other maladies that bedevil programmers and cost more than their fair share of development time. What does it take to write a Web service using the .NET Framework? Im glad you asked, because thats what the next section is about. Objectives This unit emphasizes the usage of Web Services in any Web based application development. At the end of this unit the reader would be able to: Define and Describe the concept of Web Service Develop and demonstrate a Web service Describe the testing procedure of a Web Service Discuss the concept of code-behind Web services Describe the usage of Web Service Description Language Describe the usage of complex data types in Web Services Describe the features of sample Web services like DISCO and UDDI Describe the role of Web clients and Web proxies Write a simple Web service client Give an overview of Web Service Standards

8.2 Your First Web Service


The ASMX file shown in Figure 8.5 is a complete Web service. It implements two Web methods: Add and Subtract. Both take two integers as input and return an integer as well. Deploying the Web service is as simple as copying it to a directory on your Web server that is URL-addressable. If you put Calc.asmx in wwwroot, the Web services local URL is http://localhost/calc.asmx.

Sikkim Manipal University

Page No. 265

DOT Net Technologies

Unit 8

Calc.asmx demonstrates several important principles of Web service programming using the .NET Framework:

Web services are implemented in ASMX files. ASMX is a special file name extension registered to ASP.NET (specifically, to an ASP.NET HTTP handler) in Machine.config.

ASMX files begin with @ WebService directives. At a minimum, the directive must contain a Class attribute identifying the class that makes up the Web service.

Web service classes can be attributed with optional WebService attributes. The one in this example assigns the Web service a name and a description that show up in the HTML page generated when a user calls up Calc.asmx in his or her browser. The WebService attribute also supports a Namespace parameter that can be used to change the name of the XML namespace that scopes the Web services members.

Web methods are declared by tagging public methods in the Web service class with WebMethod attributes. You can build helper methods into a Web service methods that are used internally by Web methods but that are not exposed as Web methods themselves by omitting the attribute. The WebMethod attributes in Figure 8.5 also assign descriptive text to their Web methods. Youll learn more about Description and other WebMethod parameters in the section entitled The WebMethod Attribute.

HTTP, XML, and SOAP are hidden under the hood. You dont have to deal with raw XML data or SOAP messages because the .NET Framework deals with them for you.

Sikkim Manipal University

Page No. 266

DOT Net Technologies

Unit 8

Figure 8.5: Calc Web service

Despite its brevity, Calc.asmx is a full-blown Web service when installed on a Web server outfitted with ASP.NET. Its Web methods can be invoked with SOAP, HTTP GET, and HTTP POST, and its capable of returning output in SOAP responses or simple XML wrappers. All we need now is a way to test it out. The .NET Framework lends a hand there too.

8.3 Testing a Web Service


How do you test an ASMX Web service? Simple: just call it in your browser. To demonstrate, copy Calc.asmx to wwwroot and type http://localhost/calc.asmx in your browsers address bar. Youll be greeted with the screen shown in Figure 8.6. What happened? ASP.NET responded to the HTTP request for Calc.asmx by generating an HTML page that describes the Web service.
Sikkim Manipal University Page No. 267

DOT Net Technologies

Unit 8

The name and description in the ASMX files WebService attribute appear at the top of the page. Underneath is a list of Web methods that the service exposes, complete with the descriptions spelled out in the WebMethod attributes.

Figure 8.6: Calc.asmx as seen in Internet Explorer

Click Add near the top of the page, and ASP.NET displays a page that you can use to test the Add method (Figure 8.7). ASP.NET knows the method name and signature because it reads them from the metadata in the DLL it compiled from Calc.asmx. It even generates an HTML form that you can use to call the Add method with your choice of inputs. Type 2 and 2 into the a and b boxes and click Invoke. The XML returned by the Web method appears in a separate browser window (Figure 8.8).

Sikkim Manipal University

Page No. 268

DOT Net Technologies

Unit 8

Figure 8.7: Test page for the Add method

Figure 8.8: XML returned by the Add method

The forms that ASP.NET generates on the fly from ASMX files enable you to test the Web services that you write without writing special clients to test them with. They also let you explore a Web service built with the .NET Framework simply by pointing your browser to it. For kicks, type the following URL into your browsers address bar: http://terraservice.net/terraservice.asmx Thats the URL of the Microsoft TerraService, an ultra-cool Web service that provides a programmatic interface to a massive database of geographic data known as the Microsoft TerraServer. Dont worry about the details just yet; youll be using TerraService to build a Web service client later in this

Sikkim Manipal University

Page No. 269

DOT Net Technologies

Unit 8

chapter. But do notice how much you can learn about TerraService simply by viewing the page that ASP.NET generated for it.

8.4 Web Services and Code-Behind


You can use code-behind to move Web service classes out of ASMX files and into separately compiled DLLs. Figure 8.9 shows how Calc.asmx looks after its modified to take advantage of code-behind. The ASMX file now contains just one statement. The class referenced in that statement is implemented in Calc.cs. The following command compiles Calc.cs into a DLL named Calc.dll: csc /t:library calc.cs Once compiled, the DLL must be placed in the application roots bin subdirectory (for example, wwwroot\bin).
<%@ WebService Class="CalcService" %> Calc.cs using System; using System.Web.Services; [WebService (Name="Calculator Web Service", Description="Performs simple math over the Web")] class CalcService { [WebMethod (Description="Computes the sum of two integers")] public int Add (int a, int b) { return a + b; } [WebMethod (Description="Computes the difference between two integers")] public int Subtract (int a, int b) { return a - b; } } Figure 8.9: Calc Web service with code-behind

Code-behind offers the same benefits to Web services that it offers to Web pages: it catches compilation errors before the service is deployed, and it
Sikkim Manipal University Page No. 270

DOT Net Technologies

Unit 8

enables you to write Web services in languages that ASP.NET doesnt natively support. The WebService Base Class Very often when you see ASMX code samples, the Web service classes inside them derive from a class named WebService, as in class CalcService : WebService { ... } WebService belongs to the System.Web.Services namespace. It contributes properties named Application, Session, Context, Server, and User to derived classes, enabling a Web service to access the ASP.NET objects with the same names. If you dont use these objects in your Web service for example, if you dont use application state or session stateyou dont need to derive from WebService either. The WebMethod Attribute The WebMethod attribute tags a method as a Web method. The .NET Framework automatically exposes such methods as Web methods when theyre implemented inside a Web service. WebMethod is capable of doing much more, however, than simply letting the framework know which methods are Web methods and which are not; it also supports the following parameters:
Parameter Name BufferResponse CacheDuration Description EnableSession MessageName TransactionOption Sikkim Manipal University Description Enables and disables response buffering Caches responses generated by this method for the specified number of seconds Adds a textual description to a Web method Enables and disables session state for this Web method Specifies the Web methods name Specifies the transactional behavior of a Web method Page No. 271

DOT Net Technologies

Unit 8

CacheDuration is the ASMX equivalent of an @ OutputCache directive in an ASPX or ASCX file: it caches a methods output so that subsequent requests will execute more quickly. For example you write a Web method that returns the current time: [WebMethod] public string GetCurrentTime () { return DateTime.Now.ToShortTimeString (); } Since ToShortTimeString returns a string that includes minutes but not seconds, it is wasteful to execute it too often. The following method declaration uses CacheDuration to cache the output for 10 seconds at a time: [WebMethod (CacheDuration="10")] public string GetCurrentTime () { return DateTime.Now.ToShortTimeString (); } Now the data that the method returns could be stale by a few seconds, but if the Web service is getting pounded with calls to GetCurrentTime, the load on it will be reduced commensurately. Web services enjoy access to the same session state facilities that conventional ASP.NET applications do. By default, however, session state is disabled for Web methods. You can enable it with WebMethods EnableSession parameter. If you want to use session state in a Web service, derive from WebService (to inherit its Session property) and tag each Web method that uses session state with EnableSession=true:

Sikkim Manipal University

Page No. 272

DOT Net Technologies

Unit 8

class CalcService : WebService { [WebMethod (EnableSession="true", Description="Adds an item to a shopping cart")] public void AddToCart (Item item) { ShoppingCart cart = (ShoppingCart) Session["MyShoppingCart"]; cart.Add (item); } }

Session state utilization is less common in Web services than in conventional Web applications, but it is an option nonetheless. The MessageName parameter lets you assign a Web method a name other than that of the method that implements it. For example, suppose that you build two Add methods into a Web service one that adds integers and another that adds floating point values and you tag both of them as Web methods:
[WebMethod] public int Add (int a, int b) { return a + b; } [WebMethod] public float Add (float a, float b) { return a + b; }

The only problem with this code is that it doesnt compile. C# methods can be overloaded, but Web methods cannot. The solution? Either change the method names or add MessageName parameters to the WebMethod attributes, as demonstrated here:

Sikkim Manipal University

Page No. 273

DOT Net Technologies

Unit 8

[WebMethod (MessageName="AddInts")]
public int Add (int a, int b) { return a + b; } [WebMethod (MessageName="AddFloats")] public float Add (float a, float b) { return a + b; }

Now the C# methods remain overloaded, but the corresponding Web methods are named AddInts and AddFloats.

8.5 The Web Services Description Language (WSDL)


If other developers are to consume (that is, write clients for) a Web service that you author, they need to know what Web methods your service publishes, what protocols it supports, the signatures of its methods, and the Web services location (URL), among other things. All this information and more can be expressed in a language called the Web Services Description Language, or WSDL for short. WSDL is a relatively new standard. Its an XML vocabulary devised by IBM, Microsoft, and others. Its syntax is documented at http://www.w3.org/TR/wsdl. I wont describe the details of the language here for several reasons. First, the details are already documented in the spec. Second, WSDL is a language for machines, not humans. Third, its trivial to generate a WSDL contract for a Web service built with the .NET Framework: simply point your browser to the Web services URL and append a WSDL query string, as in http://www.wintellect.com/calc.asmx?wsdl Figure 8.10 shows the result. Scan through it and youll find a service element that describes the Web service; operation elements that document the operations, or Web methods, that the service supports; binding elements that document the protocols that the Web methods support; and other descriptive information.
Sikkim Manipal University Page No. 274

DOT Net Technologies

Unit 8

Figure 8.10: WSDL contract for Calc.asmx

When you publish a Web service, you should also publish a WSDL contract describing it. For a Web service built with the .NET Framework, the contract is usually nothing more than a URL with ?wsdl on the end. Other developers can use the contract to write clients for your Web service. Typically, they dont read the contract themselves. Instead, they run it through a tool that generates a wrapper class containing all the elements needed to talk to a Web service. The .NET Framework SDK includes one such tool: its called Wsdl.exe. Youll learn all about it later in this chapter when we turn our attention from Web services to Web service clients.

8.6 Web Services and Complex Data Types


Its not hard to understand how simple data types can be passed to and from Web methods. After all, integers and other primitive types are defined in one form or another on virtually every platform. But what about more complex types? What if, for example, you define a custom class or struct and want to use it as an input parameter or return value for a Web method? Are complex types supported, and if so, how do you declare them so that they become an intrinsic part of the Web service?

Sikkim Manipal University

Page No. 275

DOT Net Technologies

Unit 8

Complex types are supported, and they work very well because virtually any type can be represented in XML. As an example, consider the Web service in Figure 8.11. It exposes a Web method named FindStores that accepts a state abbreviation (for example, CA) as input. FindStores calls a local method named FindByState, which queries the Pubs database that comes with Microsoft SQL Server for all the bookstores in the specified state and returns the results in an array of Bookstore objects. (Observe that FindByState is not a Web method because it lacks a WebMethod attribute.) FindStores returns the array to the client. Bookstore is a custom type defined in the ASMX file. Figure 8.12shows the XML returned when FindStores is called with the input string CA. The array of Bookstore objects has been serialized into XML. The serialization is performed by the .NET Frameworks System.Xml.Serialization.XmlSerializer class, otherwise known as the XML serializer. A client application that receives the XML and that has a schema describing the structure and content of the data can rehydrate the information into Bookstore objects. Or it can take the raw XML and do with it as it pleases.
Locator.asmx <%@ WebService Language="C#" Class="LocatorService" %> using System; using System.Web.Services; using System.Data; using System.Data.SqlClient; [WebService (Name="Bookstore Locator Service", Description="Retrieves bookstore information from the Pubs database")]

Sikkim Manipal University

Page No. 276

DOT Net Technologies


class LocatorService { [WebMethod (Description="Finds bookstores in a specified state")] public Bookstore[] FindStores (string state) { return FindByState (state); } Bookstore[] FindByState (string state) { SqlDataAdapter adapter = new SqlDataAdapter ("select * from stores where state = \'" + state + "\'", "server=localhost;database=pubs;uid=sa;pwd="); DataSet ds = new DataSet (); adapter.Fill (ds); DataTable table = ds.Tables[0]; Bookstore[] stores = new Bookstore[table.Rows.Count]; for (int i=0; i<table.Rows.Count; i++) { stores[i] = new Bookstore ( table.Rows[i]["stor_name"].ToString ().TrimEnd (new char[] { ' ' }), table.Rows[i]["stor_address"].ToString ().TrimEnd (new char[] { ' ' }), table.Rows[i]["city"].ToString ().TrimEnd (new char[] { ' ' }), table.Rows[i]["state"].ToString ().TrimEnd (new char[] { ' ' }) ); } return stores; }} public class Bookstore { public string Name; public string Address; public string City; public string State; public Bookstore () {} public Bookstore (string name, string address, string city, string state) { Name = name; Address = address; City = city; State = state; }}

Unit 8

Figure 8.11: Bookstore locator Web service Sikkim Manipal University Page No. 277

DOT Net Technologies

Unit 8

Figure 8.12: XML returned by the FindStores method

Where might a client obtain an XML schema describing the Bookstore data type? From the services WSDL contract, of course. Sneak a peek at Locator.asmxs WSDL contract and youll see the Bookstore data type (and arrays of Bookstores) defined this way in the contracts types element:
<s:complexType name="ArrayOfBookstore"> <s:sequence> <s:element minOccurs="0" maxOccurs="unbounded" name="Bookstore" nillable="true" type="s0:Bookstore" /> </s:sequence> </s:complexType> <s:complexType name="Bookstore"> <s:sequence> <s:element minOccurs="1" maxOccurs="1" name="Name" nillable="true" type="s:string" /> <s:element minOccurs="1" maxOccurs="1" name="Address" nillable="true" type="s:string" /> <s:element minOccurs="1" maxOccurs="1" name="City" nillable="true" type="s:string" /> <s:element minOccurs="1" maxOccurs="1" name="State" nillable="true" type="s:string" /> </s:sequence> </s:complexType>

Sikkim Manipal University

Page No. 278

DOT Net Technologies

Unit 8

Given these definitions, a client can define a Bookstore class of its own and initialize arrays of Bookstore objects by deserializing Bookstore elements. Its not as hard as it sounds. If the client is written with the .NET Framework, tools generate the class definitions for you and the framework handles the deserialization. As Locator.asmx demonstrates, its not difficult to write Web methods that use custom types. There are, however, two gotchas to be aware of:

Because query strings are limited to passing simple name/value pairs, you cant pass complex types to a Web method using HTTP GET and POST. Thats not a limitation if you use SOAP to invoke Web methods, but it does prevent ASP.NET from generating test pages for methods that accept complex types. If you go to a test page and see the warning No test form is available because this method does not support HTTP GET or something to that effect, youve found a method that accepts an input parameter that cant be represented in a query string. ASP.NET test forms invoke methods using HTTP GET commands.

Any fields or properties declared in a class or struct thats passed to or from a Web method must be public if theyre to be serialized when instances of the class or struct are serialized. Thats because the .NET Frameworks XML serializer will not serialize nonpublic members. Keep these caveats in mind and youll have few problems combining Web methods and custom data types.

8.7 Web Service Discovery DISCO


Once a client has a WSDL contract describing a Web service, it has all the information it needs to make calls to that Web service. But when you publish a Web service by making it available on a Web server, how do clients find out where to get a WSDL contract? For that matter, how do clients know that your Web service exists in the first place?
Sikkim Manipal University Page No. 279

DOT Net Technologies

Unit 8

The answer comes in two parts: DISCO and Universal Description, Discovery, and Integration, better known as UDDI. The former is a filebased mechanism for local Web service discovery that is, for getting a list of available Web services from DISCO files deployed on Web servers. The latter is a global Web service directory that is itself implemented as a Web service. UDDI is discussed in the next section. The DISCO (short for discovery) protocol is a simple one that revolves around XML-based DISCO files. The basic idea is that you publish a DISCO file on your Web server that describes the Web services available on it and perhaps on other servers as well. Clients can interrogate the DISCO file to find out what Web services are available and where the services WSDL contracts can be found. As an example, suppose you publish two Web services and their URLs are as follows:

http://www.wintellect.com/calc.asmx http://www.wintellect.com/locator.asmx

To advertise these Web services, you can deploy the following DISCO file at a well-known URL on your server. The contractRef elements identify the URLs of the Web services WSDL contracts. URLs can be absolute or relative (relative to the directory in which the DISCO file resides). The optional docRef attributes identify the locations of documents describing the Web services, which, because of the self-documenting nature of Web services built with the .NET Framework, are typically the ASMX files themselves:
<?xml version="1.0" ?> <discovery xmlns="http://schemas.xmlsoap.org/disco/" xmlns:scl="http://schemas.xmlsoap.org/disco/scl/"> <scl:contractRef ref="http://www.wintellect.com/calc.asmx?wsdl" docRef="http://www.wintellect.com/Calc.asmx" /> <scl:contractRef ref="http://www.wintellect.com/locator.asmx?wsdl" docRef="http://www.wintellect.com/Locator.asmx" /> </discovery>

Sikkim Manipal University

Page No. 280

DOT Net Technologies

Unit 8

If youd prefer, you can write DISCO files for individual Web services and reference them in a master DISCO file using discoveryRef elements. Heres a DISCO file that points to other DISCO files. Once more, URLs can be absolute or relative:
<?xml version="1.0" ?> <discovery xmlns="http://schemas.xmlsoap.org/disco/"> <discoveryRef ref="http://www.wintellect.com/calc.disco" /> <discoveryRef ref="http://www.wintellect.com/locator.disco" /> </discovery>

A third option is to deploy a VSDISCO file to enable dynamic discovery. The following VSDISCO file automatically exposes all ASMX and DISCO files in a host directory and its subdirectories, with the exception of those subdirectories noted with exclude elements:
<?xml version="1.0" ?> <dynamicDiscovery xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17"> <exclude path="_vti_cnf" /> <exclude path="_vti_pvt" /> <exclude path="_vti_log" /> <exclude path="_vti_script" /> <exclude path="_vti_txt" /> </dynamicDiscovery>

How does dynamic discovery work? ASP.NET maps the file name extension .vsdisco to an HTTP handler that scans the host directory and subdirectories for ASMX and DISCO files and returns a dynamically generated DISCO document. A client that requests a VSDISCO file gets back what appears to be a static DISCO document. For security reasons, Microsoft disabled dynamic discovery just before version 1.0 of the .NET Framework shipped. You can re-enable it by uncommenting the line in the httpHandlers section of Machine.config that maps *.vsdisco to System.Web.Services.Discovery.DiscoveryRequestHandler and
Sikkim Manipal University Page No. 281

DOT Net Technologies

Unit 8

granting the ASPNET account permission to access the IIS metabase. Microsoft highly discourages dynamic discovery for fear of compromising your Web server, and a bug in version 1.0 of the .NET Framework SDK prevents most DISCO-aware tools from working with VSDISCO anyway. My advice is to forget that VSDISCO files even exist and use static DISCO files instead. To further simplify Web service discovery, you can link to a master DISCO file from your sites default HTML document. For example, suppose the default HTML document at www.wintellect.com is Default.html and that the same directory also holds a discovery document named Default.disco. Including the following HTML in Default.html enables most tools that read DISCO files to accept the URL www.wintellect.com (as opposed to www.wintellect.com/default.disco): <html> <head> <link type="text/html" rel="alternate" href="Default.disco"> </head> </html>

Visual Studio .NET (specifically, its Add Web Reference command) reads DISCO files; so does the Disco.exe utility that comes with the .NET Framework SDK. Discos chief disadvantage is that you cant read a DISCO file if you dont have its URL. So how do you find a Web service if you dont even have a URL to start with? Can you spell U-D-D-I?

8.8 Web Service Discovery UDDI


UDDI is an abbreviation for Universal Description, Discovery, and Integration. Jointly developed by IBM, Microsoft, and Ariba and supported
Sikkim Manipal University Page No. 282

DOT Net Technologies

Unit 8

by hundreds of other companies, UDDI is a specification for building distributed databases that enable interested parties to discover each others Web services. No one company owns the databases; anyone is free to publish a UDDI-based business registry. Operator sites have already been established by IBM and Microsoft and are likely to be the first of many such sites that will come on line in the future. UDDI sites are themselves Web services. They publish a pair of SOAPbased APIs: an inquiry API for inquiring about companies and their Web services and a publisher API for advertising a companys Web services. Anyone can call the inquiry API, but operator sites typically limit the publisher API to registered members. At the time of this writing, Microsoft was beta testing a UDDI .NET SDK featuring managed wrapper classes that simplify interactions with UDDI business registries. Most developers will never deal with UDDI APIs directly. Instead, theyll use high-level tools such as Visual Studio .NET to query UDDI business registries and generate wrapper classes that allow them to place calls to the Web services that they find there. The actual placing of UDDI calls will be limited primarily to tools vendors and to clients that wish to locate and bind to Web services dynamically.

8.9 Web Service Clients


Now that youve seen Web services up close and personal, its time to learn about Web service clients that is, applications that use, or consume, Web methods. Its easy to write Web services. Writing Web service clients is even easier, thanks to some high-level support lent by the .NET Framework class library (FCL) and a code-generator named Wsdl.exe. If you have a WSDL contract describing a Web service (or the URL of a DISCO file that

Sikkim Manipal University

Page No. 283

DOT Net Technologies

Unit 8

points to a WSDL contract), you can be making calls to that Web service in no time.

8.10 Web Service Proxies


The key concept to grasp when writing Web service clients is that of the Web service proxy. A Web service proxy is an object that provides a local representation of a remote Web service. A proxy is instantiated in the clients own application domain, but calls to the proxy flow through the proxy and out to the Web service that the proxy represents. The Wsdl.exe utility that comes with the .NET Framework SDK (and that is integrated into Visual Studio .NET) generates Web service proxy classes from WSDL contracts. Once a proxy is created, calling the corresponding Web service is a simple matter of calling methods on the proxy, as shown here: CalculatorWebService calc = new CalculatorWebService (); int sum = calc.Add (2, 2); The methods in the proxy class mirror the Web methods in the Web service. If the Web service exposes Web methods named Add and Subtract, the Web service proxy also contains methods named Add and Subtract. When you call one of these methods, the proxy packages up the input parameters and invokes the Web method using the protocol encapsulated in the proxy (typically SOAP). The proxy insulates you from the low-level details of the Web service and of the protocols that it uses. It even parses the XML that comes back and makes the result available as managed types. Using Wsdl.exe to generate a Web service proxy is simplicity itself. Suppose you want to call a Web service whose URL is

http://www.wintellect.com/calc.asmx. If the Web service was written with the .NET Framework, which means you can retrieve a WSDL contract by appending a ?wsdl query string to the service URL, you can generate a proxy for the Web service like this:
Sikkim Manipal University Page No. 284

DOT Net Technologies

Unit 8

wsdl http://www.wintellect.com/calc.asmx?wsdl Or you can leave off the query string and let Wsdl.exe supply it for you: wsdl http://www.wintellect.com/calc.asmx If Calc.asmx wasnt written with the .NET Framework, it might not support WSDL query strings. In that case, you find the WSDL contract and pass its URL (or local path name) to Wsdl.exe. The following example assumes that the contract is stored in a local file named Calc.wsdl: wsdl calc.wsdl However you point it to the WSDL contract, Wsdl.exe generates a CS file containing a class that represents the Web service proxy. Thats the class you instantiate to invoke the Web services methods. The proxy classs name comes from the service name (that is, the name attribute accompanying the service element) in the WSDL contract. For example, suppose you attribute a Web service as follows in its ASMX file: [WebService (Name="Calculator Web Service")] The resulting <service> tag in the WSDL contract looks like this: <service name="Calculator Web Service"> and the resulting proxy class is named CalculatorWebService. By default, the name of the CS file that Wsdl.exe generates also derives from the service name (for example, Calculator Web Service.cs). You can override that name by passing Wsdl.exe a /out switch. The command wsdl /out:Calc.cs http://www.wintellect.com/calc.asmx names the output file Calc.cs regardless of the service name. Wsdl.exe supports a number of command line switches that you can use to customize its output. For example, if youd prefer the proxy class to be written in Visual Basic .NET rather than C#, use the /language switch: wsdl /language:vb http://www.wintellect.com/calc.asmx

Sikkim Manipal University

Page No. 285

DOT Net Technologies

Unit 8

If youd like Wsdl.exe to enclose the code that it generates in a namespace (which is extremely useful for preventing collisions between types defined in the generated code and types defined in your application and in the FCL), use the /namespace switch: wsdl /namespace:Calc http://www.wintellect.com/calc.asmx Classes generated by Wsdl.exe derive from base classes in the FCLs System.Web.Services.Protocols namespace. By default, a proxy class derives from SoapHttpClientProtocol, which enables it to invoke Web methods using SOAP over HTTP. You can change the invocation protocol with Wsdl.exes /protocol switch. The command wsdl /protocol:httpget http://www.wintellect.com/calc.asmx creates a Web service proxy that derives from HttpGetClientProtocol and calls Web methods using HTTP GET commands, while the command wsdl /protocol:httppost http://www.wintellect.com/calc.asmx creates a proxy that derives from HttpPostClientProtocol and uses HTTP POST. Why would you want to change the protocol that a proxy uses to invoke Web methods? In the vast majority of cases, SOAP is fine. However, if the methods that youre calling are simple methods that use equally simple data types, switching to HTTP GET or POST makes calls slightly more efficient by reducing the amount of data transmitted over the wire. Incidentally, if you use Visual Studio .NET to write Web service clients, you dont have to run Wsdl.exe manually. When you use the Add Web Reference command found in the Project menu, Visual Studio .NET runs Wsdl.exe for you and adds the proxy class to your project. Add Web Reference also speaks the language of UDDI, making it easy to search Microsofts UDDI registry for interesting Web services.

Sikkim Manipal University

Page No. 286

DOT Net Technologies

Unit 8

8.11 A Simple Web Service Client


Want to write a client for Calc.asmx? Here are the steps: 1. Use Wsdl.exe to create a proxy class for Calc.asmx. If you installed Calc.asmx in wwwroot, the proper command is wsdl http://localhost/calc.asmx Wsdl.exe responds by creating a file named Calculator Web Service.cs. 2. Create a new text file named CalcClient.cs and enter the code in Figure 11-9. 3. Compile the CS files into a console application with the following command: csc CalcClient.cs "Calculator Web Service.cs" 4. Run CalcClient.exe. CalcClient.exe instantiates a Web service proxy and calls the services Add method. The resulting output proves beyond the shadow of a doubt that Calc.asmx is smart enough to add 2 and 2 (Figure 8.13). CalcClient.cs using System; class MyApp { public static void Main () { CalculatorWebService calc = new CalculatorWebService (); int sum = calc.Add (2, 2); Console.WriteLine ("2 + 2 = " + sum); } }

Sikkim Manipal University

Page No. 287

DOT Net Technologies

Unit 8

Figure 8.13: Console client for Calc.asmx

Avoiding Hard-Coded Service URLs Look through a CS file generated by Wsdl.exe, and youll see the Web service proxy class as well as the methods that wrap the Web services Web methods. Youll also see that the Web services URL is hardcoded into the CS file in the proxys class constructor. Heres an example: public CalculatorWebService() { this.Url = "http://www.wintellect.com/calc.asmx"; } If the Web service moves, youll have to modify the CS file and regenerate the proxy. To avoid having to update code when a Web services URL changes, you can use Wsdl.exes /appsettingurlkey (abbreviated /urlkey) switch. The command wsdl /urlkey:CalcUrl http://www.wintellect.com/calc.asmx following class constructor: produces the

Sikkim Manipal University

Page No. 288

DOT Net Technologies

Unit 8

public CalculatorWebService() { string urlSetting = System.Configuration.ConfigurationSettings.AppSettings["CalcUrl"]; if ((urlSetting != null)) { this.Url = urlSetting; } else { this.Url = "http://www.wintellect.com/calc.asmx"; } }

Now you can assign a value to CalcUrl in the appSettings section of a local Web.config file, like so: <configuration> <appSettings> <add key="CalcUrl" value="http://www.wintellect.com/calc.asmx" /> </appSettings> </configuration>

If the URL changes, you can update the proxy simply by editing Web.config. No code changes are required. Asynchronous Method Calls Something else youll notice if you open a CS file generated by Wsdl.exe is that the proxy class contains asynchronous as well as synchronous wrappers around the Web services methods. The former can be used to invoke Web methods asynchronously. An asynchronous call returns immediately, no matter how long the Web service requires to process the call. To retrieve the results from an asynchronous call, you make a separate call later on.

Sikkim Manipal University

Page No. 289

DOT Net Technologies

Unit 8

Heres an example using Calc.asmxs Add method that demonstrates how to invoke a Web method asynchronously. The client calls the proxys BeginAdd method to initiate an asynchronous call and then goes off to attend to other business. Later it returns to finish the call by calling EndAdd: CalculatorWebService calc = new CalculatorWebService (); IAsyncResult res = calc.BeginAdd (2, 2, null, null); . . . int sum = calc.EndAdd (res); If the call hasnt completed when EndAdd is called, EndAdd blocks until it does. If desired, a client can use the IsCompleted property of the IAsyncResult interface returned by BeginAdd to determine whether the call has completed and avoid calling EndAdd prematurely: IAsyncResult res = calc.BeginAdd (2, 2, null, null); . . . if (res.IsCompleted) { int sum = calc.EndAdd (res); } else { // Try again later } Another option is to ask to be notified when an asynchronous call returns by providing a reference to an AsyncCallback delegate wrapping a callback method. In the next example, EndAdd wont block because it isnt called until the client is certain the method call has returned: AsyncCallback cb = new AsyncCallback (AddCompleted);
Sikkim Manipal University Page No. 290

DOT Net Technologies

Unit 8

IAsyncResult res = calc.BeginAdd (2, 2, cb, null); . . . public void AddCompleted (IAsyncResult res) { int sum = calc.EndAdd (res); } Whatever approach you decide on, the proxys asynchronous methodcall support is extraordinarily useful for calling methods that take a long time to complete. Add isnt a very realistic example because its such a simple method, but the principle is valid nonetheless. Web Service Clients and Proxy Servers If a client invokes methods on a Web service from behind a proxy server, the Web service proxy needs to know the address of the proxy server. You can provide that address in two ways. The first option is to pass Wsdl.exe a /proxy switch specifying the proxy servers URL: wsdl /proxy:http://myproxy http://www.wintellect.com/calc.asmx Option number two is to programmatically initialize the Web service proxys Proxy property (which it inherits from HttpWebClientProtocol) with a reference to a WebProxy object (System.Net.WebProxy) identifying the proxy server: CalculatorWebService calc = new CalculatorWebService (); calc.Proxy = new WebProxy (http://myproxy, true); int sum = calc.Add (2, 2);

Sikkim Manipal University

Page No. 291

DOT Net Technologies

Unit 8

The true passed to WebProxys constructor bypasses the proxy server for local addresses. Pass false instead to route all requests through the proxy server.

8.12 A Brief Overview of Web Service Standards


InfoPath supports XML, HTTP, SOAP, WSDL, and UDDI Web Service standards. What do these abbreviations and acronyms stand for? XML is Extensible Markup Language, a standard for describing structured data used by InfoPath and many other tools. HTTP is HyperText Transfer Protocol, which is used to retrieve data from and send data to a Web server. It is the network protocol that InfoPath supports for connecting to Web Services. It is also used to load and save templates and forms. SOAP is Simple Object Access Protocol, an XML-based protocol for sending and receiving data to and from a Web Service. InfoPath communicates with Web Services using SOAP. SOAP messages are well-formed XML documents. InfoPath sends the SOAP message to the Web Service using HTTP. WSDL is Web Services Description Language, an XML format that describes the interface to Web Services, including the data formats. InfoPath uses WSDL when creating forms and data sources based on a Web Service. UDDI is Universal Description, Discovery, and Integration, a standard interface to directories of Web Services. InfoPath can connect to a UDDI server to discover available Web Services.

8.13 Summary
The Web services are the key to Microsofts vision of a world in which computers talk to each other over the Web using HTTP and other
Sikkim Manipal University Page No. 292

DOT Net Technologies

Unit 8

universally supported protocols. And theyre the number one reason that the Microsoft .NET Framework exists in the first placeto make it as easy as humanly possible to build Web services and Web service clients. This unit starts with the definition of a web service. It explains different components of web services and the architecture of web services. It demonstrates an example of developing a simple web service. It demonstrates the ways of testing a web service. It introduces the Web Services Description language (WSDL). It gives two examples of Web services like DISCO and UDDI. It describes the concepts of Web Service Clients and Web Proxies. It demonstrates a simple example of a Web service client. It discusses in brief the standards of Web Services. Self Assessment Questions 1. The concept of __________ is the key to Microsofts vision of a world

in which computers talk to each other over the Web using HTTP and other universally supported protocols. 2. Web services are an industry standard built on open protocols such as HTTP and _____________. 3. The ______ and Service Listener components may either be standalone applications (a TCP-server or HTTP-server daemon, for instance) or may run within the context of some other type of application server. 4. ______ refers to a service consumer actually using the service offered by a service provider. 5. The ______ is an XML-based vocabulary for performing remote procedure calls using HTTP and other protocols. 6. The forms that ASP.NET generates on the fly from X files enable you to test the Web services that you write without writing special clients to test them with.

Sikkim Manipal University

Page No. 293

DOT Net Technologies

Unit 8

7. We can use ______ to move Web service classes out of ASMX files and into separately compiled DLLs.

8.14 Terminal Questions


1. Give an example of a Web Service Application (Refer to 8.1 & 8.2) 2. Write about the following example Web services: (Refer to 8.7 & 8.8) Web Service Discovery - DISCO Web Service Discovery UDDI

3. Write about the following: (Refer to 8.9 & 8.10) Web Service Clients Web Service Proxies

8.15 Answers to Self Assessment Questions


1. Web Services 2. Simple Object Access Protocol (SOAP) 3. Service Proxy 4. Binding 5. SOAP 6. ASMX 7. code-behind

Sikkim Manipal University

Page No. 294

DOT Net Technologies

Unit 9

Unit 9
Structure: 9.1 9.2 9.3 9.3 9.4 9.5 9.6 9.7 Internet Information Services (IIS) Objectives IIS 6.0 Architecture (IIS 6.0) Creating Application Pools (IIS 6.0) Managing Application Pools in IIS 6.0

Website Deployment

Deploying Your ASP.NET Applications Summary Self Assessment Questions Terminal Questions Answers to Self Assessment Questions

9.1 Internet Information Services (IIS)


The Internet Information Services technology (IIS) component is a macro component that bundles the IIS components that are found in the Software\System\Networking & Communications\Infrastructure directory in the component browser. By using this component, you can quickly add IIS support to your device. By default, this macro component will add only the IIS Web Server component to your configuration. To include other components, enable them in the Settings page for this macro component. Services: There are no services associated with this component. Associated Components: No other components interact with this component. Settings: This component can be configured by using Target Designer to include or exclude optional components from the bundle. Because this component includes a number of applications, its footprint is sizeable. To reduce the footprint of your run-time image, in Target Designer on the
Sikkim Manipal University Page No. 295

DOT Net Technologies

Unit 9

Components tab, clear the check boxes for all components that are not required in your configuration. IIS 6.0 Operations Guide (IIS 6.0) Internet Information Services (IIS) 6.0 with the Microsoft Windows Server 2003 operating system provides integrated, reliable, scalable, secure, and manageable Web server capabilities over an intranet, the Internet, or an extranet. IIS is a tool for creating a strong communications platform of dynamic network applications. Organizations of all sizes use IIS to host and manage Web pages on the Internet or on their intranet, to host and manage FTP sites, and to route news or mail using the Network News Transfer Protocol (NNTP) and the Simple Mail Transfer Protocol (SMTP). IIS 6.0 leverages the latest Web standards like Microsoft ASP.NET, XML, and Simple Object Access Protocol (SOAP) for the development, implementation, and management of Web applications. IIS 6.0 includes new features designed to help organizations, IT professionals, and server administrators achieve their goals of performance, reliability, scalability, and security for potentially thousands of Web sites either on a single IIS server or on multiple servers. Features of IIS 6.0: The following table lists all the features of IIS 6.0.
IIS 6.0 Feature Reliability Description IIS 6.0 uses a new request-processing architecture and application isolation environment that enables individual Web applications to function within a self-contained worker process. This environment prevents one application or Web site from stopping another, and reduces the amount of time administrators spend restarting services to correct problems related to applications. The new environment also includes proactive Application Pool Health. IIS 6.0 introduces a new kernel-mode driver for HTTP parsing and caching, specifically tuned to increase Web server throughput and scalability of multiprocessor computers, thereby significantly increasing the following: The number of sites a single IIS 6.0 server can host The number of concurrently-active worker processes Also, by Configuring Startup and Shutdown Time Limits, Sikkim Manipal University Page No. 296

Scalability

DOT Net Technologies

Unit 9

IIS allocates resources to active sites, as opposed to wasting resources on idle requests. Security IIS 6.0 provides significantly improved security over earlier versions of IIS. To reduce the attack surface of systems, IIS is not installed by default on the operating systems in the Windows Server 2003 family. Administrators must explicitly select and install IIS. IIS installs by default in a locked-down state, capable of serving only static content. Using the Web Service Extensions node, Web site administrators can Configuring IIS For Dynamic Content IIS functionality based on the individual needs of their organization. IIS 6.0 includes a variety of Security in IIS 6.0 features and technologies to help ensure the integrity of your Web and FTP site content, as well as the data transmitted through your sites. IIS security features include the following security-related tasks: Authentication in IIS 6.0 Manageability Access Control with IIS 6.0 IIS 6.0 Encryption Certificates Auditing in IIS 6.0

To meet the needs of a diverse set of organizations, IIS provides a variety of manageability and administration tools. Administrators can configure an IIS 6.0 server using IIS Manager, Using Command-Line Administration Scripts, or by directly Enabling Edit-While-Running in IIS 6.0. Administrators can also Administering Servers Remotely in IIS 6.0 IIS servers and sites. Compared to earlier operating systems, the Windows Server 2003 family offers an improved developer experience with About ASP.NET and IIS integration. ASP.NET recognizes most ASP code while providing greater functionality for building enterprise-class Web applications that can work as a part of the Microsoft .NET Framework. Using ASP.NET allows you to take full advantage of the features of the common language runtime, such as type safety, inheritance, language interoperability, and versioning. IIS 6.0 also offers support for the latest Web standards, including XML, SOAP, and Internet Protocol Version 6 Features. IIS 6.0 is compatible with most existing applications, based on feedback from thousands of customers and independent software vendors (ISVs). Also, to ensure maximum compatibility, IIS 6.0 can be configured to run in IIS 5.0 Isolation Mode in IIS 6.0.

Enhanced Development

Application Compatibility

Sikkim Manipal University

Page No. 297

DOT Net Technologies

Unit 9

Web Application Technologies (IIS 6.0) The Windows Server 2003 family offers an improved developer experience with ASP.NET and IIS integration. Microsoft ASP.NET recognizes most ASP code while providing greater functionality for building enterprise-class Web applications that can work as a part of the Microsoft .NET Framework. Using ASP.NET allows you to take full advantage of the features of the common language runtime, such as type safety, inheritance, language interoperability, and versioning. IIS 6.0 also offers support for the latest Web standards, including XML, Simple Object Access Protocol (SOAP) and Internet Protocol Version 6 (IPv6.0). Web Distributed Authoring and Versioning Web Distributed Authoring and Versioning (WebDAV) enables remote authors to create, move, or delete files, file properties, directories, and directory properties on your server over an HTTP connection. News and Mail You can use News Network Transport Protocol (NNTP) and Simple Mail Transfer Protocol (SMTP) services to set up intranet news and mail services that work in conjunction with IIS. HTTP Compression HTTP Compression provides faster transmission of pages between the Web server and compression-enabled clients. It compresses and caches static files, and performs on-demand compression of dynamically generated files. Internet Protocol Version 6 Features (IIS 6.0) This version of IIS provides Internet services to clients connecting over the next generation of Internet Protocol (IP) known as IP version 6, or IPv6. IPv6 is included with the Microsoft Windows XP networking platform and the Microsoft Windows Server 2003 family. The Internet Server API (ISAPI) framework provides the appropriate local- and remote-host server variables
Sikkim Manipal University Page No. 298

DOT Net Technologies

Unit 9

for IPv6 network addresses: LOCAL_ADDR and REMOTE_ADDR. When clients connect over IPv6, these variables store the IPv6 address. When writing applications that use the ISAPI server variables for network addressing over IPv6, remember that all buffers allocated for network address storage can be a maximum of 128 bits in size (56 character string), whereas buffers allocated for network address storage over IPv4 are limited to 32 bits (16 character string). After the protocol stack is installed, IIS automatically begins supporting IPv6 on your Web server. Web sites that are already running must be restarted before they begin listening for IPv6 requests. Sites created after IPv6 support is enabled automatically listen for IPv6. Functionality The IIS core functionality has not changed as a result of IPv6 support; however, only a subset of all IIS 6.0 functionality is available for IPv6. IIS Manager does not display IPv6 addresses as it does for IPv4 addresses. Bandwidth Throttling is not supported for IPv6 Web sites. The ServerBindings metabase property does not support storing IPv6 literal addresses (as defined in RFC 2732). This behavior limits IIS to support host-header routing only. The IP Address Restrictions feature in IIS does not support IPv6 addresses or IPv6 prefixes. The EnableReverseDnsLookup metabase property is not supported. Setting this property to true does not cause the REMOTE_HOST server variable to return the DNS name of the client, as it does for IPv4. REMOTE_HOST will always contain the IPv6 address regardless of the EnableReverseDNSLookup setting.

Sikkim Manipal University

Page No. 299

DOT Net Technologies

Unit 9

Site routing based on IP addresses is not supported for IPv6. Server address with sites that are configured to route based on IPv4 addresses will not respond to IPv6 requests.

IPv6 is enabled for all sites. You cannot configure IPv6 support at the machine level. In other words, you cannot configure individual sites to respond to IPv6 traffic while other sites on the same server respond to IPv4 traffic. It is possible, however, to limit IPv6 traffic to a specific site if that site is configured to use IP-based routing on an IPv4 address.

Logging. IIS writes IPv6 addresses to the log file when IPv6 is enabled and client computers connect to the server using IPv6 addresses. Log parsing tools must support IPv6 address formats if they are to be used with log files for IPv6 sites.

SSL. Due to the IP routing restriction for IPv6, IIS deployments designed for IPv6 addresses are limited to one Secure Sockets Layer (SSL) site per computer.

Objectives This unit describes the Microsoft Internet Information Service (IIS 6.0) and its usage as a Web server in Web Application deployment. At the end of this unit the reader would be able to: 1. Define and Describe the IIS and its features 2. Describe the architecture of IIS 6.0 3. Explain the mechanism of creating application pools in IIS 4. Discuss how to manage application pools in IIS 6.0 5. Demonstrate how to deploy ASP.NET applications using IIS 6.0

9.2 IIS 6.0 Architecture (IIS 6.0)


Internet Information Services (IIS) version 6.0, which runs on all editions of the Microsoft Windows Server 2003 operating system, provides a new architecture that offers flexibility in the choice of two application isolation modes. The new architecture helps you run a faster Web service that is more reliable and secure. IIS 6.0 provides a redesigned World Wide Web
Sikkim Manipal University Page No. 300

DOT Net Technologies

Unit 9

Publishing Service (WWW service) architecture that can help you achieve better performance, reliability, scalability, and security for your Web sites, whether they run on a single server running IIS or on multiple servers. IIS 6.0 runs a server in one of the two distinct request processing models, called Application Isolation Modes. Application Isolation is the separation of applications by process boundaries that prevents one application or Web site from affecting another and reduces the time that you spend restarting services to correct problems related to applications. In IIS 6.0, application isolation is configured differently for each of the two IIS application isolation modes. Both modes rely on the HTTP protocol stack (also referred to as HTTP.sys) to receive Hypertext Transfer Protocol (HTTP) requests from the Internet and return responses. HTTP.sys resides in kernel mode, where operating system code, such as device drivers, runs. HTTP.sys listens for, and queues, HTTP requests. The new request-processing architecture and application isolation

environment enables individual Web applications, which always run in user mode, to function within a self-contained worker process. A worker process is user-mode code whose role is to process requests, such as returning a static page or invoking an Internet Server API (ISAPI) extension or filter. Worker processes use HTTP.sys to receive requests and send responses over HTTP. IIS 6.0 Request Processing Models Worker process isolation mode is the new IIS request processing model. In this application isolation mode, you can group Web applications into application pools, through which you can apply configuration settings to the worker processes that service those applications. An application pool corresponds to one request routing queue within HTTP.sys and one or more worker processes. Worker process isolation mode enables you to completely separate an application in its own process, with no dependence on a central process
Sikkim Manipal University Page No. 301

DOT Net Technologies

Unit 9

such as Inetinfo.exe to load and execute the application. All requests are handled by worker processes that are isolated from the Web server itself. Process boundaries separate each application pool so that when an application is routed to one application pool, applications in other application pools do not affect that application. By using application pools, you can run all application code in an isolated environment without incurring a performance penalty. For a visual representation of worker process isolation mode architecture, see Figure 9.1.

Figure 9.1: Architecture of Worker Process Isolation Mode

Worker process isolation mode delivers all the benefits of the new IIS 6.0 architecture, including multiple application pools, health monitoring and recycling, increased security and performance, improved scalability, and processor affinity. For example, the new health monitoring features can help you discover and prevent application failures, and can also help protect your Web server from imperfect applications.
Sikkim Manipal University Page No. 302

DOT Net Technologies

Unit 9

IIS 6.0 Services IIS 6.0 provides the following four Internet services: The World Wide Web Publishing Service (WWW service) for hosting Internet and intranet content; The File Transfer Protocol (FTP) service for hosting sites where users can upload and download files; The Network News Transfer Protocol (NNTP) service for hosting discussion groups; and The Simple Mail Transfer Protocol (SMTP) service for sending and receiving e-mail messages. After installing these services, you can create sites or virtual servers, configure properties and security settings, and set up components to further customize your system. WWW Service Administration and Monitoring, which is a new set of features that were added to the WWW service in IIS 6.0, manages worker processes, supports the new request processing model, and is responsible for health management and maintenance, including application pool health monitoring, recycling worker processes, and rapid-fail protection. IIS Admin service is a service of the Microsoft Windows Server 2003, Standard Edition; Microsoft Windows Server 2003, Enterprise Edition; Microsoft Windows Server 2003, Web Edition; and Microsoft

Windows Server 2003, Datacenter Edition operating systems. The IIS Admin service manages the IIS metabase, which stores IIS configuration data. The IIS Admin service makes metabase data available to applications and the core components of IIS. Internet Information Services (IIS) 6.0, running on Microsoft Windows Server 2003, helps to provide a secure, reliable, and easily managed application server on which you can host sites over an intranet, the Internet,
Sikkim Manipal University Page No. 303

DOT Net Technologies

Unit 9

or an extranet. IIS helps you create a platform of dynamic network applications, allowing you to use the latest Web standards to develop, implement, and manage your Web applications. To match the needs of your applications to your server, IIS offers an adjustable architecture that allows you to isolate applications within a selfcontained worker process. The new process model helps prevent one application or Web site from stopping another and reduces the time that you spend restarting services to maintain the health of your server. If health issues arise, IIS helps you to manage them, usually without restarting your Web server or affecting your users.

9.3 Creating Application Pools (IIS 6.0)


When you run IIS 6.0 in worker process isolation mode, you can isolate different Web applications or Web sites in pools, which are called Application Pools. An application pool is a group of URLs that are routed to one or more worker processes that share the same configuration. The URLs that you assign to an application pool can be for an application, a Web site, a Web directory, or a virtual directory. In an application pool, process boundaries separate each worker process from other worker processes so that when an application is routed to one application pool, applications in other application pools do not affect that application. By using an application pool, you can assign specific configuration settings to a worker process (or, in the case of a Web garden, to a set of worker processes) that services a group of applications. For example, you can configure worker process recycling, which offers several configuration options to match the needs of each application. If, for example, you suspect that an application has a memory leak, you might configure the application pools worker process to recycle when its memory use reaches a certain
Sikkim Manipal University Page No. 304

DOT Net Technologies

Unit 9

threshold. If another application fails because of the volume of requests that it receives, you can set the application pools worker process to recycle when the application exceeds a specified number of requests. By creating new application pools and assigning Web sites and applications to them, you can make your server more efficient, reliable, and secure, and ensure that your applications remain available even when a worker process serving an application pool is recycled because of a faulty application. Configuring Application Pools in IIS 6.0 (IIS 6.0) Note: This feature of IIS 6.0 is available only when running in worker process isolation mode. An application pool is a configuration that links one or more applications to a set of one or more worker processes. Because applications in an application pool are separated from other applications by worker process boundaries, an application in one application pool is not affected by problems caused by applications in other application pools. By creating new application pools and assigning Web sites and applications to them, you can make your server more efficient and reliable, as well as making your other applications always available, even when the worker process serving the new application pool has problems. Guidelines for Creating Application Pools To isolate Web applications on a Web site from Web applications on other sites running on the same computer, create an individual application pool for each Web site. For enhanced security, configure a unique user account (process identity) for each application pool. Use an account with the least user rights possible, such as Network Service in the IIS_WPG group. If there is a test version of an application on the same server with the production version of the application, separate the two versions into
Sikkim Manipal University Page No. 305

DOT Net Technologies

Unit 9

different application pools. This isolates the test version of the application. As a design consideration, if you want to configure an application to run with its own unique set of properties, create a unique application pool for that application. Note: You must be a member of the Administrators group on the local computer to perform the following procedure or procedures. As a security best practice, log on to your computer by using an account that is not in the Administrators group, and then use the runas command to run IIS Manager as an administrator. At a command prompt, type runas /user:Administrative_AccountName "mmc %systemroot%\system32\inetsrv\iis.msc". Steps to create a new Application Pool: 1. In IIS Manager, expand the local computer, right-click Application Pools, point to New, and then click Application Pool. 2. In the Application pool name box, type the name of the new application pool. 3. If the ID that appears in Application pool ID box is not the ID that you want, type a new ID. 4. Under Application pool settings, click the appropriate setting. If you click Use existing application pool as template, in Application pool name box, right-click the application pool that you want to use as a template. 5. Click OK. Application pools allow you to apply configuration settings to groups of applications and the worker processes that service those applications. Any Web site, Web directory, or virtual directory can be assigned to an application pool.
Sikkim Manipal University Page No. 306

DOT Net Technologies

Unit 9

Assigning an application to an application pool: In IIS Manager, right-click the application that you want to assign to an application pool, and then click Properties. Click the Virtual Directory, Directory, or Home Directory tab. If you are assigning a directory or virtual directory, verify that Application name is filled in. If the Applicationname box is not filled in, click Create, and then type a name. In the Application pool list box, click the name of the application pool to which you want to assign the Web site. About Configuring Servers for Applications (IIS 6.0) Internet Information Services (IIS) 6.0 delivers Web hosting services through an adjustable architecture that you can use to manage server resources with improved stability, efficiency, and performance. IIS separates applications into isolated pools and automatically detects memory leaks, defective processes, and over-utilized resources. When problems occur, IIS manages them by shutting down and redeploying faulty resources and connecting faulty processes to analytical tools. IIS can run in either of two mutually exclusive modes of operation: Worker process isolation mode. This is the default mode of IIS 6.0, isolates key components of the World Wide Web Publishing Service (WWW service) from the effects of errant applications, and it protects applications from each other by using the worker process component. Use worker process isolation mode unless you have a specific compatibility issue that makes the use of IIS 5.0 isolation mode necessary. Web sites that serve static content or simple ASP applications should be able to move to IIS 6.0 running in worker process isolation mode with little or no modification.

Sikkim Manipal University

Page No. 307

DOT Net Technologies

Unit 9

IIS 5.0 isolation mode. With this mode, you can run applications that are incompatible with worker process isolation mode because they were developed for earlier versions of IIS. Applications that run correctly on IIS 5.0 should run correctly on IIS 6.0 in IIS 5.0 isolation mode.

Worker process isolation mode provides better default security for running Web applications than IIS 5.0 isolation mode. By default, worker processes run with the Network Service identity. The Network Service account has lower access rights than the default account for IIS 5.0 isolation mode. Web applications that run in-process in IIS 5.0 application mode run as LocalSystem. The LocalSystem account can read, execute, and change most of the resources on the computer. The default isolation mode upon installing IIS 6.0 depends on whether you perform a clean installation or an upgrade. After a clean install of IIS 6.0, IIS runs in worker process isolation mode. After an upgrade from an earlier version of IIS 6.0, the isolation mode is the same as configured on the previously-installed version of IIS 6.0. After an upgrade from IIS 5.0 or IIS 4.0, IIS 6.0 runs in IIS 5.0 isolation mode by default to maintain compatibility with your existing applications. Worker Process Isolation Mode IIS 6.0 introduces worker process isolation mode, which runs all Web applications in an isolated environment. When you run IIS in worker process isolation mode, applications can be configured to run in separate application pools. Each application pool is a logical representation of a configurable worker process and links to the applications in the pool. Worker processes operate independently of each other; they can fail without affecting other worker processes. The pooling of applications protects applications from the effects of worker processes that support other application pools. In this way, applications are protected from each other.
Sikkim Manipal University Page No. 308

DOT Net Technologies

Unit 9

In worker process isolation mode, Hypertext Transfer Protocol (HTTP) requests are routed directly to an in-kernel application pool queue serving the configured application. Worker processes that serve an application pool pull the requests directly from the queue, avoiding process-switching overhead. To further protect your WWW service, IIS 6.0 isolates critical World Wide Web Publishing Service (WWW service) components, such as the HTTP protocol stack (HTTP.sys) and WWW Service Administration and

Monitoring, from the effects of third-party code running in worker processes. HTTP.sys receives and queues requests for WWW services. When a worker process enters an unhealthy state, and thus stops processing requests, HTTP.sys continues to process requests. Meanwhile, the WWW service detects that the worker process is unhealthy and shuts it down. If there is demand for a new worker process to serve requests (HTTP.sys has requests queued), the WWW service starts a new worker process to pick up the queued requests from HTTP.sys. Even though a worker process has failed, the WWW service continues to process requests and shields the user from experiencing a loss of service. IIS 6.0 worker process isolation mode delivers the following specific improvements over earlier versions of IIS: Robust Performance Isolation prevents Web applications and Web sites from affecting each other or the WWW service. Reboots of the operating system and restarting of the WWW service are avoided. Self - Healing Automated management provides auto-restart of failed worker processes and periodic restart of deteriorating worker processes. Scalability Web gardens allow more than one worker process to serve the same application pool. Process Affinity enables the connection of worker processes to specific processors on multi-CPU servers.
Sikkim Manipal University Page No. 309

DOT Net Technologies

Unit 9

Automated Debugging The debugging feature enables the automatic assignment of failing worker processes to debugging tools.

CPU Limiting This monitoring feature enables controlling the amount of CPU resources that an application pool consumes in a configured amount of time.

9.4 Deploying Your ASP.NET Applications


Deploying ASP.NET Applications in IIS 6.0 (IIS 6.0) Microsoft Windows Server 2003 includes support for ASP.NET

applications and the Microsoft .NET Framework version 1.1 with the operating system installation. This chapter describes how to deploy ASP.NET applications on a newly installed server running Internet Information Services (IIS) 6.0. Version 1.1 of the .NET Framework is installed with Windows Server 2003. Most ASP.NET applications run without modification on version 1.1 of the .NET Framework. Overview of Deployment process using IIS 6.0 ASP.NET is a unified Web application platform that provides services to help you build and deploy enterprise-class Web applications and XMLbased Web services. ASP.NET Windows Server 2003, Enterprise Edition; Standard is supported on the Edition; Microsoft

Windows Server2003, Datacenter Edition; and

Windows Server2003,

Windows Server2003, Web Edition operating systems. ASP.NET is installed with the Microsoft .NET Framework version 1.1 as a part of Windows Server 2003. However, to run ASP.NET applications, you must also install IIS 6.0. ASP.NET is not available on the following the operating 64-bit systems: of

Microsoft Windows XP

64-Bit

Edition;

version

Sikkim Manipal University

Page No. 310

DOT Net Technologies

Unit 9

Windows Server 2003, Enterprise Edition; and the 64-bit version of Windows Server 2003, Datacenter Edition. The deployment process presented in this section describes how to deploy ASP.NET applications on a newly installed IIS 6.0 Web server. Before you begin this process, complete the following steps: Install Windows Server 2003, which includes version 1.1 of the .NET Framework, with the default options. Install IIS 6.0 with the default settings in Add or Remove Programs in Control Panel. When you configure IIS 6.0 to run in IIS 5.0 isolation mode, the settings in the <processModel> section of the Machine.config file are configured in the same way as they were in IIS 5.0 in the Machine.config or Web.config files. Upon completing the process described in this section, you will have a Web server running IIS 6.0 and hosting your ASP.NET applications. However, you can further configure the Web server to improve the security and availability of your ASP.NET applications. Deployment Process using IIS 6.0 The process for deploying new ASP.NET applications on a newly installed Web server requires no understanding of earlier versions of IIS or the .NET Framework. All the ASP.NET configuration sections in the Machine.config and Web.config files are configured the same way in IIS 6.0, except for the <processModel> section of the Machine.config file. When IIS 6.0 is configured to run in worker process isolation mode, some of the attributes in the <processModel> section of the Machine.config file are now in equivalent IIS 6.0 metabase properties. In addition, if your ASP.NET applications need to retain session state, you must configure IIS 6.0 to use the appropriate ASP.NET application session
Sikkim Manipal University Page No. 311

DOT Net Technologies

Unit 9

state method. Depending on the method you select, you might need to configure the ASP.NET state service or Microsoft SQL Server to act as the repository for centralized state storage. The process for deploying ASP.NET applications in IIS 6.0 is shown in Figure 9.2.

Figure 9.2: Deploying ASP.NET Applications in IIS 6.0

Note: Before deploying your ASP.NET applications on a production server, perform the process outlined in this section on a test server that is configured identically to your production server. Deploy the Web Server 1. Install Windows Server 2003. 2. Install and configure IIS 6.0. 3. Enable ASP.NET in the Web service extensions list. Install ASP.NET Applications 1. Create Web sites and virtual directories for each ASP.NET application by doing the following: Create Web sites and home directories. Create virtual directories.

2. Copy ASP.NET application content to the Web server.


Sikkim Manipal University Page No. 312

DOT Net Technologies

Unit 9

3. Enable common storage for ASP.NET session state by completing the following steps: Step-1: Select the method for maintaining and storing ASP.NET session state. Step - 2: If you have decided to maintain session state with the ASP.NET state service, configure out-of-process session state with the ASP.NET state service. Step - 3: If you have decided to maintain session state with SQL Server, configure out-of-process session state with SQL Server. Step - 4: Configure encryption and validation keys. Step - 5: Configure ASP.NET to use the appropriate session state. Step - 6: Secure the ASP.NET session state connection string. Complete the ASP.NET Application Deployment Ensure the security and availability of your ASP.NET applications. Verify that the ASP.NET applications were deployed successfully. Back up the Web server. Enable client access to your ASP.NET applications.

Deploying the Web Server (IIS 6.0) You must install the Web server before you can install your ASP.NET applications. In addition to installing Windows Server 2003, you must install and configure IIS 6.0 on the Web server. You must also enable ASP.NET so that the Web server can run ASP.NET applications.

Sikkim Manipal University

Page No. 313

DOT Net Technologies

Unit 9

Figure 9.3 below illustrates the process for deploying the Web server.

Figure 9.3: Deploying the Web Server

Installing Windows Server 2003 (IIS 6.0) The deployment process presented here assumes that you install Windows Server 2003 with the default options. If you use other methods for installing and configuring Windows Server 2003, such as unattended setup, your configuration settings might be different. Note: When you complete the installation of Windows Server 2003, Manage Your Server automatically starts. The deployment process assumes that you quit Manage Your Server, and then further configure the Web server in Add or Remove Programsin Control Panel. Installing and Configuring IIS 6.0 (IIS 6.0) Because IIS 6.0 is not installed during the default installation of Windows Server 2003, the next step in deploying the Web server is to install and configure IIS 6.0. The deployment process presented here assumes that you install IIS 6.0 with the default options in Add or Remove Programs in Control Panel. If you use other methods for installing and configuring Windows Server 2003, such as Manage Your Server, the default configuration settings might be different.

Sikkim Manipal University

Page No. 314

DOT Net Technologies

Unit 9

Install and configure IIS 6.0 by completing the following steps: Step 1: Install IIS 6.0 with only the essential components and services. As with installing Windows Server 2003, the primary concern when installing and configuring IIS 6.0 is to ensure that the security of the Web server is maintained. Enabling unnecessary components and services increases the attack surface of the Web server. You can help ensure that the Web server is secure by enabling only the essential components and services in IIS 6.0. Step 2: If you want to manage the Web site content by using Microsoft FrontPage, install FrontPage 2002 Server Extensions from Microsoft on the Web server. Enabling ASP.NET in the Web Service Extensions List (IIS 6.0) After you install IIS 6.0, you need to enable ASP.NET. You can enable ASP.NET in Add or Remove Windows Components, which is accessible from Add or Remove Programs in Control Panel. When you enable ASP.NET by using this method, ASP.NET is also enabled in the Web service extensions list. If you enabled ASP.NET in this way, then you can continue to the next step in the deployment process. ASP.NET is not Enabled ASP.NET might not be enabled in the Web service extensions list if either of the following is true: You installed a version of the .NET Framework and ASP.NET (other than version 1.1) from a Web download or as part of an application such as the Microsoft Visual Studio .NET development tool. You disabled ASP.NET in the Web service extensions list because you were not running ASP.NET applications on an existing Web server. If ASP.NET is not already enabled, view the Web service extensions list in IIS Manager and configure the status of the ASP.NET v1.1.4322 Web service extension to Allowed.
Sikkim Manipal University Page No. 315

DOT Net Technologies

Unit 9

Installing ASP.NET Applications (IIS 6.0) After the Web server is deployed, you can install your ASP.NET applications. First, you must create a Web site and virtual directories for each ASP.NET application. Then you need to install each ASP.NET application in the corresponding Web site and virtual directory. When there are provisioning or setup scripts for your ASP.NET applications, use these scripts to install the ASP.NET applications on the Web server. Because the provisioning and setup scripts create the Web sites and virtual directories while installing ASP.NET applications, you do not need to perform any manual steps to install the ASP.NET applications. In this case, run the provisioning or setup scripts to install and configure the Web sites and applications, and then continue to the next step in the application deployment process. Figure 9.4 below illustrates the process for installing your ASP.NET applications.

Figure 9.4: Installation Process for ASP.NET Applications

Creating Web Sites and Virtual Directories for each ASP.NET Application (IIS 6.0) For each ASP.NET application, you must create a virtual directory in a new or existing Web site. Later in the installation process, you will install your ASP.NET applications into their corresponding Web sites and virtual directories.
Sikkim Manipal University Page No. 316

DOT Net Technologies

Unit 9

Create the Web sites and virtual directories for your ASP.NET applications by completing the following steps: Create Web sites and home directories. Create virtual directories.

Creating Web Sites and Home Directories Using IIS 6.0 Each Web site must have one home directory. The home directory is the central location for your published Web pages. It contains a home page or index file that serves as a portal to other pages in your Web site. The home directory is mapped to the domain name of the Web site or to the name of the Web server. Create a Web site and home directory for an ASP.NET application by completing the following steps: Step 1: Create the folder that will be the home directory for the Web site on the Web server. The folder that is the home directory of the Web site contains all of the content and subdirectories for the Web site. The folder can be created on the same computer as the Web server or on a Universal Naming Convention (UNC)shared folder on a separate server. At a minimum, create the folder on the following: An NTFS file system partition, which helps ensure proper security. A disk volume other than the system volume, which reduces the potential of an attack on a Web site bringing down the entire Web server and improves performance. In a location that will not require requests for Web site content to contain /bin in the requested URL. As a security measure, ASP.NET returns a 404 error for all requests containing /bin in the requested URL. Step 2: Create the Web site on the server.

Sikkim Manipal University

Page No. 317

DOT Net Technologies

Unit 9

Step 3: If the Web site is FrontPage extended, then configure the Web site on the Web server to be FrontPage extended. Creating Virtual Directories (IIS 6.0) A virtual directory is a folder name, used in an address, which corresponds to a physical directory on the Web server or a Universal Naming Convention (UNC) location. This is also sometimes referred to as URL mapping. Virtual directories are used to publish Web content from any folder that is not contained in the home directory of the Web site. When clients access content in a virtual directory, the content appears to be in a subdirectory of the home directory, even though it is not. For security reasons, you might want to move the Web site content to a different disk volume during the application deployment process. You can move the content to another disk volume on the Web server or to a shared folder on a separate server. You can use virtual directories to specify the UNC name for the location where the content is placed, and provide a user name and password for access rights. For each virtual directory required by the ASP.NET application, create a corresponding virtual directory on the Web server by completing the following steps: Create the folder on the Web server to contain the virtual directory content. 1. Ensure that you create the folder in a secure manner that does not compromise the security of the Web server. 2. Create the virtual directory under the appropriate Web site on the server. Copying ASP.NET Application Content (IIS 6.0) When no installation program or provisioning scripts exist for your ASP.NET application, you can copy the content of the ASP.NET application to the corresponding Web site and virtual directories that you created on the Web server.
Sikkim Manipal University Page No. 318

DOT Net Technologies

Unit 9

You can copy the ASP.NET application content to the Web server by using one of the following methods: Run the Xcopy command to copy ASP.NET application content to the Web server on an intranet or internal network. Use Microsoft Windows Explorer to copy ASP.NET application content to the Web server on an intranet or internal network. Use the Copy Project command in Visual Studio .NET to copy ASP.NET application content to the Web server on an intranet or internal network, if the application has been developed by using Visual Studio .NET. Note: FrontPage Server Extensions must be installed on the Web server to use the Copy Project command. Use the Publish Web command in FrontPage to copy ASP.NET application content to the Web server on an intranet or over the Internet, if the Web site that contains the application has been developed using FrontPage. Enabling Common Storage for ASP.NET Session State (IIS 6.0) ASP.NET session state lets you share client session data across all of the Web servers in a Web farm or across different worker processes or worker process instances on a single Web server. Clients can access different servers in the Web farm across multiple requests and still have full access to session data. You can enable common storage for ASP.NET session state by performing the following steps: 1. Select the method for maintaining and storing ASP.NET session state. 2. If you have decided to maintain session state with the ASP.NET state service, configure out-of-process session state with the ASP.NET state service.
Sikkim Manipal University Page No. 319

DOT Net Technologies

Unit 9

3. If you have decided to maintain session state with SQL Server, configure out-of-process session state with SQL Server. 4. Configure the encryption and validation keys. 5. Configure ASP.NET to use the session state method that you selected in Step 1. 6. Secure the ASP.NET session state connection string in the registry

9.5 Summary
The IIS (Internet Information Services) is a web server provided by Microsoft. The IIS 6.0 provides integrated, reliable, scalable, secure, and manageable Web server capabilities over an intranet, the Internet, or an extranet. It introduces tp the reader the basic features of IIS and its

architecture. It describes the creation of application pools using IIS 6.0 with the help of other components in Visual Studio. It discusses the management of application pools in IIS 6.0. It also discusses the steps involved in deploying ASP.NET applications on IIS 6.0 Web Server. Self Assessment Questions 1. The ___________ component is a macro component that bundles the IIS components that are found in the Software\System\Networking & communications\Infrastructure directory in the component browser. 2. The ________ enables remote authors to create, move, or delete files, file properties, directories, and directory properties on your server over an HTTP connection. 3. You can use News Network Transport Protocol (NNTP) and ______ services to set up intranet news and mail services that work in conjunction with IIS. 4. The _______ feature in IIS does not support IPv6 addresses or IPv6 prefixes.

Sikkim Manipal University

Page No. 320

DOT Net Technologies

Unit 9

5. The ________ isolation mode enables you to completely separate an application in its own process, with no dependence on a central process such as Inetinfo.exe to load and execute the application. 6. An _______ is a group of URLs that are routed to one or more worker processes that share the same configuration. 7. With ________ mode, you can run applications that are incompatible with worker process isolation mode because they were developed for earlier versions of IIS.

9.6 Terminal Questions


1. Describe the features of IIS 6.0 (Refer to 9.1) 2. Discuss the following: (Refer to 9.2) IIS Architecture IIS Request Processing Models

3. Explain the process of deploying ASP.NET Applications (Refer to 9.4)

9.7 Answers to Self Assessment Questions


1. Internet Information Services technology (IIS) 2. Web Distributed Authoring and Versioning (WebDAV) 3. Simple Mail Transfer Protocol (SMTP) 4. IP Address Restrictions 5. Worker process 6. application pool 7. isolation mode

Sikkim Manipal University

Page No. 321

Você também pode gostar