MCA (New) V Semester Assignments for February 2009 Session

Subject Code Subject Name Credits : 04 Books ID: B 0974 Each question carries FIVE marks 5X 8 = 40 : MC 0081 : .(DOT) Net Technologies Assignment No: 01 Marks: 40

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

Common Language Runtime (CLR) The CLR is described as the "execution engine" of .NET. It provides the environment within which the programs run. It's this CLR that manages the execution of programs and provides core services, such as code compilation, memory allocation, thread management, and garbage collection. Through the Common Type System (CTS), it enforces strict type safety, and it ensures that the code is executed in a safe environment by enforcing code access security. The software version of .NET is actually the CLR version. Working of the CLR When the .NET program is compiled, the output of the compiler is not an executable file but a file that contains a special type of code called the Microsoft Intermediate Language (MSIL), which is a low-level set of instructions understood by the common language run time. This MSIL defines a set of portable instructions that are independent of any specific CPU. It's the job of the CLR to translate this Intermediate code into a executable code when the program is executed making the program to run in any environment for which the CLR is implemented. And that's how the .NET Framework achieves Portability. This MSIL is turned into executable code using a JIT (Just In Time) complier. The process goes like this, when .NET programs are executed, the CLR activates the JIT complier. The JIT complier converts MSIL into native code on a demand basis as each part of the program is needed. Thus the program executes as a

native code even though it is compiled into MSIL making the program to run as fast as it would if it is compiled to native code but achieves the portability benefits of MSIL. Features of the Common Language Runtime The common language runtime manages memory, thread execution, code execution, code safety verification, compilation, and other system services. These features are intrinsic to the managed code that runs on the common language runtime. With regards to security, managed components are awarded varying degrees of trust, depending on a number of factors that include their origin (such as the Internet, enterprise network, or local computer). This means that a managed component might or might not be able to perform file-access operations, registry-access operations, or other sensitive functions, even if it is being used in the same active application. The runtime enforces code access security. For example, users can trust that an executable embedded in a Web page can play an animation on screen or sing a song, but cannot access their personal data, file system, or network. The security features of the runtime thus enable legitimate Internet-deployed software to be exceptionally featuring rich. The runtime also enforces code robustness by implementing a strict type-and-code-verification infrastructure called the common type system (CTS). The CTS ensures that all managed code is self-describing. The various Microsoft and third-party language compilers generate managed code that conforms to the CTS. This means that managed code can consume other managed types and instances, while strictly enforcing type fidelity and type safety. In addition, the managed environment of the runtime eliminates many common software issues. For example, the runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. This automatic memory management resolves the two most common application errors, memory leaks and invalid memory references. The runtime also accelerates developer productivity. For example, programmers can write applications in their development language of choice, yet take full advantage of the runtime, the class library, and components written in other languages by other developers. Any compiler vendor who chooses to target the runtime can do so. Language compilers that target the .NET Framework make the features of the .NET Framework available to existing code

written in that language, greatly easing the migration process for existing applications. While the runtime is designed for the software of the future, it also supports software of today and yesterday. Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs. The runtime is designed to enhance performance. Although the common language runtime provides many standard runtime services, managed code is never interpreted. A feature called just-in-time (JIT) compiling enables all managed code to run in the native machine language of the system on which it is executing. Meanwhile, the memory manager removes the possibilities of fragmented memory and increases memory locality-of-reference to further increase performance. Finally, the runtime can be hosted by high-performance, server-side applications, such as Microsoft® SQL Server™ and Internet Information Services (IIS). This infrastructure enables you to use managed code to write your business logic, while still enjoying the superior performance of the industry's best enterprise servers that support runtime hosting.

2. With the help of a suitable example, explain the steps in compiling and running a C# program.
using System; class Hello { public static void Main() { Console.WriteLine("Hello C#"); } }
After entering the above code in an editor, you have to perform the following steps 1.Save the file as Hello.cs. cs is an extension to indicate C-Sharp like .java for a Java source file. You have to supply this extension while saving your file, otherwise the code will not compile correctly. The saved file will be of the extension .cs.txt. 2. 1.Compile the code by giving the following command at the command prompt:

csc Hello. To write the code for your application 1. If everything goes on well. With the help of a suitable example explain the creation of a simple windows form based application. 4. World!") .cs 1. Create a Windows Application called HelloWorld. 3. Click the button to select it. Otherwise. you have to simply give a command as shown below at the command prompt. Answer To create a Windows Form 1. See Figure 4. then you can be able to view the message “Hello C#” as shown in the figure above. 3. 2. Insert the following code: VB C# C++ F# JScript Copy MessageBox. set the Text property to Say Hello. you will be viewing a command prompt along with the copyright information as shown in Figure 4. Double-click the button to add an event handler for the Click event. The Code Editor will open with the insertion point placed within the event handler.If there are compile errors you will be prompted accordingly. For details.Show ("Hello. In the Properties window. From the Toolbox. you have to execute the program in order to view the final output. 2. see How to: Create a New Windows Forms Application Project. Start Visual Studio. 2. For that purpose. As a final step. drag a Button control onto the form.

This section provides an overview of the ASP. Press F5 to run the application. Describe ASP. VBC# C++ F# JScript Copy This language is not supported or no code example is available.VBC#C++F#JScript Copy This language is not supported or no code example is available. To test your application 1. 3. Close the Windows Form to return to Visual Studio. . J# Copy MessageBox.NET. When your application is running. World!"). World!" is shown.NET Architecture.NET infrastructure and subsystemrelationships. 4. click the button and verify that "Hello. The following illustration shows the relationships among the security systems in ASP.Show("Hello. 2. as they relate to the subject of security.

