mc0081 fall drive assignment 2011

23
MC0081 – .(DOT) Net Technologies 1. Describe the following: Importance of ADO.Net 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 fulfil 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 a 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 Web-based applications. To build all communication on industry standards to ensure that code based on the .NET Framework can integrate with any other code. 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 third-party 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.

Upload: vj

Post on 21-Sep-2014

151 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: MC0081 Fall Drive Assignment 2011

MC0081 – .(DOT) Net Technologies

1. Describe the following:

Importance of ADO.Net

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 fulfil 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 a 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 Web-based applications.

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

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 third-party 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

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.

Page 2: MC0081 Fall Drive Assignment 2011

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 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 applications using Windows Communication Foundation (WCF).

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.

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.

Page 3: MC0081 Fall Drive Assignment 2011

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. That’s why Microsoft created ADO.NET, an elegant, easy-to-use database API for managed applications. ADO.NET is exposed as a set of classes in the .NET Framework class library’s 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 you’re 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. That’s ADO.NET in a nutshell—the database language spoken by managed applications. ADO.NET is an essential component of the .NET Framework. Let’s see how it works.

Disconnected Architectures

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.

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.

2. With the help of a suitable example, explain the steps involved in editing, compiling and running a 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)

Page 4: MC0081 Fall Drive Assignment 2011

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

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

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:

Page 5: MC0081 Fall Drive Assignment 2011

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

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

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.

Page 6: MC0081 Fall Drive Assignment 2011

Figure 2.9: Output of the Sample Program

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().

3. Discuss the following: Web.config file : It is an optional XML File which stores configuration details for a specific asp.net web application. When you modify the settings in the Web.Config file, you do not need to restart the Web service for the modifications to take effect.. By default, the Web.Config file applies to all the pages in the current directory and its subdirectories. You can use the tag to lock configuration settings in the Web.Config file so that they cannot be overridden by a Web.Config file located below it. You can use the allowOverride attribute to lock configuration settings. This attribute is especially valuable if you are hosting untrusted applications on your server.

One of the goals of the Microsoft .NET Framework from the outset was to support XCOPY installs–that 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 don’t 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. Here’s 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

Page 7: MC0081 Fall Drive Assignment 2011

aren’t the only ones that can appear in a Web.config file, but they are the most common. Web.config’s architecture is extensible, enabling developers to define custom sections when circumstances warrant. <appSettings>The appSettings section of Web.config holds application-specific values (strings) that are keyed by other strings. Its purpose is to parameterize an application’s 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 that’s 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> Page_Load can be rewritten to extract the connection string from Web.config: string conn = ConfigurationSettings.AppSettings["MyConnectionString"]; 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 FCL’s 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. It’s 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 unlimited–as developers are free to define custom subsections–the ones listed in the following table are supported by default and can be used without writing custom configuration handlers. <system.web> Subsections 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 don’t 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 application’s virtual root directory. What’s inside a Global.asax file? Global.asax supports three element types: Global directives Global event handlers Global object tags

Page 8: MC0081 Fall Drive Assignment 2011

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. We’ll discuss global directives first and global event handlers second. Then, for completeness, we’ll talk about global object tags, too. Global Directives Global directives, also known as application directives, provide application-wide 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.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 root’s 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 enables developers to code handlers in C++ and other languages that ASP.NET doesn’t 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 isn’t 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

Page 9: MC0081 Fall Drive Assignment 2011

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 code-behind 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 doesn’t import by default. For example, let’s say you include the following <script> block in Global.asax<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 isn’t 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 application’s 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 doesn’t link to by default. (As an example, suppose your Global.asax file uses classes in the System.DirectoryServices namespace. Because that namespace isn’t imported by default and because the types that belong to that namespace live in System.DirectoryServices.dll, which ASP.NET doesn’t link to by default, you need to include the following statements in Global.asax: <%@ Import Namespace="System.DirectoryServices" %> <%@ Assembly Name="System.DirectoryServices" %> If you don’t, ASP.NET will greet you with an error message the moment the application starts up. Global Event Handlers The most common reason for including Global.asax files in ASP.NET applications is to handle global events – events that aren’t 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 application’s 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 () { ...

Page 10: MC0081 Fall Drive Assignment 2011

} </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 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 isn’t used all that often because ASP.NET applications don’t have to clean up after themselves by deleting objects created in Application_Start, but it’s 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, you’ll 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 hasn’t 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 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. They’re listed in the order in which they’re called. Method

Description

Application_Begin Request Called at the beginning of each request Application_Authenticate Request Called to authenticate the caller Application_AuthorizeRequest Called to determine whether the caller

is authorized to access the requested resource

Application_ResolveRequest Cache Called to resolve the current request by providing content from a cache

Application_AcquireRequest State Called to associate the current request with a session and populate session state

Application_PreRequestHandler Execute

Called to prepend content to the HTTP response

Application_PostRequestHandler Execute

Called to append content to the HTTP response

Application_ReleaseRequest State Called to release (store) any state associated with this session

Application_UpdateRequest Cache Called to update a cache with content returned in the response

Application_EndRequest Called at the end of each request

Page 11: MC0081 Fall Drive Assignment 2011

4. Discuss the following: IIS Architecture : 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 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 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 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

Page 12: MC0081 Fall Drive Assignment 2011

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.

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, 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 self-contained 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.

Page 13: MC0081 Fall Drive Assignment 2011
Page 14: MC0081 Fall Drive Assignment 2011

MC0081 – .(DOT) Net Technologies

1. Write the basic steps in building Connection Strings from Configuration Files in ADO.Net applications

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.

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);}}

2. Discuss the following: 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.

Page 15: MC0081 Fall Drive Assignment 2011

ASP.NET 3.5 applications can include a \App_Code directory where you place your class’s 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.

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. 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.

3. Describe the importance of Application State in ASP.Net applications

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. 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 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;

Page 16: MC0081 Fall Drive Assignment 2011

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 non-volatile 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 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.

4. Describe the theory of creating application pools in 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 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

Page 17: MC0081 Fall Drive Assignment 2011

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 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.