Vous êtes sur la page 1sur 18

Master of Computer Application (MCA) Semester 5 MC0081 .

(DOT) Net Technologies


Assignment Set 1

Que 1.Describe the steps involved in creating classes and objects with the help of a program in C#. Ans: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. 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<(Of <(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# 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:

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 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 */

Que 2. With the help of a suitable example, explain the steps involved in editing, compiling and running a C# program Ans: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 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/. 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 5

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:

The name of our C# program is hello.cs. The syntax for compilation of the above program file is:

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:

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

Que 3. Discuss the following: Web.config file Ans: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:

Global.asax Application File

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

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 8

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:

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

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 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. Whats inside a Global.asax file? Global.asax supports three element types: Global directives 9

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

10

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:

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

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:

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

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

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

13

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 event handlers Application_PreRequestHandler Execute and Application_ PostRequestHandlerExecute enable HTTP responses to be modified before theyre returned to clients. The following Global. sax 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>

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: <%@ Import Namespace=System.Diagnostics %>

14

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 e-mail 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. 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:

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

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

4. Discuss the following: IIS Architecture IIS Request Processing Models Ans:IIS Architecture: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 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. For more information about HTTP.sys, see HTTP Protocol Stack. 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. For more information about worker processes,

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.

16

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 more information about application pools, For a visual representation of worker process isolation mode architecture, see Figure 2.1.

Figure 2.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. IIS 5.0 isolation mode provides compatibility for applications that were designed to run in earlier versions of IIS. When IIS 6.0 is running in IIS 5.0 isolation mode, request processing is almost identical to the request processing in IIS 5.0. When a server is working in IIS 5.0 isolation mode, application pools, recycling, and health monitoring features are unavailable. 17

For a visual representation of IIS 5.0 isolation mode architecture, see Figure 2.2. The dashed line in Figure 2.2 indicates the dependency of the worker process on the WWW service, which manages the worker process. For more information about the role of the WWW service, see

Figure 2.2 Architecture of IIS 5.0 Isolation Mode Use IIS 5.0 isolation mode only if components or applications do not function in worker process isolation mode. The latter mode is designed to provide an environment in which most existing applications or sites function correctly.

18

Vous aimerez peut-être aussi