+ All Categories

MC0081

Date post: 27-Oct-2014
Category:
Upload: samirsofy
View: 246 times
Download: 1 times
Share this document with a friend
Popular Tags:
43
Spring 2012 Master of Computer Application (MCA) – Semester V MC0081 – .(DOT) Net Technologies– 4 Credits (Book ID: B0974) (Books ID: B 0974) Assignment Set – 1 (40 Marks) Books ID: B 0974 Each question carries FIVE marks 5X 8 = 40 1. Write about the Common Language Runtime Library of Dot Net. Ans1: 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:
Transcript
Page 1: MC0081

Spring 2012

Master of Computer Application (MCA) – Semester V

MC0081 – .(DOT) Net Technologies– 4 Credits (Book ID: B0974)

(Books ID: B 0974)

Assignment Set – 1 (40 Marks)

Books ID: B 0974 Each question carries FIVE marks 5X 8 = 40

1. Write about the Common Language Runtime Library of Dot Net.

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

Page 2: MC0081

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

Page 3: MC0081

NET Framework Class LibraryThe .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).

2) With the help of a suitable example, explain the steps in compiling and running a C# program.

A2) Creating your first C# Program

Page 4: MC0081

It would be very easy to create, compile and run a C# program by following the steps illustrated in the following topics

Compiling and ExecutingThe 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.

Steps for writing and compiling the C# code:

Type the C# code in the notepad as shown below:

Keying a program in an editor 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

Saving the program into the directory or folder 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:

Page 6: MC0081

Opening the command prompt window

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.

3) With the help of a suitable example explain the creation of a simple windows form based application. A3) 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

Page 7: MC0081

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

Page 8: MC0081

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){//…}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

Page 9: MC0081

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

{

Application.Run(new HandDrawnClass( ));

}

When you run this application, the window is opened and the text is displayed. Pressing Cancel closes the application.

Page 11: MC0081

4. Describe ASP.NET Architecture.

A4) ASP.NET Server ControlsASP.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 OverviewWhen 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 special-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.

Page 12: MC0081

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.The page framework provides predefined HTML server controls for the HTML elements most commonly used dynamically on a page: the formelement, 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.

5. Describe the anatomy of an ASP.NET Application.

A5) Anatomy of ASP.NET ApplicationTo 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 user’s 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 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

Page 13: MC0081

design surface or form, manipulate the control’s 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.NETASP.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.

ASP.NET Compilation SystemThe 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 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.

Page 14: MC0081

ASP.NET Web PagesYou 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 server-side 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.

6. Describe State Management in ASP.NET

A6) 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. It’s 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 object remains as before, but the option to plug in your own session state provider is available in ASP.NET 3.5.

Page 15: MC0081

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?

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

Page 16: MC0081

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

7. Describe the following:

o Importance of ADO.Net

o Data Access Scenarios

o Disconnected Architectures

A7) Importance of ADO.Net -; As part of the .NET Framework class library, Microsoft has created a new set of data access classes, known collectively as ADO.NET. Why has Microsoft introduced a new data access technology? For one thing, they had to. OLE DB and ADO.NET are based on COM. Because .NET provides a new object infrastructure, it is necessary to provide .NET data access classes. (It is quite possible in .NET to call legacy COM components, a subject we will discuss in Chapter 23. Hence .NET applications can call ADO through an interoperability layer. But it is clearly desirable to provide native .NET interfaces for something as basic as data access.)

Moreover, there has been a significant evolution in application development since ADO was designed. Many of today’s applications are oriented toward the Web and have a much more loosely coupled structure than traditional desktop or client/server applications. Many modern applications use XML to

Page 17: MC0081

encode data that is passed over a network. After the needed data has been extracted from the data source and converted to XML, the connection to the data source can be closed. An application that does not require all its clients to simultaneously maintain database applications can be much more scaleable.

To facilitate programming in this disconnected scenario, ADO.NET provides a new class, DataSet, which holds in memory a representation of data that was retrieved from some data source. Unlike the Recordset of the ADO model, which could hold only a single table, the DataSet can hold many tables; it also holds constraints and relationships among the tables. Thus, a data set can be viewed as an in-memory database.

To obtain data from a database, ADO.NET supplies a Connection class. A Connection object can be used to support connection-oriented programming of a database, if that is what is desired. Or, through a DataAdapter object, a data set can be populated with data from the data source, and the connection can be closed.

Data Access Scenarios

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.

Page 18: MC0081

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

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.

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.

8. Describe the ASP.NET Security Model.

A8) 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

Page 19: MC0081

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.

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.

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.

Page 20: MC0081

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

Page 21: MC0081

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.

MC0081 – .(DOT) Net Technologies– 4 Credits

(Book ID: B0974)

Page 22: MC0081

Assignment Set – 2 (40 Marks)

Each question carries FIVE marks 5X 8 = 40

1. Write about Assemblies in Dot Net