NET provides the two additional types of authentication described in the following table. If the application authenticates the request.As the illustration shows. Centralized authentication service provided by Microsoft that offers a single log on and core profile services for member sites. the system issues a form that contains the credentials or a key for reacquiring the identity. IIS always assumes that a set of credentials maps to a Windows NT account and uses them to authenticate a user.NET is contained in files named Web. the request and authentication information are handed off to the application. all Web clients communicate with ASP. ASP.config can be placed in the same directories as . no authentication occurs.NET applications through IIS. The user provides credentials and submits the form.NET application ). see the IIS documentation.NET configuration. IIS deciphers and optionally authenticates the request. see Key Security Concepts.NET authentication.0: basic. and.NET handler using whatever validation method the application developer specifies.0 as the primary host environment. returns the appropriate resource. they are authenticated and authorized by an ASP.NET Framework. Web.NET Configuration Files ASP.config. For more information on IIS authentication. If you request a URL containing an ASP. There are three different kinds of authentication available in IIS 5. Passport authentication Using ASP. You can select the type of authentication to use in the IIS administrative services.NET security features. if the client is authorized.NET application. has a hierarchical architecture.config and Machine. Subsequent requests are issued with the form in the request headers.NET authentication provider Forms authentication Description A system by which unauthenticated requests are redirected to an HTML form using HTTP client-side redirection.NET application can use the low-level security features of the . IIS also finds the requested resource ( such as an ASP. ASP. you should understand the interaction with IIS authentication services. For more information. digest. Integrating with IIS This release of ASP. If Allow Anonymous is turned on. and Integrated Windows Authentication ( NTLM or Kerberos ). of which security is a part. an ASP. When considering ASP.NET uses IIS 5. In addition to the built-in ASP. All configuration information for ASP.

The Machine.ASPXAUTH"> The authentication mode cannot be set at a level below the application root directory. there are sections for each major category of ASP.config file in the subdirectory. In a Web.config file is organized as follows: <authentication mode = " [ Windows/Forms/Passport/None ] "> <forms name = " [ name ] " loginUrl = " [ url ] " > <credentials passwordFormat = " [ Clear. Empty Empty If you set the mode to forms. and if the request does not have a valid form.the application files.config file is in the Config directory of the install root. Subdirectories inherit a directory's settings unless overridden by a Web. Default Value <allow roles= > No default value Comment <allow users = "*"> All <authentication mode = "Windows"> <credentials passwordFormat = "SHA1"> <deny roles = ""> <deny users = ""> <forms loginUrl = "login. this is the URL to which the request is directed for a forms-based logon. MD5 ] "> <user name = " [ UserName ] " password = " [ password ] " /> </credentials> </forms> <passport redirectUrl = "internal" /> </authentication> <authorization> <allow users = " [ comma separated list of users ] " roles = " [ comma separated list of roles ] " /> <deny users = " [ comma separated list of users ] " roles = " [ comma separated list of roles ] " /> </authorization> <identity impersonate = " [ true/false ] " /> The default settings for these elements are shown in the following table. The hashing algorithm to be used on passwords. To see an example of the way in which the hierarchical configuration system works for security see Hierarchical Configuration Architecture.config file. Forms name.aspx"> <forms name = ".NET functionality. . SHA1. The security section of a Web.

config file.cs) and in the Page_Load method.dll and System. If you set the mode to passport.NET\ASP.dll. all of them can be found at c:\Program Files\Microsoft ASP. Create a new ASP. The values for each of the elements are usually set by overriding this section of the computer-level configuration file with a similar section in an application configuration file placed in the application root. Use the MvcHttpHandler to handle MVC requests. However. subdirectories can have their own configuration files that override other settings. Empty Empty There are three major subsections: authentication. This creates an application with a Default. a standard web.Routing. <forms protection = Type= [ All|None|Encryption|Validation ] "type"> <forms timeout = "30"> <forms validation = "?"> <identity impersonate = "false"> <passport redirectUrl = "internal" <user name = ""> <user password = ""> Timeout in seconds. and if the requested page requires authentication but the user has not logged on with Passport. EventArgs e) { . All subdirectories automatically inherit those settings. System.Net Web Application. True or false.aspx.Abstractions. 5.<forms path = "/"> Path.Mvc. and identity.NET Application. Add references to System.NET MVC Beta\Assemblies folder. authorization. Answer 1. and adds the initial references to the project. 2. Describe the anatomy of an ASP.dll.aspx page.Web.aspx (default. Open the code-behind file of Default.Web. Impersonation is disabled by default. process the request in MVC style: protected void Page_Load(object sender. then the user will be redirected to this URL.Web.

asax). 5.ApplicationPath). since those are extension methods. a URI template as the second. Notice the naming convention for it: Default comes from the route default value and the controller is just a suffix in the convention. and should contain a public method with a name the corresponds to an action.Web. you should add a using directive to use the namespace System. "{controller}/{action}".Current). map the route to the home controller. action="Index" }). Add a class to the web application under a Controllers folder and name it DefaultController.RewritePath(Request.} HttpContext. and navigate to the application directory ( “/” ). Create a default controller. Run the application. Add a Global Application Class (global.Mvc. EventArgs e) { RouteTable.Current. and default values as the third. world". } } 6. Notice that the default values object should have properties that correspond the names of the properties in the URI template. world”. 3. httpHandler. This class should inherit from System. } 4.Controller class. Since the default action is Index (taken from the default route).Routes. protected void Application_Start(object sender. The route above maps an incoming Url to a combination of a controller and an action.MapRoute("Default Route". . The MapRoute method takes a name of a route as the first parameter.Mvc.Web. then the class should look like this: public class DefaultController : Controller { public string Index() { return "Hello. new { controller = "Default". what you should get is the response “hello. and in the Application_Start method.ProcessRequest(HttpContext. In order to use the MapRoute and IgnoreRoute methods. IHttpHandler httpHandler = new MvcHttpHandler().

Now.config. There are several types of results we can return (such as JosnResult. Version=3.0.Web. Add the Url Routing Module. by calling the View method.Routing.5. Change the return value of the Index method in the default controller to be of type ActionResult.) but in this sample we will return a ViewResult.. 9. If you try to navigate to the Index action in the Default controller (/Default/Index).web section. Return a view as the result of the Index action. you should get the same response as earlier. <add name="UrlRoutingModule" type="System. Run the application and navigate to the Index action in the Default Controller.Web.But. register the Url Routing Module: <httpModules> .. Open the web. PublicKeyToken=31BF3856AD364E35" /> </httpModules> 8.UrlRoutingModule. System.0. ContentResult etc.Routing. and locate the <httpModules> tab in the system. There. 7. you will get an error. . Culture=neutral.

public ActionResult Index() { return View(). in the view markup. and in the Index method. Create a new ASP.cs) and change the class to inherit from System.aspx. Run the application and you should receive the response from the View we’ve just created.aspx inside Views\Default\ folder. which returned the Index. <%= ViewData["name"] %></h1> </div> </form> </body> 12. Display data in the View. open the code behind file (Index. Run the application and receive a greeting message bounded to the data that the controller has added to the dictionary.Mvc. . world</h1> </div> </form> </body> 10.aspx view. } Now.Web. the View method will look for a view whose name is equals to the name of the action.Net Form called Index. add data to the ViewData dictionary: public ActionResult Index() { ViewData["name"] = "Guy". return View(). } Create a view that corresponds to this action. 11. When called parameterless. The routing engine called the Index action in the Default controller. inside a folder the corresponds to the name of the controller. Edit the page (in design mode or source mode) and add a greeting message: <body> <form id="form1" runat="server"> <div> <h1>Hello. Open the controller. use that data in the greeting line: <body> <form id="form1" runat="server"> <div> <h1>Hello. In order to make this an MVC View.ViewPage.

Client – Side State Management This stores information on the client's computer by embedding the information into a Web page.Net MVC application from scratch in order to understand the anatomy of an ASP. You can add custom values to the view state.Net MVC application and the magic behind this framework. you should use control state to ensure other developers don’t break your control by disabling view state. The data is available only when the form is processed. c. This understanding can help me with adding MVC capabilities to my existing web applications as well. hidden fields store data in an HTML form without displaying it in the user's browser. a uniform resource locator(url). The techniques available to store the state information at the client end are listed down below: a. View State – Asp. or a cookie.NET Types of State Management There are 2 types State Management: 1.Net uses View State to track the values in the Controls. 6. Describe State Management in ASP. . Hidden fields – Like view state.In this post I build an ASP. one of the first tasks performed by page processing is to restore view state. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site. It is used by the Asp. d. When the page is posted. b. Control State – If you create a custom control that requires view state to work properly.net page framework to automatically save the values of the page and of each control just prior to rendering to the page.

e. If the data is too long for a single field. Though this adds processing overhead to the Web server. To configure view state encryption for an application does the following: <Configuration> <system. When an ASP. regardless of which user requests a page. then ASP.NET page is processed. Both application state and session state information is lost when the application restarts. Session State – Session State information is available to all pages opened by a user during a single visit. the current state of the page and controls is hashed into a string and saved in the page as a hidden field.NET 2. Implementation Procedure Client – Side State Management: View State: The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. Server – Side State Management a. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.web> <pages viewStateEncryptionMode="Always"/> </system. b.NET performs view state chunking (new in ASP. Query Strings . it supports in storing confidential information in view state. Application State . The following code sample demonstrates how view state adds data as a hidden form within a Web page’s HTML: <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE” value="/wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6 MTEgUE1kZGROWHn/rt75XF/pMGnqjqHlH66cdw==" /> Encrypting of the View State: You can enable view state encryption to make it more difficult for attackers and malicious users to directly read view state information. To persist user data between application restarts. you can store it using profile properties. 2.0) to split it across multiple hidden fields.Application State information is available to all pages.web> </configuration> .Query strings store values in the URL that are visible to the user.

This reduces the server processing time and decreases page size. If you use hidden fields. Unlike view state data.NET allows you to create your own custom hidden fields and store values that are submitted with other form data. so it is useful only for temporarily storing values. DateTime. ViewState is lost if the user visits a different Web page. However. ControlState allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property. you can enable view state encryption for a specific page by setting the value in the page directive.". or chunking. hashing. Hidden fields: ViewState stores information in the Web page using hidden fields. Control State: If you create a custom control that requires ViewState.Now.Text = (string)ViewState["lastVisit"]. Reading and Writing Custom View State Data: If you have a value that you’d like to keep track of while the user is visiting a single ASP.Alternatively. . but if you can disable it by setting the EnableViewState property for each web control to false. you must submit your pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which happens if the user clicks a link).ToString()). ASP. as the following sample demonstrates: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default. adding a custom value to ViewState is the most efficient and secure way to do that. however. // Define the ViewState object for the next page view ViewState.aspx. Hidden fields are sent back to the server when the user submits a form. else Label1. To use control state in a custom control. the information is never displayed by the Web browser (unless the user chooses to view the page source).cs" Inherits="_Default" ViewStateEncryptionMode="Always"%> View State is enabled by default. and display it if it does If (ViewState ["lastVisit"]!= null) Label1. Example: Determine the time of last visit to the page // Check if View State object exists. hidden fields have no builtin compression. so users can view or modify data stored in hidden fields. You can use hidden fields only to store information for a single page.Add("lastVisit". A HiddenField control stores a single variable in its Value property and must be explicitly added to the page. you can use the ControlState property to store state information for your control. your control must override the OnInit method and call the Register-RequiresControlState method during initialization and then override the SaveControl-State and LoadControlState methods. so it is not useful for storing session data.NET Web page.Text = "lastVisit ViewState not defined. encryption.

and display it if it does if (Request. Controlling the Cookie Scope: By default. browsers won’t send a cookie to a Web site with a different hostname. // Define the cookie for the next visit Response. as the following example demonstrates: Example: Response.Value = DateTime. You can’t directly delete cookies because they are stored on the client’s computer. We can expand the scope to a particular domain using the following statement: Example: Response.Cookies["lastVisit"]. and each cookie can be a maximum of 4 KB in length.Cookies: Web applications can store small pieces of data in the client’s Web browser by using cookies. the browser stores it in memory and the cookie is lost if the user closes his or her browser.Value).Cookies HttpCookieCollection. overwrite the cookie and set an expiration date in the past. you typically can’t store more than 20 cookies per site. To limit the scope of a cookie to a folder. else Label1. To work around the .Expires = DateTime. The Web browser then submits the same cookie to the server with every new request.Cookies.Cookies[“lastVisit”]. Through this the scope is limited to the “/Application1” folder that is the browser submits the cookie to any page with in this folder and not to pages in other folders even if the folder is in the same server.Cookies["lastVisit"].Cookies["lastVisit"]. To delete a cookie.HtmlEncode(Request.Path = "/Application1".ToString().Now. If you do not define the Expires property. You can control a cookie’s scope to either limit the scope to a specific folder on the Web server or expand the scope to any server in a domain.Text = Server. The most common use of cookies is to identify a single user as he or she visits multiple Web pages. Read a cookie -> read values in Request. A cookie is a small amount of data that is stored either in a text file on the client file system (if the cookie is persistent) or in memory in the client browser session (if the cookie is temporary).Response.Cookies["lastVisit"] != null) // Encode the cookie in case the cookie contains client-side script Label1. Create a cookie -> add a value to the Response.Domain = “Contoso”. set the Path property.AddDays(1).Text = "No value defined". Example: // Check if cookie exists. Reading and Writing Cookies: A Web application creates a cookie by sending it to the client as a header in an HTTP response.Now.Cookies["lastVisit"]. Storing Multiple Values in a Cookie: Though it depends on the browser.

. Response. Some Browsers and client devices impose a 2083 – character limit on the length of the URL. 2.aspx?mkt=en-US&setlang=enUS&q=hello+world Value Name | ASP. You must manually add query string values to every hyperlink that the user might click.QueryString["page"]).aspx?kbid=315233 In this example.20-cookie limit.Value = DateTime.Expires = DateTime. Therefore. Page: " + Server. the URL identifies the Default.QueryString[“q”] | hello world Limitations for Query Strings: 1. A query string is information that is appended to the end of a page URL. Example: Label1. you shouldn’t add query strings to button targets in forms. “315233. You must submit the page using an HTTP GET command in order for query string values to be available during page processing.HtmlEncode(Request. which specifies a language and query when searching the Microsoft.Value = "Tony".Now.aspx page.Value = "blue".QueryString[“setlang”] | en-US q | Request. A typical query string might look like the following real-world example: http://support. as the following code demonstrates: Example: Response. Response.Cookies["info"].com/results.QueryString[“mkt”] | en-US setlang | Request.microsoft.NET Object | Value mkt | Request.QueryString["prefs"]) + ". Running the code in this example sends a cookie with the following value to the Web browser: (visit=4/5/2006 2:35:18 PM) (firstName=Tony) (border=blue) Query Strings: Query strings are commonly used to store variables that identify specific pages. The query string (which starts with a question mark [?]) contains a single parameter named “kbid.microsoft. 3.AddDays(1).Text = "User: " + Server.HtmlEncode(Request.com/Default. Response.Cookies["info"]["firstName"]. Prefs: " + Server.ToString().Cookies["info"]["border"]. such as the following real-world URL.com Web site: http://search.Now.QueryString["user"]) + ".HtmlEncode(Request. you can store multiple values in a cookie. such as search terms or page numbers.” Query strings can also have multiple parameters.” and a value for that parameter.Cookies["info"]["visit"].

Server . This is the perfect place to initialize Application variables. and it is never exposed to the client. Application state is stored in the Application key/value dictionary.NET allows you to save values using session state. all pages can access data from a single location in memory. a global storage mechanism that is accessible from all pages in the Web application. Use this to perform error logging. Application_Error: Raised when an unhandled error occurs. a storage mechanism that is accessible from all pages requested by a single Web browser . Application state is a great place to store information that is not user-specific. Application_End: Raised when an application shuts down. Once you add your application-specific information to application state. ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors: a. rather than keeping separate copies of the data. c. the server manages it. By storing it in the application state. Session State: ASP.Side State Management: Application State: ASP. Application_Start: Raised when the application starts. Data stored in the Application object is not permanent and is lost any time the application is restarted. Use this to free application resources and perform logging. b.NET allows you to save values using application state.

You can use session state to accomplish the following tasks: i. and it offers much better performance than using the ASP. . This is the default. you can use session state to store user-specific information. each user session has a different session state. if a user leaves your application and then returns later after the session timeout period. ASP. but robust applications that use multiple Web servers or must persist session data between application restarts should use State Server or SQLServer. iii. Store session-specific data on the server for use across multiple browser or clientdevice requests during the same session. ii. Session state is stored in the Session key/value dictionary. This is perfect for storing shopping cart information. session state information is lost and a new session is created for the user. you can write application code leveraging these events. In addition. In addition.NET session state supports several different storage options for session data: a.NET state service or storing state information in a database server. This allows you to track which pages a user saw on your site during a specific visit. Therefore. Raise appropriate session management events.session. InProc Stores session state in memory on the Web server. Uniquely identify browser or client-device requests and map them to individual session instances on the server. InProc is fine for simple applications. Session state is similar to application state. except that it is scoped to the current browser session. If different users are using your application.

This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.NET State Service outperforms SQLServer. e. ASP.NET State Service. c. Better Scalability: With server-side state management. On the same hardware.NET State Service is included with any computer set up to run ASP. however. the service is set up to start manually by default.NET Web applications. You also need to implement the custom storage provider. a SQL Server database offers more robust data integrity and reporting capabilities. Custom Enables you to specify a custom storage provider. Off Disables session state.NET State Service. you must set the startup type to Automatic. d. Advantages Advantages of Client – Side State Management: 1. However. when configuring the ASP. StateServer Stores session state in a service called the ASP. Therefore.b. You should disable session state if you are not using it to improve performance. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. the ASP. each client that connects . SQLServer Stores session state in a SQL Server database.

Supports multiple Web servers: With client-side state management. sending that information back and forth to the client can increase bandwidth utilization and page load times. if a client switches servers in the middle of the session. potentially increasing your costs and reducing scalability. you should never use client-side state management to store confidential information. Therefore. 2. Pushing this burden to the clients removes that potential bottleneck. but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access). Advantages of Server – Side State Management: 1. the memory consumed by storing state management information can become a limiting factor.to the Web server consumes memory on the Web server. The increased bandwidth usage affects mobile clients most of all. 2. you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. because . Reduced bandwidth: If you store large amounts of state management information. You can use multiple servers with server-side state management. or authentication status. If a Web site has hundreds or thousands of simultaneous users. such as a password. With server-side state management. authorization level. the new server does not necessarily have access to the client’s state information.

Instead.0. A conceptual Entity Data Model (Entity-relationship model) is mapped to a datastore schema model.NET Framework 4. but was changed so extensively that it can be considered an entirely new product. ADO. Entity SQL. similar to the Java Persistence API. Using the Entity Data Model. Similarly.NET is sometimes considered an evolution of ActiveX Data Objects (ADO) technology. serves for querying the Entity Data Model (instead of the underlying datastore). the Entity Framework allows data to be treated as entities independently of their underlying datastore representations. you should store large amounts of state management data (say. allowing convenient access to each field through strongly-typed properties.NET Entity Framework is a set of data-access APIs for the Microsoft . An Entity Framework Entity is an object which has a key representing the primary key of a logical datastore entity. Describe the following: o o o Importance of ADO. Functionality exists in the Visual Studio IDE to create specialized subclasses of the DataSet classes for a particular database schema.NET Framework 4. This helps catch more programming errors at compiletime and makes the IDE's Intellisense feature more beneficial. released on January 2010.NET Entity Framework is included with . ADO.0 Service Pack 1 and Visual Studio 2010. though it can also access data in non-relational sources. targeting the version of ADO. more than 1 KB) on the server. 7.NET Framework.Net ADO.NET that ships with . It is commonly used by programmers to access and modify data stored in relational database systems.NET is a set of computer software components that programmers can use to access data and data services. Entity SQL and LINQ to Entities queries are converted internally into a Canonical Query Tree which is then converted into .NET Framework. Entity Framework ADO. It is a part of the base class library that is included with the Microsoft . a SQL-like language.Net Data Access Scenarios Disconnected Architectures Answer Importance of ADO.they often have very slow connections. LINQ extension LINQ to Entities provides typed querying on the Entity Data Model.

Private Sub ParmQueryButton_Click() Dim Qy As New rdoQuery Dim rs As rdoResultset Static FirstTime As Boolean If cn. Perform the query again with new parameters. This technique builds a temporary stored procedure (SP) behind the scenes that is referenced by the Requery method. pass in the first parameter. an RDO approach to the problem is shown. Data Access Scenarios Following are five data access scenarios that are more complex than simple Select queries. The temporary SP is dropped when the connection is closed. First. a SELECT statement that requires one or more parameters. the Refresh method re-executes the query. Since the object is appended to the rdoConnection object’s rdoQueries collection. Build a query that expects a parameter. then perform the query. This process is done in two steps: 1.Count = 0 Then FirstTime = True . • • • • • Executing a Parameter Query Performing a Parameter-Driven Stored Procedure Running a Stored Procedure That Returns Multiple Resultsets Performing an Action Query Running an Optimistic Batch Query Executing a Parameter Query RDO The procedure below illustrates a method for performing a parameterized Select query: that is. The first time the query is called.rdoQueries. Each subsequent time the procedure is called. you can reference it each time the procedure is called.g. 2.a query understandable to the underlying datastore (e. followed by the ADO solution so that you can compare how each is accomplished. The entities can use their relationships. RDO attempts to create a new RDO query object. with their changes committed back to the datastore. Each one is discussed in a succeeding topic. into SQL in the case of a relational database).

Close End Sub ADO This procedure is designed to perform a table-access query that accepts a parameter.ActiveConnection = cn With Cmd . you don't create an rdoQuery object that is kept in a collection off the rdoConnection object. If you tell ADO everything it needs to know about a query. you set up the Command properties. though. Note You don’t have to build the ADO Parameters collection in code.sql = "select * from authors where year_born = ?" Set Qy = cn.ShowData rs rs. It eliminates the need ' for ADO to fetch the parameter metrics from the server.Text If FirstTime Then Set rs = Qy. You use the "?" character (as in the previous RDO example) to indicate where the parameter is to be placed.CommandText = "select * from authors where year_born = ?" . ' With Parm . so queries run faster.Type = adInteger .CommandText = "" Then Cmd.Size = 4 .Requery End If rdoGrid1. Private Sub ParmQueryButton_Click() If Cmd. ADO gives you a lot of flexibility here—more.OpenResultset() FirstTime = False Else rs. in some cases than RDO. and each time thereafter. ' but can make execution faster. In this case. make sure that the Command is associated with an open connection so ADO can query the service provider (and the server) for the parameter's description. it won't have to perform informational queries against the database to get missing information. you simply execute the command after having changed the parameter.CommandType = adCmdText .CreateQuery("Pq". at the cost of a little code complexity. you instead use a stand-alone ADO Command object created (and scoped) earlier.CommandTimeout = 15 End With ' ' The following section of code is not required. since it's automatically created for you just like when you use RDO. The first time through. However. it is possible to do so. use the Execute method on the Command object. To run the query and create the resultset. and doing so can improve performance. sql) End If Qy(0) = QueryParam. If you elect to do it.

Private Sub RunSPButton_Click() Dim Qy As New rdoQuery Dim rs As rdoResultset sql = "{? = Call AuthorByYearBorn (?. you use the stand-alone rdoQuery object and assign the already open Connection to it.Append Parm End With End If Cmd. can be tricky to handle. The code below shows the RDO approach to these problems.OpenResultset() .Text Set rs = Cmd. Again. In addition..ShowData rs rs.sql = sql Qy. The rdoQuery object can then be used in subsequent calls to handle a parameter query.rdoParameters(0).Execute() ADOGrid1. including PRINT or RAISERROR statement return values. Stored procedures.Close End Sub Performing a Parameter-Driven Stored Procedure RDO Since many client/server applications depend heavily on stored procedures (SP). Note that the code requires us to include a correct ODBC "Call" statement. a data access interface should be able to perform them quickly and efficiently. In some cases.Direction = adParamInput . however.Parameters(0). It uses the same connections established in the earlier examples.Text Cmd. Some accommodations are made to the subsequent ADO design. Note also that the code does not attempt to refer to the return status argument. but it’s essential in the RDO codebased approach. this is not necessary in the UserConnection designer.Value = QueryParam. In some cases. more conventional arguments.Direction = rdParamReturnValue Qy(1) = "1947" Qy(2) = "1948" Set rs = Qy. while in others it’s better and easier to keep SPs simpler and more modular and use Visual Basic to tie them together. This value is not available until the resultset is fully populated. only then does SQL Server return this value. it performs a simple parameter-based SP and shows the results in the grid.?)}" Set Qy.ActiveConnection = cn Qy. stored procedures require management of OUTPUT and return status values and other.Value = QueryParam. Here.Parameters. it's better to create complex SPs. and these are noted. First. an SP can return several complex resultsets.

Each call to MoreResults closes the current resultset and moves to the next (if there is one).Parameter Dim Parm2 As New ADODB.ActiveConnection = cn Qy(0)="1947" Qy(1)="1948" Qy.Close End Sub ADO ADO has a lot of flexibility when it comes to performing stored procedures.Parameter Set Qy. Note that although ADO allows you to create your own parameters. As a result. But this flexibility comes at the cost of more code. RDO collections are 1-based.OpenResultset(sql) . it's not necessary to do so. it's possible to build your own ADODB Parameters collection.CommandType = adCmdStoredProc Qy. Note ADO collections are 0-based to match DAO. or else you won’t be able to use the product of your query.Command Dim Parm As New ADODB.ShowData rs End Sub Running a Stored Procedure That Returns Multiple Resultsets RDO This example illustrates how to perform a query that returns more than one resultset.ShowData rs ShowRows = rs. In RDO. It’s common for a stored procedure to return more than a single set of rows or a resultset that contains results from an action query. As with the previous example ("Performing a Parameter Query").Execute(ShowRows) ADOGrid1. In this case. you use the MoreResults method to step through the resultsets one at a time.CommandText = "AuthorByYearBorn" Set rs = Qy. Private Sub MultipleRSButton_Click() sql = "Select * from Authors Where year_born is not null. "AuthorByYearBorn". that returns a small resultset. Private Sub RunSPButton_Click() Dim Qy As New ADODB. you’re performing a simple two-argument SP. " _ & "Select * from Authors where year_born is null" Set rs = cn.rdoGrid1. your code must deal with each of the resultsets individually.RowCount rs.

vbYesNoCancel) If i = vbYes Then If rs. if the data provider supports it. you can use the Execute method to run the query directly.ShowData rs i = MsgBox("Ready for next results?". ADO also allows for multiple recordsets. as it does in RDO.Recordset sql = "Select * from Authors Where year_born is not null. The next recordset read doesn't overwrite the first one. Private Sub MultipleRSButton_Click() Dim rs As New ADODB. ADO’s approach is different from the RDO approach in that ADO uses the NextRecordset method in which you assign the next recordset in the batch to an ADO Recordset object. cn Do i = MsgBox("Ready for results?".) Note that you can use the RowsAffected property to find out the number of rows affected by this query. Private Sub ExecuteButton_Click() sql = "Begin Transaction " _ & " Update Authors " _ & " set Year_Born = 1900 where year_born is null" _ .rdoGrid1. or perform a maintenance operation (like SQL Server’s DBCC functions). " _ & "Select * from Authors where year_born is null" rs. it would be more efficient to create an SP to do it. you don’t need ODBC or SQL Server to create a temporary SP to run the query as it’s only being done once.NextRecordset End If Loop Until rs. In this case. vbYesNoCancel) If i = vbYes Then ADOGrid1.Open sql. (If this were a regular operation.State = adStateClosed End Sub Performing an Action Query RDO In case your application needs to manipulate tables directly.ShowData rs End If End If End Sub ADO The following code illustrates how to handle SPs that return multiple resultsets in ADO.ShowData rs Set rs = rs.MoreResults Then rdoGrid1.

MousePointer = vbDefault End Sub ADO When you need to perform an action query. In this case. but these properties improve data access performance. Generally.CommandType = adCmdText Qy.QueryTimeout = 45 Set rs = cnB. the code prompts the user for a new value and writes it to the resultset.ActiveConnection = cn Qy. Private Sub ExecuteButton_Click() Dim Qy As New ADODB. This is because ADO doesn’t have to poll the server to determine what to do. Private Sub BatchOpsButton_Click() Dim rs As rdoResultset sql = "Select * from Authors where year_born is null" rdoEnvironment. The changes are not made to the data.MousePointer = vbHourglass cn. however. you fetch a resultset using the ClientBatch cursor library and save the bookmarks for each row fetched.& " rollback transaction" Screen. In this case. just arguments passed to the object interface.CommandText = sql Qy. you can take advantage of the Execute method in ADO. until you perform the BatchUpdate method. you don’t see Visual Basic using arguments passed back to the application. rdConcurBatch) . vbInformation End Sub Running an Optimistic Batch Query RDO The following code demonstrates a query that can be used to drive a subsequent "optimistic batch update" operation. rdExecDirect ShowRows = cn. rdOpenStatic.Execute sql.Command Dim Rows As Long sql = "Begin Transaction " _ & " Update Authors " _ & " set Year_Born = 1900 where year_born is null" _ & " rollback transaction" Qy.CursorDriver = rdUseClientBatch cnB. or how to handle the query. Note that the new output argument for the Execute method returns the number of rows affected. you have to set a few more properties than you do in RDO.OpenResultset(sql. When the user chooses a row in the grid (where the rows are displayed).Execute Rows MsgBox Rows & " rows would have been affected".RowsAffected Screen.

Row) rs.Update Changes = Changes + 1 i = MsgBox("Commit all " & Changes & " changes?". vbYesNoCancel) Select Case i Case vbYes rs. "Author Age". vbYesNo) If i = vbYes Then rs. . author age). _ "1960") rs.rs.MoveFirst rdoGrid1.ShowData rs End Sub Performing an Update Operation Based on User Input The following code demonstrates how to gather user input (in this case.MoveLast: rs.MoveNext Loop rs.EOF bms(i) = rs.Bookmark = bms(rdoGrid1.CancelBatch (True) Else rs.RowCount + 1) As Variant Do Until rs. simply change the contents of a field and use the Update method to make the changes to the database. To achieve the same effect as the previous RDO example.MoveFirst ReDim bms(rs.CancelBatch End If End Select End Sub ADO In this batch operation.BatchUpdate Changes = 0 Case vbNo Exit Sub Case vbCancel Changes = 0 i = MsgBox("Cancel just this change (Yes) or all " & Changes & _ " made so far (No)?".Edit rs!Year_Born = NewValue rs. note that the routine used to change the chosen row in the R/W resultset doesn't require starting an "Edit" session. and then use this information to update the database in a batch update operation: Private Sub rdoGrid1_Click() Dim rs As rdoResultset Dim NewValue As Integer NewValue = InputBox("Enter new age -.1900 to 1997".Bookmark i=i+1 rs.

. Dataset is said to be disconnected module and datareader is said to be connected module. adLockBatchOptimistic rs.Open sql.Update Changes = Changes + 1 i = MsgBox("Commit all " & Changes & " changes?".1900 to 1997".Close End Sub Private Sub ADOGrid1_Click() Dim NewValue As Integer NewValue = InputBox("Enter new age -.Row) rs!Year_Born = NewValue rs. vbYesNo) If i = vbYes Then rs. the whole data is obtained at one strech and the modification is doen to the local table. _ "1960") rs.net.Bookmark i=i+1 rs.MoveFirst ADOGrid1.CancelBatch End If End Select End Sub Disconnected Architectures According to ADO.ShowData rs rs.EOF bms(i) = rs.MoveNext Loop rs. adOpenStatic. In connected module. "Author Age".CancelBatch (True) Else rs. In disconnected module.Bookmark = bms(ADOGrid1.MoveLast: rs.UpdateBatch Changes = 0 Case vbNo Exit Sub Case vbCancel Changes = 0 i = MsgBox("Cancel just this change (Yes) or all " & Changes & _ " made so far (No)?".RecordCount + 1) As Variant Do Until rs. vbYesNoCancel) Select Case i Case vbYes rs. cnB.MoveFirst ReDim bms(rs.Private Sub BatchOpsButton_Click() sql = "Select * from Authors where year_born is null" rs. Only one row is obtained each time from the database.

This object basically gives you a single table view of your data. this is crucial in creating efficient applications.config contains the master list that maps file types to HTTP handlers. ASP. This is nice when you are working with other business applications and also helps when you are working with firewalls because data is passed as HTML and XML. ADO. For Internet development.NET Security Model. ADO.dll runs in the same process as IIS—that is. The DataSet object will actually allow you to store the relational model of your database. With ADO. · ADO allows you to create client-side cursors only. of course.NET HTTP pipeline. Aspnet_isapi.NET gives you the choice of either using client-side or server-side cursors. inside Inetinfo.exe. Machine.NET (for example. This allows you to pull up customers and their orders. the request travels through the ASP. 8. · Whereas ADO allows you to persist records in XML format. whereas ADO.NET. Aspnet_isapi. · ADO has one main object that is used to reference data. ADO.dll. it is assigned to a specific application executing in a specific AppDomain.NET uses data in a disconnected fashion.dll forwards requests to Aspnet_wp. When you access data. where it is examined by various HTTP modules and ultimately processed by the HTTP handler that corresponds to the resource type requested.NET. When the request reaches the worker process. an ASPX file). classes actually handle the work of cursors. This makes ADO. . called the Recordset object. with a connection being used all the time.NET makes a copy of the data using XML. Once inside an AppDomain.NET. although you can join tables to create a new set of records.exe. When IIS receives a request for a file registered to ASP.NET efficient to use for Web applications. Describe the ASP. you have various objects that allow you to access data in various ways. it hands the request off to an ISAPI DLL named Aspnet_isapi. such as viewing and updating data.NET applications run in a separate process named Aspnet_wp. ADO. it is real-time. This is barring.NET only holds the connection open long enough to either pull down the data or to make any requested updates. This means that when you access data. This allows the developer to decide which is best.NET are different in several ways: · ADO works with connected data.ADO and ADO. accessing/updating the data in each related table individually. ASP.exe using a named pipe.NET allows you to manipulate your data using XML as the primary means. It's also decent for desktop applications. you programming special routines to pull all your data into temporary tables. In ADO.NET Security Figure 2 shows the relationship between IIS and ASP.

such as . Slated for release in 2002 with Windows Server 2003.NET is installed. it also forwards the access token that it obtained from IIS. By default.NET performs before processing the request means you can deny Bob access to an ASPX file simply by tagging that file with an ACL that denies Bob read access.NET use Aspnet_wp. the developer. Unless you specify otherwise.exe.aspx has an ACL that denies read permission to Bob. Microsoft plans to connect Inetinfo. for example.exe runs as ASPNET. Before processing the request by sending it through the targeted application's HTTP pipeline.NET performs this ACL check regardless of whether impersonation is enabled in ASP. The importance of these actions cannot be overstated. In IIS 6. by default. Bob). If. Among other things. The right choice depends on what the application is designed to do and how it's designed to do it.NET. I'll provide some background to enrich your understanding.0 will feature a more robust security model that gives IIS administrators the ability to segregate applications into surrogate processes very much like Aspnet_wp.exe. the application can impersonate the caller and protect resources guarded by ACLs from code executed during the request.NET fails the request with an access denied error. requests executed by ASP. At the time of this writing.exe's identity. Aspnet_wp. The fact that ASP.exe.Figure 2 Relationship between IIS and ASP The architecture in Figure 2 changes somewhat when ASP. the access token represents Bob.0. That access token is typically one of the following: an IUSR_machinename token representing an unauthenticated user. this means that barring configuration changes.NET application can't perform.dll forwards an HTTP request to Aspnet_wp. The ACL check that ASP. IIS 6. a special account that's set up when ASP.exe to worker processes using Local Procedures Calls (LPCs) rather than named pipes. there are certain actions an ASP. if desired. or a token representing an authenticated security principal (for example. ASPNET is a member of the Users group. requests run as ASPNET. What does all of this have to do with security? When Aspnet_isapi. there is no Aspnet_wp. but restricted enough to prevent certain kinds of attacks.exe does the following: • It performs an ACL check on the requested resource using the access token presented to it.aspx.NET makes the caller's access token available for impersonation purposes means you.0. IIS provides the worker process.NET is paired with IIS 6. then ASP. the request is a GET command asking for Foo. Therefore. and Foo. which means it's privileged enough to perform most of the actions a legitimate application might want to perform. have some latitude in deciding what identity to use when processing the request. • It makes the access token available to the application that handles the request so that. ASP. instead. Aspnet_wp.

In that case.NET application that must have widerranging permissions than those afforded ASPNET—for example. You can configure Aspnet_wp.NET security will be far easier to grasp once you've experienced it firsthand. Suppose you write an ASP. a technique known as impersonation. In the meantime.exe to run as SYSTEM by changing the statement <processModel userName="machine" .NET requests will default to Network Service rather than ASPNET.. Clearly. but that was changed shortly before the product shipped. you'll use operating system ACLs to restrict access to pages that aren't intended for everyone.NET was in beta. impersonation won't buy you much because IUSR_machinename is a weak account that enjoys few privileges on the host machine.. • If you're building an Internet application that serves the general public but want to secure access to certain pages.config file or modifying the <identity> element already present in Machine. depending on the needs of the application. ASP. ASP.config: <identity impersonate="true" /> If IIS assigns a request the identity of IUSR_machinename.config to read: <processModel userName="SYSTEM" .0. modify your ACLs to allow access to Network Service rather than ASPNET. • If you're building an intranet application or any application whose permissions are based on mapping incoming requests to Windows accounts on your server. Aspnet_wp. Another possible complication arises from the fact that in IIS 6. In that case.. /> This enables your application to do almost anything it wants on the host machine.. SYSTEM was the default when ASP.exe can be configured to run as a principal other than ASPNET. You may or may not enable impersonation. the freedom to write to any part of the registry. don't fret. you'll probably use Windows authentication and ACL authorization. If your head is spinning right now trying to make sense of it all. but it also makes ASP.0.NET less resistant to attacks.NET worker process and to the requests that it executes play crucial roles in determining how successful an application is in carrying out its appointed mission. /> in Machine. the identities assigned to the ASP. To further complicate matters. here are some guidelines to help you sort through the options and figure out which of them really matter for a given deployment scenario: • If your application requires no special protection—if all of its pages can be freely browsed by anyone and none are personalized for individual users—you needn't bother with application-level security.web> section of a top-level Web. But if Windows authentication is enabled and IIS presents ASP. impersonation ensures that the application can't do anything on the Web server that the requestor isn't allowed to do. Just grant Everyone access to the application's files and be done with it. you'll most likely use forms authentication and URL authorization.NET with a token representing the actual requestor. Impersonation is enabled by including the following statement in the <system.modifying entries in the HKEY_LOCAL_MACHINE section of the registry. If you use ACLs to allow access to the ASPNET account while denying access to other security principals and find that requests mysteriously fail with access denied errors after you install IIS 6. you'll leave impersonation disabled and rely on credentials . The other option is to execute the request using the access token provided by IIS.

always grant the ASPNET account—or whatever account Aspnet_wp.NET application.config to protect them. ASP.entered in login forms as the basis for authorizations. Subject Code Subject Name : MC 0081 : .exe runs as—read access to them.(DOT) Net Technologies Assignment No: 02 Marks: 40 . Many of the aformentioned issues regarding IIS and access tokens fall by the wayside in this scenario because you grant Everyone access to the application's files and rely on URL authorizations in Web.NET itself will be unable to read them and you'll experience all kinds of access denied errors that you probably didn't expect. Otherwise. A final thought to keep in mind is that if you use ACLs to limit access to files and directories in an ASP.

they might exist as the executable (. shared assemblies are not copied in the private folders of each calling assembly. Write about Assemblies in Dot Net answer The . and manifest. Dot NET assemblies may or may not be executable. 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.exe) file or dynamic link library (DLL) file.NET.NET have worked a lot on the component (assembly) resolution.NET. The designers of . Shared assemblies (also called strong named assemblies) are copied to a single location (usually the Global assembly cache). An assembly can be a single file or it may consist of the multiple files. All the .. In case of multi-file. version. Hence. Each shared assembly has a four part name including its face name.NET assemblies contain the definition of types.Credits : 04 Book ID: B 0974 Each question carries FIVE marks 5X 8 = 40 1. For all calling assemblies within the same application. public key token and culture information.e. the same copy of the shared assembly is used from its original location. There are two kind of assemblies in . there is one master module containing the manifest while other . meta-data. versioning information for the type. Private assemblies are simple and copied with each calling assemblies in the calling assemblies folder.NET assembly is the standard for components developed with the Microsoft. private and shared. i.

Every assembly file contains information about itself.NET architecture along with reflections and attributes. What is assembly manifest? • • • Assembly manifest is a data structure which stores information about an assembly This information is stored within the assembly file(DLL/EXE) itself The information includes version information. What is an assembly? • • • • • • • • An Assembly is a logical unit of code Assembly physically exist as DLLs or EXEs One assembly can contain one or more files The constituent files can include any file types like image files. list of constituent files etc. Suppose you created a DLL which encapsulates your business logic. but unfortunately very few people take interest in learning such theoretical looking topics. . text files etc.NET is a sub part of a multi-file . A module in . Thus the assembly is private to your application.assemblies exist as non-manifest modules. Assembly is one of the most interesting and extremely useful areas of . What is private and shared assembly? The assembly which is used only by a single application is called as private assembly. along with DLLs or EXEs When you compile your source code by default the exe/dll generated is actually an assembly Unless your code is bundled as assembly it can not be used in any other application When you talk about version of a component you are actually talking about version of the assembly to which the component belongs. This DLL will be used by your client application only and not by any other application. In order to run the application properly your DLL must reside in the same folder in which the client application is installed.NET assembly. This information is called as Assembly Manifest.

build. How assemblies avoid DLL Hell? As stated earlier most of the assemblies are private. Now. Hence each client application refers assemblies from its own installation folder. All assemblies has a version number in the form: major. Such assemblies are called as shared assemblies. It is located under <drive>:\WinNT\Assembly folder. What is Global Assembly Cache? Global assembly cache is nothing but a special disk folder where all the shared assemblies will be kept. When the client application requests assembly the requested version number is matched against available versions and the version matching major and minor version numbers and having most latest build and revision number are supplied. Consider following example : • • • • • • • You created assembly Assembly1 You also created a client application which uses Assembly1 say Client1 You installed the client in C:\MyApp1 and also placed Assembly1 in this folder After some days you changed Assembly1 You now created another application Client2 which uses this changed Assembly1 You installed Client2 in C:\MyApp2 and also placed changed Assembly1 in this folder Since both the clients are referring to their own versions of Assembly1 everything goes on smoothly Now consider the case when you develop assembly that is shared one.minor. even though there are multiple versions of same assembly they will not conflict with each other. So.Suppose that you are creating a general purpose DLL which provides functionality which will be used by variety of applications.revision If you change the original assembly the changed version will be considered compatible with existing one if the major and minor versions of both the assemblies match. In this case it is important to know how assemblies are versioned. . instead of each client application having its own copy of DLL you can place the DLL in 'global assembly cache'.

These keys are generated using a utility called SN. How do I place the assembly in shared cache? Microsoft has provided a utility called AL.NET solution explorer and change it to include following lines : [assembly:AssemblyKeyFile("file_path")] Now recompile the project and the assembly will be signed for you. .exe to actually place your assembly in shared cache. How do I sign my DLL/EXE? Before placing the assembly into shared cache you need to sign it using the keys we just generated. Open the file from VS. You mention the signing information in a special file called AssemblyInfo.How do I create shared assemblies? Following steps are involved in creating shared assemblies : • • • • • Create your DLL/EXE source code Generate unique assembly name using SN utility Sign your DLL/EXE with the private key by modifying AssemblyInfo file Compile your DLL/EXE Place the resultant DLL/EXE in global assembly cache using AL utility How do I create unique assembly name? Microsoft now uses a public-private key pair to uniquely identify an assembly.keyfile switch. The most common syntax of is : sn -k mykeyfile.exe (SN stands for shared name). Note : You can also supply the key file information during command line compilation via /a.key Where k represents that we want to generate a key and the file name followed is the file in which the keys will be stored.

Hands On.dll Now your dll will be placed at proper location by the utility.. Now.NET component called SampleGAC ( GAC stands for Global Assembly Cache). sn -k sample. It just includes one method which returns a string. • Step 1 : Creating our sample component Here is the code for the component.keyfile:sample.key. We will sign our component with this key file and place it in Global Assembly Cache. wee will sign the assembly with the key file we just created. In this example we will create a VB.AL /i:my_dll. imports system namespace BAJComponents public class Sample public function GetData() as string return "hello world" end function end class end namespace • Step 2 : Generate a key file To generate the key file issue following command at command prompt.key This will generate the key file in the same folder • Step 3 : Sign your component with the key Now.vb /t:library /a.. vbc sampleGAC. We will also create a key file named sample.key . that we have understood the basics of assemblies let us apply our knowledge by developing a simple shared assembly.

• Step 4 : Host the signed assembly in Global Assembly Cache We will use AL utility to place the assembly in Global Assembly Cache. copy the resulting EXE in any other folder and run it.writeline(s) end sub end class Compile above code using : vbc sampletest. It will display "Hello World" indicating that it is using our shared assembly. we will create a sample client application which uses our shared assembly.vb /t:exe /r:<assembly_dll_path_here> Now. Just create a sample code as listed below : imports system imports BAJComponents public class SampleTest shared sub main() dim x as new sample dim s as string="x".dll After hosting the assembly just go to WINNT\Assembly folder and you will find your assembly listed there. . • Step 5 : Test that our assembly works Now. Note how the assembly folder is treated differently that normal folders. AL /i:sampleGAC.getdata() console.

if (Age < 18) { Console. In case. A department head. When . would have a property denoting the department he heads.WriteLine("You are not permitted in here. there would be various fields associated with it. etc. else construct is very simple and follows the pattern . } Lets step through the code. Finally the value is stored in the integer variable Age. The working of if . the age entered by the user is read using ReadLine() (as a string) and converted to an integer using the ToInt32 function. } else { Console. else Syntax:if ( < condition > ) { statements } else { statements } The else part is optional and can be omitted. int Age = Convert. C# provides the following conditional constructs:if .").. We use conditional branching in such a scenario. for example. there is no else statement. otherwise the statements inside the else block are executed.2.ToInt32(Console. Depending upon the post of the employee.ReadLine()). At line 2.").WriteLine("You may come in.. Write a C# program to perform basic arithmetic operations answer a program to store the details of employees. Here’s an example:CODE Console.If this is true I’ll do that or else I’ll do something else. The statements included within the if block are executed when the condition specified in if. the execution flow continues to the proceeding statements.WriteLine("Enter your age:"). Line 1 displays a message Enter your age. is true.

the execution reaches line 3, the expression inside if is evaluated. If the user supplied an age less than 18, the execution flow would move to line 5 - Console.WriteLine("You are not permitted in here."); and the message You are not permitted in here would be displayed. In the other scenario, when the age would be either equal to or greater than 18, line 7 would be executed and the message You may come in will be displayed. The condition inside the if statement can be composed of a complex expression chained by the logical operators. For Example:CODE Console.WriteLine("Enter your age:"); int Age = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Are you with your guardian? (True/False)"); bool WithGuardian = Convert.ToBoolean(Console.ReadLine()); if ((Age < 18 ) && (WithGuardian = false)) { Console.WriteLine("You are not permitted in here."); } else { Console.WriteLine("You may come in."); } At line 4 the user's response of whether he/she is with a guardian would be stored inside the boolean variable WithGuardian. Notice that ToBoolean function is used to convert the input to boolean (True/False) value. At line 5, the complex expression will be evaluated. The expression is made up of two sub-expressions: Age < 18 and WithGuardian = false. These two expressions are joined with the logical AND operator (&&). Therefore, when both of the expressions amount to true, the entire expression would evaluate to true and the message - You are not permitted in here will be displayed. For any other combination, the final expression would be equivalent to false and the message - You may come in will be displayed. A number of conditions can be chained by using else if as follows:CODE Console.WriteLine("Enter your salary"); int Salary = Convert.ToInt32(Console.ReadLine()); if (Salary > 250000) { Console.WriteLine("Welcome Mr. CEO"); } else if (Salary > 200000)

{ Console.WriteLine("Welcome Mr. Chairman"); } else if (Salary > 0) { Console.WriteLine("Welcome Programmer"); } else { Console.WriteLine("Welcome dear Customer"); } In this case, if the salary supplied by the user is greater than 250000, the message Welcome Mr. CEO will be displayed otherwise if the Salary is greater than 2000000 then the output will be Welcome Mr. Chairman else if the salary is greater than 0, the message - Welcome Programmer will be displayed. For any other value (Salary less than 1), the statements inside the else block would be executed and Welcome dear Customer will be the output. switch .. case Construct Switch case facilitates easy branching when the condition is pertaining to a single expression. Each supplied Value is preceded by a case construct. Syntax:switch (< expression >) { case Expression_1; statements break; case Expression_2; statements break; …. } break is a C# keyword, which is used to exit the body of a switch, for or while loop. Equivalent to the else construct is the default case. Statements within the default case are executed when no other condition holds true. Example:-

CODE Console.WriteLine("Enter the month (mm)"); int Month = Convert.ToInt32(Console.ReadLine()); switch (Month) { case 1: Console.WriteLine("January"); break; case 2: Console.WriteLine("February"); break; case 3: Console.WriteLine("March"); break; case 4: Console.WriteLine("April"); break; case 5: Console.WriteLine("May"); break; case 6: Console.WriteLine("June"); break; case 7: Console.WriteLine("July"); break; case 8: Console.WriteLine("August"); break; case 9: Console.WriteLine("September"); break; case 10: Console.WriteLine("October"); break; case 11:

WriteLine("The number is prime.WriteLine("Enter a number (1-10)"). } . case 1: case 9: Console."). break.Console. break. Multiple Values can be made to lead to the same block of statements by excluding the break statement. case 4: case 6: case 8: Console. break.")."). the default case will be executed and the message There are only 12 Months.ReadLine())."). break. default: Console. break. } Depending on the value entered by the user (1-12). switch (Num) { case 2: case 3: case 5: case 7: Console.WriteLine("The number is Even"). case 12: Console.WriteLine("December"). the appropriate month will be displayed.WriteLine("There are only 12 Months. break. break. CODE Console. For any other value.WriteLine("The number is odd.WriteLine("The number is not in range. will be displayed. default: Console.WriteLine("November").ToInt32(Console. int Num = Convert.

So.10. CODE for(int I = 1. you could remove the condition part to make the loop infinite or you can include the increment statement within the body of the for statement itself (inside the { and } brackets). } Lets break the for statement down:Initialization: int I = 1 Condition: I <= 1000 Increment: I++ All the parts here are optional and can be left out. initialize it to the starting number (1) and keep incrementing its value by 1 until the number exceeds the end point (1000).< condition >. above the for statement and leave out the initialization block.1000. C# supports 3 kinds of loops which are discussed below:The for loop This loop is generally used for arithmetic operations. I <= 1000. displaying the numbers on screen.1000? Using the computer’s iterative power is a much better approach. we declare a counter variable (preferably single character variable like I). where we are aware of the starting and end point of the loop. I++).< increment/decrement >) { statements } To print numbers within a range. say 1 . Suppose you want to print numbers from 1 . we would have the body of the loop where the operation would be done. in this case. I <= 1000.Looping A Set of instructions that are repeated is called a loop. you can initialize the variable I.WriteLine statement for each of the 10 numbers. what if you had to print numbers from 1 . But. You could do that using Console. . Syntax of for loop is as follows:for(< initialization >.WriteLine(I). I++) { Console. The code would look like this (. Off course. Similarly.

is stored in Continue. Take a look at the code snippet below. Below is the code to print numbers from 1 . actually it can. } We have declared a boolean variable Continue which we use to check whether to continue repeating the process. so that the loop is executed for the first time.ReadLine()). I <= 1000.WriteLine("Continue (True/False)"). These need to be implemented additionally. It has been initialized to true. can also be done using the while loop. CODE int I = 1. you want to continue inputting values from the user as long he wishes to. Such a for statement is followed by the semicolon. while(I <= 1000) . Console. The user’s choice of whether to continue with the loop or not.1000 using while. the statements within the body of the while loop would keep on executing. The while loop The for loop cannot be used when the range of the loop is unknown (Well. This can be easily implemented by the while statement.ToBoolean(Console. Say.WriteLine("Please Enter a Number"). Console.ToInt32(Console. Continue = Convert.Another variation of a for statement is the empty loop which does not contain any body: for(int I = 1. Syntax:while(< condition >) { statements } We don’t have initialization and increment/decrement slot over here. but the approach would not be logical). while(Continue == true) { int A. As long as the user enters true.ReadLine()). I++). CODE bool Continue = true. A = Convert. Anything that can be implemented using for loop.

one needs to use the appropriate loop for the job. Console. which causes the server to load . 3. Continue = Convert.ToBoolean(Console. However. } The do while loop The do while loop is a variation of the while loop in which the condition is evaluated at the end of the loop. either of the three types of loops can be used to do an iteration. A = Convert.WriteLine(I). The bool variable continue stores the user’s choice. from beginning to end. The code for which is given below. for the first iteration. Recall the first while program we did.ToInt32(Console. do { int A. we had to initialize continue with the value true so that the loop is executed for the first time. Use the for loop for arithmetic operations. it does not store the choice. Although. Answer Every request for a page made from a web server causes a chain of events at the server.WriteLine("Continue (True/False)").WriteLine("Please Enter a Number"). I++. Describe the Web form life cycle.{ Console. } while(Continue == true). Console.ReadLine()). These events.ReadLine()). constitute the life cycle of the page and all its components. CODE bool Continue. Note: The while part in the do while loop needs to be terminated with the semicolon. In such a scenario. the loop is executed at least once. A better approach would be to use the do while loop and check the condition at the end. The life cycle begins with a request for the page. Thus. while loop for non-arithmetic ones and the do-while loop when the loop must execute at least once.

Load: CreateChildControls( ) is called. Now it is saved back to the hidden variable. to create and initialize server controls in the control tree.NET server: Initialize: Initialize is the first phase in the life cycle for any page or control. to create and initialize . the persisted view state was loaded from the hidden variable. When the request is complete. You can modify the load phase by handling the Load event with the OnLoad method. and the form controls show client-side data. The ViewState information comes from a hidden variable on the control. persisting as a string object that will complete the round trip to the client. Handle Postback Events: The client-side event that caused the postback is handled. It is essentially your last chance to modify the output prior to rendering using the OnPreRender( ) method.it. You can override this using the SaveViewState( ) method. each of which you can handle yourself or leave to default handling by the ASP. the goal is to render appropriate HTML output back to the requesting browser.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. and the ViewState property is set. Send Postback Change Modifications: If there are any state changes between the current state and the previous state. Render: This is where the output to be sent back to the client browser is generated. the page is unloaded. Save State: Near the beginning of the life cycle. Process Postback Data: During this phase. If any of this data results in a requirement to update the ViewState. State is restored. This can be modified via the LoadViewState( ) method. CreateChildControls( ) is called. the data sent to the server in the posting is processed. This allows ASP. that update is performed via the LoadPostData( ) method. It is here that you initialize any settings needed for the duration of the incoming request. change events are raised via the RaisePostDataChangedEvent( ) method. You can override it using the Render method. The input string from this hidden variable is parsed by the page framework. if necessary. Load View State: The ViewState property of the control is populated. The life cycle of a page is marked by the following events. used to persist the state across round trips to the server. PreRender: This is the phase just before the output is rendered to the browser. if necessary. From one end of the life cycle to the other.

Write about the creation of Master Pages in ASP. period. Master-Page Framework. consistent web-sites etc. but still long way to go).NET Page Templates . every where. You canmodify it using the Dispose( ) method. Look's a big deal now :). Dispose: This is the last phase of the life cycle. Apart from some CSS style-sheet for consistency. It gives you an opportunity to do any final cleanup and release references to any expensive resources.server controls in the control tree. such as database connections. One of the use cases while we develop web application is that User needs a consistent look and feel. etc� We see good-looking �sexy� web sites.Net applications answer Master Page Framework Development: Every thing starts with a use case in Object Oriented Software Engineering.. pluggable and modifiable visually! (Sounds great! what a wish :)) There is no such thing existing in ASP. through out. ASP. how much maintenance cost is required if we need one change for the whole of the web site. but we don�t see one thing (well! you can�t see that). Now what a deal??? We see every day.NET (Whidbey. . which should be extendible. 4.Using Inheritance by Peter Provost. I started looking around the web and found some interesting articles: • • Master Your Site Design with Visual Inheritance and Page Templates by Fritz Onion. does have one. easy to use. what else we need. a framework.

I call it POAD because my application has a peculiar look and feel that it follows a pattern. Let's move further! Here are the steps involved in designing the POAD based softwares. POAD means you have entire prototypic pattern. Elaborate Objects while designing them. menus/submenus. not design patterns. in the first place. I was looking for something like a reusable/extendible Framework. The approach I took.These articles are very good starting points. I took the responsibility of redesigning the whole wheel that never existed. Find Objects responsible for doing the job. what I devised is. Write test cases. your application will follow. so I took the entire valuable advises from them and went further.). sounds good. navigator. since. how is that . with some examples. Find design patterns needed. Steps Involved: . How�s that. but will be overridden later for concrete structure of it (the concept needs a whole article and I would write later. hopefully next month). • • • • • • Draw the whole abstract pattern your framework would provide. footer. So the master-page has header. Pattern Oriented Architecture and Design (POAD). Find relationships between them. and find functionality for them. and content place-holders that would be filled in later as needed for concrete pages. they are different.

e. Here is the prototypic pattern of our Framework: Figure 1 (Master-Page Layout/pattern) Master Web User-Control If we decompose this pattern into objects. there should be something like a master-page that is composed of the placeholders. menus. logo. i.. navigator. . it�s being clear that we should have something like skeleton or template for the place holders. and contents etc. footer.Draw the whole abstract pattern your framework would provide. like header.

ascx"/> </appSettings> . so we�ll dynamically load it at run time using web. our model would have a Master Page that in turn is composed of Master UserControl (PageUserControlBase) that in turn is composed of placeholders. We want this user-control to be pluggable at run time. Call it a Master user-control. great! :) Now the visual part is decided that we provide using usercontrol or so. Now. we could safely put these place holders in a user control (PageUserControlBase) that in turn contains all the place holders. where you define your layout for these contents. like this: Getting closer.config like this: Collapse | Copy Code <appSettings> <add key="MasterPageUserControl" value="MasterPageUserControl.Since our plan is to change these place holders visually.

so that we can extend it in future.Our Framework encapsulates all the functionality of the Master User-Control (PageUserControlBase) class in an assembly as a base/abstract class. if we need it. Here is how it would look like: .

With this approach. all we need is to extend PageUserControlBase class and use it: Collapse | Copy Code <%@ Control Inherits="Shams. we decide with some other look and feel of the master user control.PageUserControl" %> Or use it like this: Collapse | Copy Code <%@ Control Inherits="Shams.Web.MasterPages. will provide us access to WebControls. Here is how the PageUserControlBase.PlaceHolder(s).UI.MasterPages. if in future.UI.Web.ascx should the look like: .PageUserControlExtra" %> PageUserControl or PageUserControlExtra.

.

We have a long way to go. What else would be needed. right? Yes. it is. is pluggable through the web. extendible and pluggable Framework. and further.config. and is ready.This was straightforward. great :). we are right on target. well lot of work still there? All we have done so far is we provided a consistent look and feel through pluggable Master User Control-Base. Let's first analyze how the HTML/aspx page looks like: . So while designing the Framework. Now the visual component can easily be extended.

and Part-D in it. Part-D: . Page title. Part-C. We put all the server-controls in this form (part-C). let�s examine them closely: • • • • Part A: . [or any controls]. This Form object would be used to add our famous master-user-control or Part-C in it. Part-B: . If you look at the Control class.Master User-Control area.HTML footer area. and HTML body etc.Form area. our master .HtmlForm object. This extended Custom Control.Web.You can see the page itself has four parts. Master Custom-Control: Every page can have one and only one HTML Form.UI. describing code-behind language. what we need is another object that would encapsulate all these HTML-Rendering stuff shown above. Part-C: . we named it PageControlBase. The Control is a composite that means we can put other controls in it. Meta info.HTML Header. So.HtmlControls. Part-B. it would be a good starting point to start with a Custom control by extending the Control Object. Now. it has all the functionality we are looking for. So. will provide HTML rendering capability as well as it would have a System. like Part-A.

derived from UI. Here is the UML diagram that demonstrates all these: Now that we have a pluggable Master-User-Control. a custom control that will create all of the HTML parts is necessary. and master-user-control.Page class:- Design Patterns used in Master-Page Framework . What we need is an integrator class that will insert Master User-Control into Custom control form and attach it to the Master-Page.page would be composed of some master custom control. And that�s the MasterPageBase class.

Template Design Pattern is used in two occasions: .Control ParentControl(). void void void void void HtmlRenderStarts(). PreHtmlRender(). /// <summary> /// The title page can be set with this property /// </summary> string PageTitle { get. set.UI.Web. } /// <summary> /// </summary> string MetaInfo { get.When you are planning for any Framework that is based on some prototype or follow POAD. PostHtmlRender(). the most effective pattern is the Template design pattern. HtmlRenderEnds(). Here is the code that demonstrates this pattern: Collapse | Copy Code public interface IPageControl { System. } } We defined the sequence/pattern of execution that would later be overridden by the derived classes. HtmlRender(). set.

• Defined template in the Custom control:- • And here is the other place where the same design pattern is used: .

we can do it. if we have plan to put some business logic around their creation. like Control Class is itself based on composite pattern. Composite Pattern in its simple form is a list of list of objects. Composite Pattern is built in with the . and should provide one place.Other patterns that are used are Factory and Composite Design Patterns. I used the Control class as my starting point. without breaking the existing code. Instead of reinventing my own containers for objects.NET Framework. The Factory pattern is used to create classes. .

and override the stuff you want to change in your concrete classes.So that�s it. All you need is to derive your page from the MasterPage class. How we do it is shown using UML Diagram here: . we are done with the Framework.

Creation of Master Page Skeleton: - .Let�s discuss some typical scenarios we�ll come across while doing implementation: 1.

ascx"/> </appSettings> . Here is the code snippet as an example: Here is the output we�ll get. Collapse | Copy Code <appSettings> <add key="MasterPageUserControl" value="MasterPageUserControl.config.e. all we need is to derive from MasterPageBase. i. it�s a master-page skeleton. The visual settings are from web.As discussed earlier..

Here is the not so detailed objects sequence diagram.If you have some other-layout in your mind for your MasterPage. for the above scenario:- 2.config. you can create your own user control and change the signature in the web. Here is the example code snippet for this:- . Creation of MasterPage from MasterPage Skeleton:We would create a MasterPage class from MasterPageBase and override the placeholders with our own UserControls.

but this is not the same case with visual studio 2005.0 and 3.asax file in Asp.asax file is default and if you want to add it you have to add manually. So till here we are clear that in visual studio 2005 and 2008 global.> press "Add" Button .asax file by default. 3. You need to explicitly add global. Explain the importance and applications of Global.Net 2.asax file to make use of this.5? Its simple . How to create or add global. Right click on the solution explorer in visual studio editor -> Add New Item -> Select "Global Application Class" .asax Application file.1 when you create web application with visual studio 2003 editor it will automatically create global. 2008 it will not create global.net 1. Answer In Asp.5.0.asax file. But here I want to make it clear that all the event and method will fired according to it nature.

asax file. Application_Start Application_End Application_Error Session_Start Session_End Like This view source print? 01 02 <%@ Application Language="C#" %> <script runat="server"> .Now you have added global. By default you can see that below event method is automatically available in your global.asax file in you web application.

This method will be fired when When application started shut down. Session_End . That means If the IIS recycle or restart again then this event also will be fired. This event method is one of most important method used by most of the web developwer.This method will get fired when First time the application and web server (eg. If session mode is set to StateServer // or SQLServer. Session_Start . Application_End . // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web. EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender. EventArgs e) { // Code that runs when a new session is started } void Session_End(object sender.This event will be fired when a new user request a page from the server.03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 void Application_Start(object sender.This event will be fired when there is any exception occurred in the application during run time. the event is not raised.config file. But make sure this event willl only fired when Session Mode is "InProc" as we know . } </script> one. EventArgs e) { // Code that runs when a session ends. Now we will explore each above listed method and its importance one by Application_Start . Application_Error . EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender. IIS ) starts. EventArgs e) { // Code that runs on application startup } void Application_End(object sender.This code will be fired when session end for a use. That means for every user request the page this event will b fired.

Describe the importance of Application State in ASP. As such.UnLock(). which programmers can use to build dynamic web sites.asax file. view source print? 01 02 03 04 05 06 07 08 09 10 11 12 13 14 public void Application_Start(object sender.Net applications. } 6. it has to implement state management on its own. EventArgs e) { //Create Application object and assign 0 to it Application["TotalHits"] = 0. web applications and web services.Lock(). Answer ASP.NET is a web application framework developed and marketed by Microsoft. StateServer. ASP. //Increment by 1 Application object every time when session starts Application["TotalHits"] = Application["TotalHits"] + 1. We are going to make use of Application_Start event and Session_Start even to achieve hit counter. ASP. For more information on Session in Asp. //Unlock the Application Object using Unlock() method if Application object Application. EventArgs e) { //Lock the Application using Lock method of application Application. SqlServer mode to store session.there are three session state InProc. if the application uses stateful interaction.NET applications are hosted in a web server and are accessed over the stateless HTTP protocol. Create Hits counter of web application.NET provides various .net Please Refer this Tutorial Now let's see real time example of the above events present in global.NET and its State of Application ASP. } public void Session_Start(object sender.

Because the state management happens outside the ASP.NET process.NET runs a separate Windows service that maintains the state variables. ASP. the session variables are maintained within the ASP. These variables are unique to different instances of a user session.NET process is recycled or shut down. Since the application is recycled from time to time this mode is not recommended for critical applications.net developer. and SqlServer Mode. Session variables can be set to be automatically destroyed after a defined time of inactivity. session state. ASP. Session state is a collection of user-defined session variables. Session variables can be persisted across ASP.NET instances to share the same state server. thus allowing an ASP. Learn more about these with the austin . Application state variables are identified by names.NET supports three modes of persistence for session variables: the In Process Mode.net developer. the controls render at their last state. these state management includes application state. These are set and initialized when the Application_OnStart event fires on the loading of the first instance of the applications and are available till the last instance exits.net developer.NET process shutdowns in this mode as well. Learn more about this with the austin . and are accessed using the Session collection. View state refers to the page-level state management mechanism. accessible using SQL. however.NET applications to maintain the state of the web form controls and widgets. This is the fastest way. and view state. In the SqlServer Mode. Application state variables are accessed using the Applications collection. In ASPState Mode. The server sends back the variable so that when the page is re-rendered.NET process.NET applications.functionality for state management in ASP. the state variables are stored in a database server. ASPState Mode. Application state is a collection of user-defined variables that are shared by all invocations of an ASP.NET application. this has a negative impact on performance. but it allows multiple ASP. Learn more about this with the austin . On the In Process Mode. even if the session does not end. which is utilized by the HTML pages emitted by ASP.NET application to be load-balanced and scaled out on multiple servers. in this mode the variables are destroyed when the ASP. which are persisted during a user session. which provides a wrapper for the application state variables. The main advantage of this mode is it would allow the application to balance load on a server cluster while sharing sessions between servers. .

UserID. Dim settings As ConnectionStringSettings = _ ConfigurationManager. 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. The configuration file is defined as follows. 7.config or web. Example This example demonstrates retrieving a partial connection string from a configuration file and completing it by setting the DataSource.Data. <connectionStrings> <clear/> <add name="partialConnectString" connectionString="Initial Catalog=Northwind.ConnectionStrings("partialConnectString") If Not settings Is Nothing Then ' Retrieve the partial connection string. For example. the name of the database might be known in advance.ConnectionString Console. The states of individual controls are decoded at the server.NET pages using the ViewState collection. they can be stored in a configuration file and retrieved at run time to construct a complete connection string.SqlClient" /> </connectionStrings> Private Sub BuildConnectionString(ByVal dataSource As String. The partial connection string can be stored in a configuration file and retrieved at run time. connectString) ' Create a new SqlConnectionStringBuilder based on the ' partial connection string retrieved from the config file. _ ByVal userName As String.Net applications. but not the name of the server.WriteLine("Original: {0}"." providerName="System. One of the overloaded constructors for a connection string builder takes a String as an argument.At the server side. Dim connectString As String = settings. and Password properties of the SqlConnectionStringBuilder. . which allows you to supply a partial connection string which can then be completed from user input. Write the basic steps in building Connection Strings from Configuration Files in ADO. ByVal userPassword As String) ' Retrieve the partial connection string named databaseConnection ' from the application's app.config file. Answer If certain elements of a connection string are known ahead of time. if the processing results in updating the state of any control. the application might change the viewstate. and are available for use in ASP.

This ticket contains anything from just a valid session identification access token to customized personalization values. Upon submitting the form.g. . a secured page from your site). 2. Forms Authentication is one of three authentication providers. Also note that because the authentication mode in the ASP. Related Reading Forms Authentication Flow 1. builder. therefore making the identity persistent). This authorization cookie contains the user's credentials or a key for reacquiring the user's identity (e. IIS authentication cannot be used. Answer Often.NET Windows Forms in a A client generates a request for a protected Nutshell resource (e.ConnectionString) End If End Sub 8.DataSource = dataSource builder. Windows Authentication and Passport Authentication make up the other two providers. the application then submits a ticket in the form of a cookie. Forms Authentication is a means for wrapping your Web application around your own login user interface and verification processes. we will focus on Forms Authentication. In essence.NET application by default.Password = userPassword Console. ASP.Dim builder As New SqlConnectionStringBuilder(connectString) ' Supply the additional values. users authenticate themselves via a Web form.NET encompasses and extends the very same logic described above into its architecture as an authentication facility. IIS (Internet Information Server) receives the Matthew Adams request. This Web form submits the user's credentials to business logic that determines their authorization level. the client will be passed onto the ASP. Windows will prompt the user for credentials to access the server's resources. Otherwise. the user/client is passed on to the ASP. and being properly verified by your application. builder. If the requesting client is authenticated by IIS. .UserID = userName builder. By Ian Griffiths.g.NET application. Forms Authentication. in legacy Web applications. albeit a hard cookie or session variable.NET application is set to Forms. Describe the concept of Forms Authentication in Dot Net.WriteLine("Modified: {0}". Upon successful authentication. Forms Authentication is a system in which unauthenticated requests are redirected to a Web form where users are required to provide their credentials. In this article. an authorization ticket is issued by your Web application in the form of a cookie. Note that if Anonymous Access is enabled.

</system. all subsequent requests will be authenticated automatically until the client closes the browser or the session terminates. Enable anonymous access in IIS. The attributes and their descriptions are as follows : . The Forms element has five attributes that implement your forms authentication configuration. you may opt to layer an Integrated Windows OS security layer level with Forms authentication. <forms name=". After that date. </authentication> 13. you'll notice that we appended another child element. however.NET application. We will discuss how to integrate this layer with anonymous access enabled in the article succeeding this one ("Part 2 (Integration w/ Active Directory)").config file to use Forms Authentication.3. Configure your Web application's web. the user is prompted to enter their credentials to gain access to the secure resource.aspx" 9.NET will redirect the user to the URL specified in the loginURL attribute of the Authentication tag in your web. <configuration> 5. provided that the client has met the authentication and authorization prerequisites discussed above. </configuration> Upon setting the authentication mode to Forms. if the client is authorized to access the secure resource. Your ASP. 2. and. <deny users="?" /> 15. </authorization> 16.config file for your Web application: 3. the client is usually returned an Access Denied message. protection="All" 10. and denying access to anonymous users. 4. Once the authorization ticket/cookie is set. <authorization> 14. In general. path="/"/> 12. anonymous users should be allowed to access your Web application.NET application also determines the authorization level of the request. By default. The following example shows how this can be done in the web. The client can then be redirected back to the originally-requested resource.web> 6. timeout="30" 11. If authentication fails. which is now accessible. In rare cases. Start by setting the authentication mode attribute to Forms. setting up Forms Authentication involves just a few simple steps. 5. You can have the user's credentials persist over time by setting the authorization ticket/cookie expiration value to the date you desire to have the credentials persist through. the user will have to log in again. loginUrl="login. The client must provide credentials. <system.config file.COOKIEDEMO" 8. This URL should contain the login page for your application.web> 17. ASP. At this URL. 1. 4. If the client doesn't contain a valid authentication ticket/cookie. an authentication ticket is finally distributed to the client. Setting Up Forms Authentication Let's take a look at the applicable settings to execute Forms Authentication. <authentication mode="Forms"> 7. which are then authenticated/processed by your ASP.

we set that value of the users attribute to "?" to deny all anonymous users. This is because browsers are case-sensitive when returning cookies. The default value for this attribute is 30 (thus expiring the cookie in 30 minutes). if it is available and if the key is long enough (48 bytes). the validation key is concatenated in a buffer with the cookie data and a MAC is computed/appended to the outgoing cookie. This is the URL from which your unauthenticated client will be redirected. but data validation is not done on the cookie. It's important to note that this type of cookie is subject to chosen plaintext attacks. The following valid values can be supplied: name loginURL protection All: Specifies to use both data validation and encryption to protect the cookie. thus redirecting unauthenticated clients to the loginURL.web> . The All value is the default (and suggested) value. In most scenarios. The default value is set to "/" to avoid issues with mismatched case in paths. it's also important to note the value we have for the deny child element of the authorization section (as highlighted below). The value specified is a sliding value. Validation: Specifies to avoid encrypting the contents of the cookie. meaning that the cookie will expire n minutes from the time the last request was received. this would be your login page. <configuration> <system. respectively. None: Used for sites that are only using cookies for personalization and have weaker requirements for security. Both encryption and validation can be disabled. path This is the path to use for the issued cookie. Encryption: Specifies that the cookie is encrypted using Triple DES or DES.Attribute Description This is the name of the HTTP cookie from which we will store our authentication ticket and information. but validate that the cookie data has not been altered in transit.config file. Essentially. where the client is required to provide their credentials for authentication. but must be used with caution. Triple DES is used for encryption. To create the cookie. timeout This is the amount of time (in integer minutes) that the cookie has until it expires. In our web. This is the most efficient performance wise. This is used to set the method from which to protect your cookie data.

(UserPass. runat="server"/> 49. Display="Static" 47. FormsAuthentication. } 38. we should save our login page as login. <body> 41. This is the page to where clients without valid authentication cookie will be redirected. 37. if ((UserEmail. } 39. <script language="C#" runat=server> 23. <html> 22.Security " %> 21. <%@ Import Namespace="System.aspx" protection="All" timeout="30" path="/"/> </authentication> <authorization> <deny users="?" /> </authorization> </system. 26. <h3>Login Page</h3> 43. Create your login page (as referenced in the loginURL attribute discussed above).com and a password of 'password' 28.com") && 29.<authentication mode="Forms"> <forms name=". <hr> 44. The client will complete the HTML form and submit the values to the server.aspx. runat="server"/> .Value. 20.RedirectFromLoginPage(UserEmail. 33. PersistCookie.Checked). { 36. 19.web> </configuration> 18.Value == "username@domain. <form runat="server"> 42. <asp:RequiredFieldValidator ControlToValidate="UserEmail" 46. EventArgs E) 24. type="password" 51. { 31. // authenticate user: this sample accepts only one user with 27. lblResults. <p>Password:<input id="UserPass" 50.COOKIEDEMO" loginUrl="login. You can use the example below as a prototype.Value == "password")) 30. else 35.Text = "Invalid Credentials: Please try again". { 25. ErrorMessage="*" 48. } 34. </script> 40. void Login_Click(Object sender. In this case. 32.Web. Email:<input id="UserEmail" type="text" runat="server"/> 45. // a name of username@domain.

text="Login" 60. the client is not authorized. It is here at the Login_Click function that you can substitute the logic with that of your own.52. If not. </form> 67. </html> It's important to note that the above page authenticates the client on the click event of the cmdLogin button.web> <authentication mode="Forms"> <forms name=". <p>Persistent Cookie:<ASP:CheckBox id="PersistCookie" 57.COOKIEDEMO" loginUrl="login. You can adjust the logic to fit your needs. runat="server" /> 58. Upon clicking. as it is very likely that you will not have your usernames and passwords hard-coded into the logic. runat="server"/> 56. It is common practice to substitute database logic to verify the credentials against a data table with a stored procedure. <asp:RequiredFieldValidator ControlToValidate="UserPass" 53. ErrorMessage="*" 55. ForeColor="red" 64. the client is redirected to the requested resource. Inside the forms section. If so. and thus receives a message depicting this. </body> 68. runat="server" /> 66. Display="Static" 54. as follows : <configuration> <system.aspx" protection="All" timeout="30" path="/"> <credentials passwordFormat="Clear"> <user name="user1" password="password1"/> <user name="user2" password="password2"/> <user name="user3" password="password3"/> </credentials> </forms> </authentication> <authorization> <deny users="?" /> </authorization> . you would append a user element(s). <p><asp:button id="cmdLogin" 59. runat="server"/> 62. the logic determines if the username and password provided match those hard-coded in the logic. You can also provide authorized credentials in the web.config file. OnClick="Login_Click" 61. Font-Size="10" 65. <p><asp:Label id="lblResults" 63.

the cookie generated by Forms Authentication is lost and the client will not be able to authenticate.web> </configuration> Doing so allows you to authenticate against a list of users in your web. To authenticate against that list of users. once through your user interface and again through the Windows user interface. .Text = "Invalid Credentials: Please try again".Value)) { FormsAuthentication. we'll discuss how to incorporate Active Directory with Forms Authentication.config file. } } Client Requirements To enable forms authentication. UserPass. easily. Coming in Next Part of This Series In the next part of this series. } else { lblResults.Authenticate(UserEmail. You can append as many users as necessary. to get that Windows OS layer of security without forcing the user to authenticate twice.Value.Checked).</system. PersistCookie. you would append the applicable logic in the click event of the cmdLogin button discussed above. cookies must be enabled on the client browser. Here is the code : void Login_Click(Object sender.Value.config file if (FormsAuthentication. If the client disables cookies. EventArgs E) { // authenticate user: this sample authenticates // against users in your app domain's web.RedirectFromLoginPage(UserEmail.