A1) The .NET assembly is the standard for components developed with the Microsoft.NET. Dot NET assemblies may or may not be executable, i.e., they might exist as the executable (.exe) file or dynamic link library (DLL) file. All the .NET assemblies contain the definition of types, versioning information for the type, meta-data, and manifest. The designers of .NET have worked a lot on the component (assembly) resolution.

There are two kind of assemblies in .NET;

private  shared

Private assemblies are simple and copied with each calling assemblies in the calling assemblies folder.

Shared assemblies (also called strong named assemblies) are copied to a single location (usually the Global assembly cache). For all calling assemblies within the same application, the same copy of the shared assembly is used from its original location. Hence, shared assemblies are not copied in the private folders of each calling assembly. Each shared assembly has a four part name including its face name, version, public key token and culture information. The public key token and version information makes it almost impossible for two different assemblies with the same name or for two similar assemblies with different version to mix with each other.

An assembly can be a single file or it may consist of the multiple files. In case of multi-file, there is one master module containing the manifest while other assemblies exist as non-manifest modules. A module in .NET is a sub part of a multi-file .NET assembly. Assembly is one of the most interesting and extremely useful areas of .NET architecture along with reflections and attributes, but unfortunately very few people take interest in learning such theoretical looking topics.

2) Write a C# program to perform basic arithmetic operations

Page 23: MC0081

A2) public static class Operation{ public static bool DoSequenceOfAnd(params bool[] sequenceOfBooleanValue) { bool andResult = true; Array.ForEach(sequenceOfBooleanValue, (item) => { andResult &= item; }); return andResult; } public static bool DoSequenceOfOr(params bool[] sequenceOfBooleanValue) { bool orredResult = default(bool); Array.ForEach(sequenceOfBooleanValue, (item) => { orredResult |= item; }); return orredResult; } public static bool DoSequenceOfXOr(params bool[] sequenceOfBooleanValue) { bool xoredResult = default(bool); Array.ForEach(sequenceOfBooleanValue, (item) => { xoredResult ^= item; }); return xoredResult; } public static T DoSequenceOfPlus<T>(params T[] sequenceOfTValues) where T : struct { T additionResult = default(T); Func<T, T, T> adder = ExpressionGenerator.AdditionExpression<T>(); Array.ForEach(sequenceOfBooleanValue, (item) => { additionResult = adder(item, additionResult); });

Page 24: MC0081

return additionResult; } public static T DoSequenceOfMultiply<T>(params T[] sequenceOfTValues) where T : struct { dynamic multiplicationResult = (DoSequenceOfPlus<int>(default(int), 1)); Func<T, T, T> multiplier = ExpressionGenerator.MultiplicationExpression<T>(); Array.ForEach(sequenceOfBooleanValue, (item) => { multiplicationResult = multiplier(item, multiplicationResult); }); return multiplicationResult; }}

3. Describe the Web form life cycle.

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

Page 25: MC0081

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.

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.

4. Write about the creation of Master Pages in ASP.Net applicationsMaster PagesMaster 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

Page 26: MC0081

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 file’s page directive.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:

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

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.

Page 27: MC0081

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.

5. Explain the importance and applications of Global.asax Application file.

A5) 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 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 28: MC0081

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

Page 29: MC0081

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

Page 30: MC0081

The @ Import DirectiveThe @ 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:

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 DirectiveThe @ 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” %>

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

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.

Page 31: MC0081

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.

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

A7) 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

Page 32: MC0081

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

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.

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

Page 33: MC0081

8. Describe the concept of Forms Authentication in Dot Net.

A8) Form-Based Authentication

Form-based authentication is, at its core, a vendor specific, container-implemented authentication mechanism that allows the look and feel of the login screen to be customized.

This is a cookie based authentication system where the username and password is stored in a text file or a database. This is the most widely used authentication method on Web. The login is performed via a form that must contain two fields for entering a username and a

Page 34: MC0081

password,j_username and j_password, respectively, and a special container-recognized action j_security_check.

Apart from the login form, two very important elements, the login-config and security-constraint elements in the Web.xml are used for the application-specific implementation of form-based authentication.

· The login-config element is used to indicate that an application is using form-based authentication and to specify the locations of the login and error pages to be used.

· The security-constraint element is used to define which resources are protected and to associate role-based constraints with these protected resources.

When a user attempts to access a restricted resource, the container checks the user’s authentication. If the user is already authenticated and occupies a role that is authorized to access the resource, the requested resource is activated and a reference to it is returned. If the user is not authenticated, the following series of events occur:

1. The login form is sent to the client and the container stores the original client request.

2. The client posts the login form back to the server, which then attempts to authenticate the client.

3. If authentication is successful, the user’s roles are compared to the roles necessary to access the resource. If the user’s roles authorize access to the resource, the client is redirected to the resource using the original request URL path stored by the container in the first step.

4. If authentication is not successful, the user is redirected to the error page defined in the login-config element.


Recommended