ASP.NET MATERIAL INTRODUCTION TO WEB TECHNOLOGIES

Introduction to scripts:

• Html & Java Script:

A client-side script is a program that may accompany an HTML document or be embedded directly in it. The program executes on the client's machine when the document loads, or at some other time such as when a link is activated. HTML's support for scripts is independent of the .

Scripts offer authors a means to extend HTML documents in highly active and interactive ways. For example:

• Scripts may be evaluated as a document loads to modify the contents of the document dynamically. • Scripts may accompany a form to process input as it is entered. Designers may dynamically fill out parts of a form based on the values of other fields. They may also ensure that input data conforms to predetermined ranges of values, that fields are mutually consistent, etc. • Scripts may be triggered by events that affect the document, such as loading, unloading, element focus, mouse movement, etc. • Scripts may be linked to form controls (e.g., buttons) to produce graphical user interface elements.

There are two types of scripts authors may attach to an HTML document:

• Those that are executed one time when the document is loaded by the user agent. Scripts that appear within a SCRIPT element are executed when the document is loaded. For user agents that cannot or will not handle scripts, authors may include alternate content via the NOSCRIPT element. • Those that are executed every time a specific event occurs. These scripts may be assigned to a number of elements via the intrinsic event attributes.

The SCRIPT Element:

Page 1 ASP.NET MATERIAL

charset %Charset; #IMPLIED -- char encoding of linked resource --

type %Content Type; #REQUIRED -- content type of script language –

src %URI; #IMPLIED -- URI for an external script --

defer (defer) #IMPLIED -- UA may defer execution of script --

• Script Technologies:

The following table lists the Windows script technologies and describes the functionality included in each technology.

JScript :

The powerful Microsoft scripting language targeted specifically at the Internet. JScript 5.8 is the Microsoft implementation of the ECMA 262 language.

VBScript :

Microsoft Visual Basic Scripting Edition brings active scripting to a wide variety of environments. These include Web client scripting in Microsoft and Web server scripting in Microsoft Internet Information Services.

Script Runtime :

A Dictionary object is the equivalent of a PERL associative array. Items can be any form of data, and are stored in the array.

The FileSystemObject (FSO) object model lets you use the familiar object. method syntax with a rich set of properties, methods, and events to process folders and files.

Script Encoder is a simple command-line tool that enables script designers to encode their final script so that Web hosts and Web clients cannot view or modify their source.

Windows Script Components :

Microsoft Windows Script Components give you an easy way to create COM components using scripting languages such as Microsoft Visual Basic Scripting Edition (VBScript) and Microsoft JScript.

Page 2 ASP.NET MATERIAL

Windows Script Host:

The Script Host (WSH) is a tool that lets you run Visual Basic Scripting Edition and JScript natively in the base operating system.

Windows Script Interfaces:

Microsoft Windows Script Interfaces provide a way for an application to add scripting and OLE Automation capabilities.

• Client side scripting & Server side scripting

Client-side:

Client-side scripting enables interaction within a webpage. The code required to process user-input is downloaded and compiled by the browser or plug-in. An example of a client-side interaction is a rollover (typically triggered when choosing a navigation option).

Client-side scripting languages include JavaScript.

Server-side:

With server-side scripting, completing an activity involves sending information to another computer (server) across the internet. The server then runs a program that processes the information and returns the results, typically a webpage.

Search engines use server-side processing. When a keyword is sent, a program on a server matches the word or phrase entered against an index of website content. (To complete the same search as a client-side process would require the browser to download the entire search engine program and index.)

Server-side scripting languages include ASP and PHP.

Page 3 ASP.NET MATERIAL

Client-side vs. Server-side

Client-side interaction:

• Response to interaction may be more immediate (once the program code has been downloaded) • Services are secure (as no information is sent from the browser) • Reliant on the user having using a specific browser and/or plug-in on their computer • Affected by the processing speed of the user’s computer

Server-side interaction:

Complex processes are often more efficient (as the program and the associated resources are not downloaded to the browser)

There are security considerations when sending sensitive information

Does not rely on the user having specific browser or plug-in

Affected by the processing speed of the host server.

Architecture in ASP.NET (IIS 6.0)

This section provides an overview of the ASP.NET infrastructure and subsystem relationships, as they relate to the subject of security. The following illustration shows the relationships among the security systems in ASP.NET.

Page 4 ASP.NET MATERIAL

As the illustration shows, all Web clients communicate with ASP.NET applications through Internet Information Services (IIS). IIS deciphers and optionally authenticates the request. If Allow Anonymous is set to true, no authentication occurs. IIS also finds the requested resource (such as an ASP.NET application), and, if the client is authorized, returns the appropriate resource.

In addition to the built-in ASP.NET features, an ASP.NET application can use the low- level security features of the .NET Framework. For more information, see the "Key Security Concepts" topic in .NET Framework Help.

Integrating with IIS:

When considering ASP.NET authentication, you should understand the interaction with IIS authentication services.

IIS always assumes that a set of credentials maps to a Microsoft Windows NT account and uses them to authenticate a user. There are three different kinds of authentication available in IIS 5.0 through IIS 6.0: basic, digest, and Integrated Windows Authentication (NTLM or Kerberos). You can select the type of authentication to use in IIS administrative services.

If you request a URL containing an ASP.NET application, the request and authentication information are handed off to the application. ASP.NET provides the two additional types of authentication described in the following table.

ASP.NET Description authentication provider Forms A system by which unauthenticated requests are redirected to an authentication HTML form using HTTP client side redirection. The user provides credentials and submits the form. If the application authenticates the request, the system issues an authentication ticket in a cookie that contains the credentials or a key for reacquiring the identity. Subsequent requests are issued with the cookie in the request headers; they are authenticated and authorized by an ASP.NET handler using whatever validation method the application developer specifies. Passport Centralized authentication service provided by Microsoft that

Page 5 ASP.NET MATERIAL

ASP.NET Description authentication provider authentication offers a single logon and core profile services for member sites.

• ASP Objects Introduction

Objects are a way of encapsulating multiple methods (they're like functions) and variables in one easy to manage Uber-Variable (an Object). Objects in ASP resemble other Object Oriented Programming languages. In this lesson we will be using the ASP CDO.Message object as our example object to be dissected.

ASP Object Overview:

Objects were created to combat the increasing complexity of programming. The rationale for understanding and using Objects in your programming is to make programming easier and your code more human readable.

ASP Create an Object - Server.CreateObject:

An object in ASP is created by passing a name string to the Server.CreateObject function (actually referred to as a method). The string to create a Message object is "CDO.Message". We will be creating a CDO.Message object in this example.

Note: Because objects are special there is a special way that you create and destroy them using the Set keyword. These areas are marked in red in the example below.

ASP Code:

<%

Dim myObject Set myObject = Server.CreateObject ("CDO.Message")

'You must Set your objects to "nothing" to free up the 'the computer memory that was allocated to it Set myObject = nothing %>

Page 6 ASP.NET MATERIAL Objects are a collection of related things that are combined into this blob of programming go that can be created and destroyed whenever we may need it. For example say that you wanted to make an object that allowed you to send an email...

ASP Object Properties:

These smaller variables are commonly referred to as an object's properties and the format for setting these properties is nearly identical to setting a variable equal to a value.

The correct syntax for setting an object's properties is:

objectName.propertyName = someValue

In this tiny example below we are creating a new mail object and setting its To and From properties.

ASP Code:

<% Dim myObject Set myObject = Server.CreateObject("CDO.Message")

'Then we set the To and From properties myObject.To = "[email protected]" myObject.From = "[email protected]"

'You must Set your objects to "nothing" to free up the 'the computer memory that was allocated to it Set myObject = nothing %>

Now I know we didn't DO anything in the above example, but we still need to learn a bit more about objects before we can get anything done! Objects, besides having a clump of associated common variables, may also have a collection of functions(which become referred to as methods) associated with them.

These methods are processes that you would want to commonly do to either manipulate the variables of the object or to use the variables to do something. In our Message object we have a collection of information that, when put together into the proper email form and sent to an email service will become an email.

Page 7 ASP.NET MATERIAL All this complex code has been programmed by Microsoft employees and stored into the Message objects Send method.

ASP Object Methods:

We cannot see the code that was used to program the Send method, but that's one of the great things about using object programming. You know what you need to know and nothing more. In our example below we create a Message object and set the necessary properties and send it off with the Send method.

ASP Code:

<% Dim myObject Set myObject = Server.CreateObject("CDO.Message") 'Then we set the To and From properties myObject.To = "[email protected]" myObject.From = "[email protected]" myObject.Subject = "Can you see me?" myObject.TextBody = "I'm really really big!" myObject.Send() 'You must Set your objects to "nothing" to free up the 'the computer memory that was allocated to it Set myObject = nothing %>

ASP Object Summary:

In this lesson you learned how to create and destroy an object in ASP. You also learned how to access the properties and utilize the methods of an object. If you still have no idea what this lesson was about, hopefully there's enough information for you to hack out what you need to do in your ASP project.

Page 8 ASP.NET MATERIAL

ASP.NET INTRODUCTION

What is ASP.Net?

ASP.NET, the next version of ASP, is a programming framework used to create enterprise-class Web Applications. These applications are accessible on a global basis leading to efficient information management. The advantage ASP.NET offers is more than just the next version of ASP.

Why ASP.NET?

Since 1995, Microsoft has been constantly working to shift it's focus from Windows-based platforms to the Internet. As a result, Microsoft introduced ASP () in November 1996. ASP offered the efficiency of ISAPI applications along with a new level of simplicity that made it easy to understand and use. However, ASP script was an interpreted script and consisted unstructured code and was difficult to debug and maintain. As the web consists of many different technologies, integration for Web development was complicated and required to understand many different technologies. Also, as applications grew bigger in size and became more complex, the number of lines of source code in ASP applications increased dramatically and was hard to maintain. Therefore, an architecture was needed that would allow development of Web applications in a structured and consistent way.

The .NET Framework was introduced with a vision to create globally distributed software with Internet functionality and interoperability. The .NET Framework consists of many class libraries, includes multiple language support and a common execution platform. It's a very flexible foundation on which many different types of top class applications can be developed that do different things. Developing Internet applications with the .NET Framework is very easy. ASP.NET is built into this framework; we can create ASP.NET applications using any of the built-in languages.

Unlike ASP, ASP.NET uses the Common Language Runtime (CLR) provided by the .NET Framework. This CLR manages execution of the code we write. ASP.NET code is a compiled CLR code instead of interpreted code (ASP). CLR also allows objects written in different languages to interact with each other. The CLR makes development of Web applications simple.

Page 9 ASP.NET MATERIAL Advantages Using ASP.NET:

• ASP.NET drastically reduces the amount of code required to build large applications • ASP.NET makes development simpler and easier to maintain with an event- driven, server-side programming model • ASP.NET pages are easy to write and maintain because the source code and HTML are together • The source code is executed on the server. The pages have lots of power and flexibility by this approach • The source code is compiled the first time the page is requested. Execution is fast as the Web Server compiles the page the first time it is requested. The server saves the compiled version of the page for use next time the page is requested • The HTML produced by the ASP.NET page is sent back to the browser. The application source code you write is not sent and is not easily stolen • ASP.NET makes for easy deployment. There is no need to register components because the configuration information is built-in • The Web server continuously monitors the pages, components and applications running on it. If it noticies memory leaks, infinite loops, other illegal software or activities, it seamlessly kills those activities and restarts itself. • ASP.NET validates information (validation controls) entered by the user without writing a single line of code • ASP.NET easily works with ADO .NET using data-binding and page formatting features • ASP.NET applications run fater and counters large volumes of users without performance problems

Differences between ASP.NET and Client-Side Technologies:

Client-side refers to the browser and the machine running the browser. Server-side on the other hand refers to a Web server.

Client-Side Scripting:

JavaScript and VBScript and generally used for Client-side scripting. Client-side scripting executes in the browser after the page is loaded. Using client-side scripting you can add some cool features to your page. Both, HTML and the script are together in the same file and the script is downloading as part of the page which anyone can view.

Page 10 ASP.NET MATERIAL A client-side script runs only on a browser that supports scripting and specifically the scripting language that is used. Since the script is in the same file as the HTML and as it executes on the machine you use, the page may take longer time to download.

Server-Side Scripting:

ASP.NET is purely server-side technology. ASP.NET code executes on the server before it is sent to the browser. The code that is sent back to the browser is pure HTML and not ASP.NET code. Like client-side scripting, ASP.NET code is similar in a way that it allows you to write your code alongside HTML. Unlike client-side scripting, ASP.NET code is executed on the server and not in the browser. The script that you write alongside your HTML is not sent back to the browser and that prevents others from stealing the code you developed.

• Difference between Asp and Asp.Net:

Introduction:

In 1996 I was programming web applications using the old HTX/IDC method. Hopefully, not too many people remember this type of programming. It was bulky and did not have anything to offer outside database connectivity. ASP was a big improvement over this method and I quickly moved to it. I do not see ASP to ASP.net as quite a big jump as HTX/IDC to ASP, but it still requires a bit of education. ASP.net is the next rendition of ASP with a little bit of a twist and in this document we will touch upon some of the differences between ASP and ASP.net.

ASP is no longer an interpreted language; rather it is now a compiled language. What does that mean? It means that when a page is called in ASP the script is read and executed by a command line interpreter one line at a time. With ASP.net the pages are compiled common language code executing on the server. This allows for advantages and forces some changes in the traditional ASP programming.

Pros and Cons:

This new type of ASP coding allows for added performance benefit. This type of functionality is seen with COM Objects. Since COM Objects are pre-compiled they did not need to be interpreted every time the script was executed on the server. They are already in machine code and ready to go and thus give any code in COM Objects a performance boost. This also added a security benefit to COM Objects.

Page 11 ASP.NET MATERIAL Since ASP scripts were always interpreted the code needed to be in the web pages themselves. Since COM Objects are pre-compiled the source code is much harder to hack and thus is not as susceptible to security breaches. ASP.net, being compiled has similar increased the security in the new framework.

Another added benefit of ASP.net is its additional features that are included in the package. The functionality of these features can created in COM Objects, and some have been in the past. They have simply been included as part of the base package.

Lastly, ASP.net adds another language to the fold, C#, known as C sharp. All the following examples will use VBScript, but I encourage a look at this new language.

Now For the specific differences.

Rendered Ineffective:

The largest basic programming difference between ASP and ASP.net is the lost ability to program page-render functions. This means there will no longer be ASP functions with HTML intertwined throughout. I perceive this as the most radical change for current ASP programmers. One of the strengths of ASP was to easily drop functions into existing HTML web pages without much re-coding. ASP.net requires any HTML that appears within functions to be written to the screen using the response. write function.

ASP: <% Option Explicit Function PrintHello Dim i For i= 1 to 5

%> >Hello> <% Next End Function %>

Page 12 ASP.NET MATERIAL Asp.net:

<% Option Explicit Function PrintHello() Dim i For i= 1 to 5 response.write(" Hello")

<% Next End Function %>

Declaration of Independence from <% :

When a function is declared in ASP.net it must appear in a

Page 13 ASP.NET MATERIAL <% HelloWrite() %>

An added change that you may notice as well is that function calls require that the parentheses () appear after the function name. I have gotten it to work without the parentheses but I think officially it is required.

Array of Sunlight (or not):

ASP allowed array values to be passed via a querystring or form post and then received by a request on the receiving page. In order to access these values you simply had to request the variable with the array position following. This type of system was based upon a 1-index, meaning the first value was always in the 1 position. There are two big changes here. First of all, it has changed to a 0-index, meaning the first value will be in the 0 position. This is more concurrent with other compiled languages. Secondly, in order to access the values in an array from a querystring or the like the GetValues method must be called.

ASP:

<% Variable1=Request.QueryString("values")(1) %>

Asp.net: <% variable1=(Request.QueryString.GetValues("values")(0) %>

Ready, “Set”, Go! :

With ASP whenever an object was created or a database connection needed to be made a variable was usually assigned using “Set". In Asp.net there is no more need for variables to be “Set”, the variable must be simply made to be equal. This also applies to "Let".

ASP:

Page 14 ASP.NET MATERIAL <% Dim Connection Set Connection = Server.CreateObject("ADODB.Connection") %>

Asp.net: <% Dim Connection Connection = Server.CreateObject("ADODB.Connection") %>

I need an index please:

With some components, such as the ADO component, a default non-indexed property could be referred by simply referring to the object itself. This allowed for a shortcut in programming. However, in this more structured environment, this is no longer allowed. When an object is referred to the property must be called.

ASP:

<% Connection = Server.CreateObject("ADODB.Connection") Connection .Open("MyDatabase") RS = Connection .Execute("Select * from Operations") Response.Write(RS("ID")) %> Asp.net: <% Connection = Server.CreateObject("ADODB.Connection") Connection .Open("MyDatabase") RS = Connection .Execute("Select * from Operations") Response.Write(RS("ID").Value) %>

In the above ASP.net example the "Value" property must be explicitly indicated or it would not recognize what value to write to the screen and would generate an error.

Page 15 ASP.NET MATERIAL Oops!:

When an ASP.net page is run, if you are on the machine that the code is being executed on, or you have a web.config file in the root directory of the website configured properly, error messages that appear are a little more intuitive than the current error messages. In ASP error messages can be somewhat vague, but with ASP.net, the specific line of code that is causing the error is displayed with a little better description. This allows for an easier debugging time than before.

Bi-lingual I am not:

One large difference between ASP and ASP.net is ASP.net does not contain the capability to have multiple languages on a single page. This means you can not switch between VBScript to JScript and then back again. You still can have different languages on different pages within the same application, however.

I have a new extension, please forward all my calls:

The one last final and perhaps most minute change is ASP.net pages require a different extension. When a page is created in ASP.net it requires an .aspx extension, which you may notice this web page has as well. When a page has this extension IIS knows to treat it as an ASP.net page instead of an older ASP page.

Conclusion:

As you can see there are some changes to ASP, but with a little education you can easily move into the realm of ASP.net. I know a large concern for me is whether all the old ASP programming will need to be changed. Eventually, perhaps, but for now the old asp.dll is still available and has not been altered by these new improvements. Instead, Microsoft has put these changes into other libraries. All the old code you know and love will still run under ASP, but if you want to change to ASP.net there will be some time involved. For now, I think I will stick to updating my old code in ASP and writing new code in ASP.net.

Page 16 ASP.NET MATERIAL • In page and Code behind technique

Microsoft recommends dealing with dynamic program code by using the code-behind model, which places this code in a separate file or in a specially designated script tag. Code-behind files typically have names like MyPage.aspx.cs or MyPage.aspx.vb while the page file is MyPage.aspx (same filename as the page file (ASPX), but with the final extension denoting the page language). This practice is automatic in and other IDEs. When using this style of programming, the developer writes code to respond to different events, like the page being loaded, or a control being clicked, rather than a procedural walk through the document.

ASP. Net’s code-behind model marks a departure from Classic ASP in that it encourages developers to build applications with separation of presentation and content in mind. In theory, this would allow a web designer, for example, to focus on the design markup with less potential for disturbing the programming code that drives it. This is similar to the separation of the controller from the view in model-view-controller frameworks.

Example: <%@ Page Language="C#" CodeFile="SampleCodeBehind.aspx.cs" Inherits="Website.SampleCodeBehind" AutoEventWireup="true" %>

The above tag is placed at the beginning of the ASPX file. The CodeFile property of the @ Page directive specifies the file (.cs or .vb) acting as the code-behind while the Inherits property specifies the Class the Page derives from. In this example, the @ Page directive is included in SampleCodeBehind.aspx, then SampleCodeBehind.aspx.cs acts as the code-behind for this page: using System; namespace Website { public partial class SampleCodeBehind : System.Web.UI.Page { Protected void Page_ Load (object sender, EventArgs e) { Response. Write ("Hello, world"); } } }

Page 17 ASP.NET MATERIAL SERVER SIDE CONTROLS

In ASP.Net you have server side controls apart from the ordinary controls that are used in the web page. The server side controls are executed on the server and they have an attribute runat=”server”. This attribute that is found in the control indicates that it is a server side control.

The main advantage of using the server side control is that you can separate the code that is executed and the code that is used for display. By using the object oriented programming model of the server side control you can even create complex server side controls. They have rich set of properties, methods, and events.

There are basically three types of server side controls in ASP.Net. They are HTML Server Controls, Web Server Controls, and Validation Server Controls. The html server controls are ordinary html controls with an added attribute runat=”server”. The web server controls have the syntax,

The validation server controls also have the same syntax and they are used to validate the input that is given by the user in the forms. With this validation server controls you can also throw some error message to the user if their input is invalid.

• Client Side Controls Vs Server Side Controls:

I receive an excessive number of questions asking for help and asking how to do certain coding tasks. One question this week caught me by surprise. In a prior article, I presented a method for separating the scripting code form your actual HTML files. This raised the question about running the JavaScript on the server rather than on the client so that the client could not see the code. This question raised a critical issue for understanding Web programs to understand the different types of Web applications that can be created, you should understand the difference between client-side and server-side code.

Web pages are displayed in your browser on your local machine. Just like a customer or client for a restaurant, you and your browser are a client using a Web site. The Web site is displayed by your browser, which interprets code that was sent to it. In general this code will be primarily HTML, but may also contain anything supported by your browser such as JavaScript, flash movies, and more.

Page 18 ASP.NET MATERIAL The machine where the Web site actually resides is called a Web server. When you send a request for a Web page by entering a Web site address, this request is sent to a Web Server. The Web server then sends the Web page to your browser. The interesting thing about a Web server is that it can manipulate the code within a Web page before sending it to your browser. For most Web pages, no manipulation is done. Rather, the server simply sends a copy to the browser and the browser does the work of displaying the code.

A Web Server can manipulate what is included in a Web page before sending it. When the request is made to a server to send a Web page, the server can actually execute a program instead. This can be a program written in a variety of languages. Some of the programming languages and technologies that can be used are Active Server Pages (ASP), PHP, C/C++, and ISAPI, Java Server Pages (JSP), and more. Of course, in order to use any of these languages.

An important issue when working with Web applications is to remember that the Web server is separate from the Web browsers that will use a Web site's pages. The Web server can be located anywhere in the world -- or even off the world! The browser is generally on a machine you are using. Stated a different way, you can act as a customer, or client, using a browser to access a Web site that is located on a Web server.

The programs running on the Web Server are server side programs because they are on the side of the internet that the Web server is on. The browser being used to access the Web site is on the same side of the Web as you, the client side. If code is executed on the Web server, it is considered server side code. If code is executed on your browser, it is considered client-side. Because the internet is vast, the client side and server side programs are not constantly in contact with each other. Because of this, there is code that you can use on the server and there is code that you can use on the client.

What do you do on the server?

There are a number of types of programming things that can be done on the server. One of the primary functions you can do with code is to prepare the code that is to be sent to the Web browser. This includes such tasks as building pages customized for the type of browser that requested a page. It could also include doing tapping into a database to create information for a Web page. A very popular server side program is a Visitor Counter that keeps track of the number of people who have accessed a Web Site. The counter program would keep track of people who have come and store the information. It would also provide the actual number for any Web pages that are sent back to a browser.

What do you do on the client?

HTML, JavaScript, Flash files, ActiveX controls, Java applets, and a number of other technologies can be executed on the client side. You can execute any technology

Page 19 ASP.NET MATERIAL supported by your browser. Client side programming is used because the browser is separate from the server. By including code within a web page, a number of features can be added to a Web page without the need to send information to the Web Server which takes time. Tasks done on the client side include data validation, special formatting features that go beyond HTML, controls that take care of page navigation and ad presentation, and more.

• Types of Server Side Controls (Html Server Controls, Web Server Controls)

When you create Web Forms pages, you can use these types of controls:

• HTML server controls HTML elements exposed to the server so you can program them. HTML server controls expose an object model that maps very closely to the HTML elements that they render. • Web server controls Controls with more built-in features than HTML server controls. Web server controls include not only form-type controls such as buttons and text boxes, but also special-purpose controls such as a calendar. Web server controls are more abstract than HTML server controls in that their object model does not necessarily reflect HTML syntax. • Validation controls Controls that incorporate logic to allow you to test a user's input. You attach a validation control to an input control to test what the user enters for that input control. Validation controls are provided to allow you to check for a required field, to test against a specific value or pattern of characters, to verify that a value lies within a range, and so on. • User controls Controls that you create as Web Forms pages. You can embed Web Forms user controls in other Web Forms pages, which is an easy way to create menus, toolbars, and other reusable elements.

HTML Server Controls:

HTML server controls are HTML elements containing attributes that make them visible to — and programmable on — the server. By default, HTML elements on a Web Forms page are not available to the server; they are treated as opaque text that is passed through to the browser. However, by converting HTML elements to HTML server controls, you expose them as elements you can program on the server.

The object model for HTML server controls maps closely to that of the corresponding elements. For example, HTML attributes are exposed in HTML server controls as properties.

Page 20 ASP.NET MATERIAL Any HTML element on a page can be converted to an HTML server control. Conversion is a simple process involving just a few attributes. As a minimum, an HTML element is converted to a control by the addition of the attribute RUNAT="SERVER". This alerts the ASP.NET page framework during parsing that it should create an instance of the control to use during server-side page processing. If you want to reference the control as a member within your code, you should also assign an ID attribute to the control.

The page framework provides predefined HTML server controls for the HTML elements most commonly used dynamically on a page: forms, the HTML elements (text box, check box, Submit button, and so on), list box (

Adding such confirmation dialog boxes is quite possible in ASP.NET version 1.x, but requires writing code. See Adding Client-Side Message Boxes in Your ASP.NET Web Pages for more information on achieving this functionality with ASP.NET 1.x.

Page 176 ASP.NET MATERIAL Maintaining Scroll Position on Postback:

When working with large web pages where users typically have to scroll down, one annoyance that can occur when a Button, LinkButton, or ImageButton far down on the page is clicked is that, on postback, the browser returns to the top of the page. That is, if a user has to scroll down to click a button that causes a postback, on postback the browser will reload the document and be at the top of the page, meaning that the user has to scroll back down to where the button was clicked from if they want to see or work with the page at that point. This is a common pain when working with an editable GridView that may span many pages - when scrolling down and clicking the Edit button for some row that's not visible from the very top of the page, on postback the user has to scroll back down to the row being edited.

A previous 4Guys article authored by Steve Stchur - Maintaining Scroll Position on Postback - examined how to add a bit of JavaScript that would remember the X and Y scroll positions across postbacks and use JavaScript on the postback to "restore" the user's scroll position. I've personally used Steve's technique in a number of my ASP.NET 1.x projects over the past several years.

ASP.NET 2.0 makes remembering scroll position on postback even easier, as the ASP.NET 2.0 engine will kindly inject the necessary JavaScript and HTML elements necessary to remember scroll position across postbacks. To turn on this feature in ASP.NET 2.0, simply set the MaintainScrollPositionOnPostback directive to True, either on the page-level or in Web.config if you want it to apply to all pages in the website. To apply it for a single page, just update the <% @Page %gt; directive so that it looks lkike:

<%@ Page Language="..." MaintainScrollPositionOnPostback="true" ... %>

To apply this setting to all pages in the website, add the following markup to the Web.config file (within the element):

Turning on the MaintainScrollPositionOnPostback feature adds two hidden form fields to the rendered markup to track the X and Y scroll positions across postbacks:

Page 177 ASP.NET MATERIAL

Also, script is injected to associate the web form's client-side onsubmit event handler with the WebForm_SaveScrollPositionOnSubmit() function, which saves the current scroll positions in the hidden form fields shown above. On postback, the window's client- side onload event handler is configured to call the WebForm_RestoreScrollPosition() function, which restores the scroll position prior to the postback. Both the WebForm_SaveScrollPositionOnSubmit() and WebForm_RestoreScrollPosition() functions are included in the page via a JavaScript include to WebResource.axd? d=KJ8KmyYEIkBWV17-XIEtOQ2, which defines these functions as such: function WebForm_GetScrollX() { if (__nonMSDOMBrowser) { return window.pageXOffset; } else { if (document.documentElement && document.documentElement.scrollLeft) { return document.documentElement.scrollLeft; } else if (document.body) { return document.body.scrollLeft; } } return 0; } function WebForm_GetScrollY() { if (__nonMSDOMBrowser) { return window.pageYOffset; } else { if (document.documentElement && document.documentElement.scrollTop) { return document.documentElement.scrollTop; } else if (document.body) { return document.body.scrollTop; } } return 0; } function WebForm_SaveScrollPositionOnSubmit() { theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX(); theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY(); if ((typeof(this.oldOnSubmit) != "undefined") && (this.oldOnSubmit ! = null)) { return this.oldOnSubmit(); } return true; }

Page 178 ASP.NET MATERIAL function WebForm_RestoreScrollPosition() { if (__nonMSDOMBrowser) { window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value); } else { window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value); } if ((typeof(theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) { return theForm.oldOnLoad(); } return true; }

Conclusion: In many scenarios, adding client-side functionality can greatly improve the overall user experience of your web application. Such possibilities were available in ASP.NET 1.x, but ASP.NET 2.0 has added a variety of properties and methods to make it easier to perform a plethora of common client-side tasks. In this article we examined how to set the focus of a Web control, how to associate some client-side action when a Button, LinkButton, or ImageButton was clicked, and how to maintain scroll position across postbacks. Live demos of all of these techniques are provided in the download at the end of this article.

• In process & Out Process Session State:

In-process Mode:

In-process mode simply means using ASP.NET session state in a similar manner to classic ASP session state. That is, session state is managed in process and if the process is re-cycled, state is lost. Given the new settings that ASP.NET provides, you might wonder why you would ever use this mode. The reasoning is quite simple: performance. The performance of session state, e.g. the time it takes to read from and write to the session state dictionary, will be much faster when the memory read to and from is in process, as cross-process calls add overhead when data is marshaled back and forth or possibly read from SQL Server.

In-process mode is the default setting for ASP.NET. When this setting is used, the only other session config.web settings used are cookieless and timeout.

If we call SessionState.aspx, set a session state value, and stop and start the ASP.NET process (iisreset), the value set before the process was cycled will be lost.

Page 179 ASP.NET MATERIAL Out-of-process Mode:

Included with the .NET SDK is a Windows® NT service: ASPState. This Windows service is what ASP.NET uses for out-of-process session state management. To use this state manager, you first need to start the service. To start the service, open a command prompt and type:

Figure 1. Starting the Windows NT service ASPState at the command prompt

At this point, the Windows NT Service ASPState has started and is available to ASP.NET. Next, we need to configure ASP.NET to take advantage of this service. To do this we need to configure config.web:

We changed only from inproc mode to stateserver mode. This setting tells ASP.NET to look for the ASP state service on the server specified in the server and port settings —in this case, the local server.

We can now call SessionState.aspx, set a session state value, stop and start the IIS process (iisreset), and continue to have access to the values for our current state.

• Cookie less Session:

Are Cookies a Problem?

For several years, cookies were simply considered a technical feature and largely ignored. A few years ago, the worldwide push on Web security focused the spotlight on cookies.

Page 180 ASP.NET MATERIAL Cookies were alleged to contain dangerous programs capable of stealing valuable information even beyond the physical boundaries of the machine.

It goes without saying that cookies are not programs and therefore can't collect any information on their own, let alone any personal information about users. More simply, a cookie is a piece of text that a Web site can park on a user's machine to be retrieved and reused later. The information stored consists of harmless name-value pairs.

The point is, cookies are not part of the standard HTTP specification, so they imply a collaboration between browsers and Web sites to work. Not all browsers support cookies and, more importantly, not all users may have cookie support enabled in their own copy of the browser.

There are Web site features that are historically so tightly bound to cookies that they make it hard to distinguish which really came first. On the one hand, session state management and user authentication are much easier to code with cookies. On the other hand, if you take a look at your site's statistics regarding browsers used to access pages, you might be surprised to discover that a significant share of users connect with cookies disabled. This poses a point for you as a developer.

Summarizing, cookies are not a problem per se but their use undoubtedly gives some server code the ability to store a piece of data on client machines. This prefigures some potential security risks and an overall situation less then ideal. (In some cases and countries, it's even illegal for an application to require cookies to work.)

Enter Cookieless Sessions:

In ASP.NET, the necessary session-to-user link may optionally be established without using cookies. Interestingly enough, you don't have to change anything in your ASP.NET application to enable cookieless sessions, except the following configuration setting.

Default settings for ASP.NET session state are defined in the machine.config file and can be overridden in the web.config file in the application's root folder. By ensuring that the above line appears in the root web.config file, you enable cookieless sessions. That's it—easy and effective.

Page 181 ASP.NET MATERIAL The node can also be used to configure other aspects of the session state management, including the storage medium and the connection strings. However, as far as cookies are concerned, setting the cookieless attribute to true (default is false) is all that you have to do.

Note that session settings are application-wide settings. In other words, all the pages in your site will, or will not, use cookies to store session IDs.

Where is ASP.NET storing the session ID when cookies are not being used? In this case, the session ID is inserted in a particular position within the URL. The figure below shows a snapshot from a real-world site that uses cookieless sessions.

Figure 1. MapPoint using cookieless sessions

Imagine you request a page like http://yourserver/folder/default.aspx. As you can see from the MapPoint screenshot, the slash immediately preceding the resource name is expanded to include parentheses with the session ID stuffed inside, as below.

The session ID is embedded in the URL and there's no need to persist it anywhere. Well, not exactly.. Consider the following scenario.

You visit a page and get assigned a session ID. Next, you clear the address bar of the same browser instance, go to another application and work. Then, you retype the URL of the previous application and, guess what, retrieve your session values as you get in.

If you use cookieless sessions, in your second access to the application you're assigned a different session ID and lose all of your previous state. This is a typical side effect of cookieless sessions. To understand why, let's delve deep into the implementation of cookieless sessions.

Implementation:

Page 182 ASP.NET MATERIAL The implementation of cookieless sessions results from the efforts of two runtime modules—the standard Session HTTP module named SessionStateModule and an executable known as aspnet_filter.dll. The latter is a small piece of Win32 code acting as an ISAPI filter. HTTP modules and ISAPI filters realize the same idea, except that HTTP modules are made of managed code and require ASP.NET and CLR to trigger and work. Classic ISAPI filters like aspnet_filter.dll are invoked by Internet Information Services (IIS). Both intercept IIS events fired during the processing of the request.

When the first request of a new browser session comes in, the session state module reads about the cookie support in the web.config file. If the cookieless attribute of the section is set to true, the module generates a new session ID, mangles the URL by stuffing the session ID just before the resource name, and redirects the browser to the new URL using the HTTP 302 command.

When each request arrives at the IIS gate—far before it is handed over to ASP.NET— aspnet_filter.dll is given a chance to look at it. If the URL embeds a session ID in parentheses, then the session ID is extracted and copied into a request header named AspFilterSessionId. The URL is then rewritten to look like the originally requested resource and let go. This time the ASP.NET session state module retrieves the session ID from the request header and proceeds with session-state binding.

The cookieless mechanism works great as long as the URL contains information that can be used to obtain the session ID. As you'll see in a moment, this poses some usage restrictions.

Let's review the pros and cons of cookieless sessions.

Thumbs Up:

In ASP.NET, session management and forms authentication are the only two system features that use cookies under the hood. With cookieless sessions, you can now deploy stateful applications that work regardless of the user's preferences about cookies. As of ASP.NET 1.x, though, cookies are still required to implement forms authentication. The good news is that in ASP.NET 2.0 forms authentication can optionally work in a cookieless fashion.

Another common reason advanced against cookies is security. This is a point that deserves a bit more attention.

Page 183 ASP.NET MATERIAL Cookies are inert text files and as such can be replaced or poisoned by hackers, should they gain access to a machine. The real threat lies not much in what cookies can install on your client machine, but in what they can upload to the target site. Cookies are not programs and never run like programs; other software that gets installed on your machine, though, can use the built-in browser support for cookies to do bad things remotely.

Furthermore, cookies are at risk of theft. Once stolen, a cookie that contains valuable and personal information can disclose its contents to malicious hackers and favor other types of Web attacks. In summary, by using cookies you expose yourself to risks that can be zeroed off otherwise. Really?

Thumbs Down:

Let's look at security from another perspective. Have you ever heard of session hijacking? If not, take a look at the TechNet Magazine article Theft On The Web: Prevent Session Hijacking. In brief, session hijacking occurs when an attacker gains access to the session state of a particular user. Basically, the attacker steals a valid session ID and uses that to get into the system and snoop into the data. One common way to get a valid session ID is stealing a valid session cookie. That said, if you think that cookieless sessions put your application on the safe side, you're deadly wrong. With cookieless sessions, in fact, the session ID shows up right in the address bar! Try the following:

1. Connect to a Web site that uses cookieless sessions—for example, MapPoint— and get a map. At this point, the address is stored in the session state. 2. Grab the URL up to the page name. Don't include the query string but make sure the URL includes the session ID. 3. Save the URL to a file and copy/send the file to another machine. 4. On the second machine, open the file and paste the URL in a new instance of the browser. 5. The same map shows up as long as the session timeout is still valid.

With cookieless sessions, stealing session IDs is easier than ever.

I believe we all agree that stealing sessions is a reprehensible action from an ethical point of view. But is it injurious as well? That depends on what is actually stored in the session state. Stealing a session ID per se doesn't execute an action out of the code control. But it could disclose private data to unauthorized users and enable the bad guy to execute unauthorized operations. Read Wicked Code: Foiling Session Hijacking Attempts for tips on how to block session hijacking in ASP.NET applications. (And, yes, it doesn't rely on cookieless sessions!)

Page 184 ASP.NET MATERIAL Using cookieless sessions also raises issues with links. For example, you can't have absolute, fully qualified links in your ASP.NET pages. If you do this, each request that originates from that hyperlink will be considered as part of a new session. Cookieless sessions require that you always use relative URLs, like in ASP.NET postbacks. You can use a fully qualified URL only if you can embed the session ID in it. But how can you do that, since session IDs are generated at run time?

The following code breaks the session:

Click

To use absolute URLs, resort to a little trick that uses the ApplyAppPathModifier method on the HttpResponse class:

>Click

The ApplyAppPathModifier method takes a string representing a URL and returns an absolute URL that embeds session information. For example, this trick is especially useful in situations in which you need to redirect from a HTTP page to an HTTPS page. Finally, be conscious that every time you type a path to a site from within the same browser you're going to lose your state with cookieless sessions. As a further warning, be aware that cookieless sessions can be problematic with mobile applications if the device can't handle the specially formatted URL.

Summary:

The main reason for cookieless sessions in ASP.NET is that users—for whatever reasons —may have cookies disabled on their browsers. Like it or not, this is a situation you have to face if your application requires session state. Cookieless sessions embed the session ID in the URL and obtain a two-fold result. On the one hand, they provide a way for the Web site to correctly identify the user making the request. On the other hand, though, they make the session ID clearly visible to potential hackers who can easily steal it and represent themselves as you.

To implement cookieless sessions you don't have to modify your programming model—a simple change in the web.config file does the trick—but refactoring your application to avoid storing valuable information in the session state is strongly recommended too. At

Page 185 ASP.NET MATERIAL the same time, reducing the lifetime of a session to less than the default 20 minutes can help in keeping your users and your site safe.

ASP.NET SECURITY

ASP.NET Impersonation:

When using impersonation, ASP.NET applications can optionally execute with the identity of the client on whose behalf they are operating. The usual reason for doing this is to avoid dealing with authentication and authorization issues in the ASP.NET application code. Instead, you rely on Microsoft Internet Information Services (IIS) to authenticate the user and either pass an authenticated token to the ASP.NET application or, if unable to authenticate the user, pass an unauthenticated token. In either case, the ASP.NET application impersonates whichever token is received if impersonation is enabled. The ASP.NET application, now impersonating the client, then relies on the

Page 186 ASP.NET MATERIAL settings in the NTFS directories and files to allow it to gain access, or not. Be sure to format the server file space as NTFS, so that access permissions can be set.

Impersonation is disabled by default. For ASP compatibility, the user must explicitly enable impersonation. If impersonation is enabled for a given application, ASP.NET always impersonates the access token that IIS provides to ISAPI extensions. That token can be either an authenticated user token, or the token for the anonymous user (such as IUSR_MACHINENAME). The impersonation occurs regardless of the type of authentication being used in the application.

Only application code is impersonated; compilation and configuration are read as the process token. The result of the compilation is put in the "Temporary ASP.NET files" directory. The account that is being impersonated needs to have read/write access to this directory. If an application is on a universal naming convention (UNC) share, ASP.NET will always impersonate the token provided to IIS to access that share unless a configured account is used. If an explicit configured account is provided, ASP.NET will use that account in preference to the IIS UNC token. Applications that do want per-request impersonation can simply be configured to impersonate the user making the request.

Impersonation is disabled at the computer level by default and, unless overridden, all the application domains inherit this setting. You can enable impersonation by putting a configuration file in the application root directory. For more information about the ASP.NET configuration system, see ASP.NET Configuration.

As is the case with other configuration directives, this directive applies hierarchically. It is respected by nested applications in the hierarchy, unless explicitly overridden. The default value for this setting is as follows.

A minimal configuration file to enable impersonation for an application might look similar to the following example.

There is also name support for running an application as a configurable identity. For example:

Page 187 ASP.NET MATERIAL

This enables the entire application to run as contoso\Jane, regardless of the identity of the request, as long as the password is correct. This type of impersonation can be delegated to another computer.

You can programmatically read the identity of the impersonated user, as shown in the following example.

This language is not supported or no code example is available.

In the preceding example, userName and password are stored in clear text in the configuration file. Although IIS will not transmit .config files in response to a user agent request, configuration files can be read by other means, for instance by an authenticated user with proper credentials on the domain that contains the server. To help increase security, the identity section supports storage of encrypted userName and password attributes in the registry as shown in the following example.

userName="registry:HKLM\Software\AspNetIdentity,Name" password="registry:HKLM\Software\AspNetIdentity,Password"

The portion of the string after the keyword registry and before the comma indicates the name of the registry key that ASP.NET opens. The portion after the comma contains a single string value name from which ASP.NET will read the credentials. The comma is required, and the credentials must be stored in the HKLM hive. If the configuration format is incorrect, ASP.NET will not launch the worker process and the current account creation failure code path will be followed.

The credentials must be in REG_BINARY format, containing the output of a call to the Windows API function CryptProtectData. You can create the encrypted credentials and store them in the registry with the ASP.NET Set Registry console application(Aspnet_setreg.exe), which uses CryptProtectData to accomplish the encryption. To download Aspnet_setreg.exe, along with the Visual C++ source code and documentation, visit the Web site www.asp.net and search for "aspnet_setreg".

You should configure access to the key storing the encrypted credentials so that access is provided only to Administrators and SYSTEM. Because the key will be read by the ASP.NET process running as SYSTEM, you should set the following permissions:

Administrators:F SYSTEM:F CREATOR OWNER:F ProcessAccount:R

This provides two lines of defense to protect the data:

Page 188 ASP.NET MATERIAL 1. The ACL permissions require the identity accessing the data to be an Administrator. 2. An attacker must run code on the server (CryptUnprotectData) to recover the credentials for the account. • Authentication & Authorization:

Designing an Authentication and Authorization Strategy:

The following steps identify a process that will help you develop an authentication and authorization strategy for your application:

1. Identify resources 2. Choose an authorization strategy 3. Choose the identities used for resource access 4. Consider identity flow 5. Choose an authentication approach 6. Decide how to flow identity

Identify Resources:

Identify resources that your application needs to expose to clients. Typical resources include:

• Web Server resources such as Web pages, Web services, static resources (HTML pages and images). • Database resources such as per-user data or application-wide data. • Network resources such as remote file system resources and data from directory stores such as Active Directory.

You must also identify the system resources that your application needs to access. This is in contrast to resources that are exposed to clients. Examples of system resources include the registry, event logs and configuration files.

Choose an Authorization Strategy:

The two basic authorization strategies are:

• Role based. Access to operations (typically methods) is secured based on the role membership of the caller. Roles are used to partition your application's user base into sets of users that share the same security privileges within the application; for example, Senior Managers, Managers and Employees .Users are mapped to roles

Page 189 ASP.NET MATERIAL and if the user is authorized to perform the requested operation, the application uses fixed identities with which to access resources. These identities are trusted by the respective resource managers (for example, databases, the file system and so on). • Resource based. Individual resources are secured using Windows ACLs. The application impersonates the caller prior to accessing resources, which allows the operating system to perform standard access checks. All resource access is performed using the original caller's security context. This impersonation approach severely impacts application scalability, because it means that connection pooling cannot be used effectively within the application's middle tier.

In the vast majority of .NET Web applications where scalability is essential, a role-based approach to authorization represents the best choice. For certain smaller scale intranet applications that serve per-user content from resources (such as files) that can be secured with Windows ACLs against individual users, a resource-based approach may be appropriate.

The recommended and common pattern for role-based authorization is:

• Authenticate users within your front-end Web application. • Map users to roles. • Authorize access to operations (not directly to resources) based on role membership. • Access the necessary back-end resources (required to support the requested and authorized operations) by using fixed service identities. The back-end resource managers (for example, databases) trust the application to authorize callers and are willing to grant permissions to the trusted service identity or identities.

For example, a database administrator may grant access permissions exclusively to a specific HR application (but not to individual users).

More information

• For more information about the two contrasting authorization approaches, see Authorization Approaches later in this chapter. • For more information about role-based authorization and the various types of roles that can be used, see Role-Based Authorization later in this chapter.

Choose the Identities Used for Resource Access:

Choose the identity or identities that should be used to access resources across the layers of your application. This includes resources accessed from Web-based applications, and

Page 190 ASP.NET MATERIAL optionally Web services, Enterprise Services and .NET Remoting components. In all cases, the identity used for resource access can be:

• Original caller's identity. This assumes an impersonation/delegation model in which the original caller identity can be obtained and then flowed through each layer of your system. The delegation factor is a key criteria used to determine your authentication mechanism. • Process identity. This is the default case (without specific impersonation). Local resource access and downstream calls are made using the current process identity. The feasibility of this approach depends on the boundary being crossed, because the process identity must be recognized by the target system.

This implies that calls are made in one of the following ways:

o Within the same Windows security domain o Across Windows security domains (using trust and domain accounts, or duplicated user names and passwords where no trust relationship exists) • Service account. This approach uses a (fixed) service account. For example: o For database access this might be a fixed SQL user name and password presented by the component connecting to the database. o When a fixed Windows identity is required, use an Enterprise Services server application. • Custom identity. When you don't have Windows accounts to work with, you can construct your own identities (using IPrincipal and IIdentity implementations) that can contain details that relate to your own specific security context. For example, these could include role lists, unique identifiers, or any other type of custom information.

By implementing your custom identity with IPrincipal and IIdentity types and placing them in the current Web context (using HttpContext.User), you immediately benefit from built-in gatekeepers such as .NET roles and PrincipalPermission demands.

Consider Identity Flow

To support per-user authorization, auditing, and per-user data retrieval you may need to flow the original caller's identity through various application tiers and across multiple computer boundaries. For example, if a back-end resource manager needs to perform per- caller authorization, the caller's identity must be passed to that resource manager.

Based on resource manager authorization requirements and the auditing requirements of your system, identify which identities need to be passed through your application.

Page 191 ASP.NET MATERIAL Choose an Authentication Approach

Two key factors that influence the choice of authentication approach are first and foremost the nature of your application's user base (what types of browsers are they using and do they have Windows accounts), and secondly your application's impersonation/delegation and auditing requirements.

More information

For more detailed considerations that help you to choose an authentication mechanism for your application, see Choosing an Authentication Mechanism later in this chapter.

Decide How to Flow Identity:

You can flow identity (to provide security context) at the application level or you can flow identity and security context at the operating system level.

To flow identity at the application level, use method and stored procedure parameters. Application identity flow supports:

• Per-user data retrieval using trusted query parameters • SELECT x,y FROM SomeTable WHERE username="bob" • Custom auditing within any application tier

Operating system identity flow supports:

• Platform level auditing (for example, Windows auditing and SQL Server auditing) • Per-user authorization based on Windows identities

To flow identity at the operating system level, you can use the impersonation/delegation model. In some circumstances you can use Kerberos delegation, while in others (where perhaps the environment does not support Kerberos) you may need to use other approaches such as, using Basic authentication. With Basic authentication, the user's credentials are available to the server application and can be used to access downstream network resources.

More information

For more information about flowing identity and how to obtain an impersonation token with network credentials (that is, supports delegation), see Flowing Identity later in this chapter.

Page 192 ASP.NET MATERIAL Authorization Approaches:

There are two basic approaches to authorization:

• Role based. Users are partitioned into application-defined, logical roles. Members of a particular role share the same privileges within the application. Access to operations (typically expressed by method calls) is authorized based on the role- membership of the caller.

Resources are accessed using fixed identities (such as a Web application's or Web service's process identity). The resource managers trust the application to correctly authorize users and they authorize the trusted identity.

• Resource based. Individual resources are secured using Windows ACLs. The ACL determines which users are allowed to access the resource and also the types of operation that each user is allowed to perform (read, write, delete and so on).

Resources are accessed using the original caller's identity (using impersonation).

Role Based:

With a role-based (or operations-based) approach to security, access to operations (not back-end resources) is authorized based on the role membership of the caller. Roles (analyzed and defined at application design time) are used as logical containers that group together users who share the same security privileges (or capabilities) within the application. Users are mapped to roles within the application and role membership is used to control access to specific operations (methods) exposed by the application.

Where within your application this role mapping occurs is a key design criterion; for example:

• On one extreme, role mapping might be performed within a back-end resource manager such as a database. This requires the original caller's security context to flow through your application's tiers to the back-end database. • On the other extreme, role mapping might be performed within your front-end Web application. With this approach, downstream resource managers are accessed using fixed identities that each resource manager authorizes and is willing to trust. • A third option is to perform role mapping somewhere in between the front-end and back-end tiers; for example, within a middle tier Enterprise Services application.

Page 193 ASP.NET MATERIAL In multi-tiered Web applications, the use of trusted identities to access back-end resource managers provides greater opportunities for application scalability (thanks to connection pooling). Also, the use of trusted identities alleviates the need to flow the original caller's security context at the operating system level, something that can be difficult (if not impossible in certain scenarios) to achieve.

Resource Based:

The resource-based approach to authorization relies on Windows ACLs and the underlying access control mechanics of the operating system. The application impersonates the caller and leaves it to the operating system in conjunction with specific resource managers (the file system, databases, and so on) to perform access checks.

This approach tends to work best for applications that provide access to resources that can be individually secured with Windows ACLs, such as files. An example would be an FTP application or a simple data driven Web application. The approach starts to break down where the requested resource consists of data that needs to be obtained and consolidated from a number of different sources; for example, multiple databases, database tables, external applications or Web services.

The resource-based approach also relies on the original caller's security context flowing through the application to the back-end resource managers. This can require complex configuration and significantly reduces the ability of a multi-tiered application to scale to large numbers of users, because it prevents the efficient use of pooling (for example, database connection pooling) within the application's middle tier.

Resource Access Models:

The two contrasting approaches to authorization can be seen within the two most commonly used resource-access security models used by .NET Web applications (and distributed multi-tier applications in general). These are:

• The trusted subsystem model • The impersonation/delegation model

Each model offers advantages and disadvantages both from a security and scalability perspective. The next sections describe these models.

The Trusted Subsystem Model:

With this model, the middle tier service uses a fixed identity to access downstream services and resources. The security context of the original caller does not flow through

Page 194 ASP.NET MATERIAL the service at the operating system level, although the application may choose to flow the original caller's identity at the application level. It may need to do so to support back-end auditing requirements, or to support per-user data access and authorization.

The model name stems from the fact that the downstream service (perhaps a database) trusts the upstream service to authorize callers. Figure 3.1 shows this model. Pay particular attention to the trust boundary. In this example, the database trusts the middle tier to authorize callers and allow only authorized callers to access the database using the trusted identity.

Figure 3.1. The Trusted Subsystem model

The pattern for resource access in the trusted subsystem model is the following:

• Authenticate users • Map users to roles • Authorize based on role membership • Access downstream resource manager using a fixed trusted identity

Fixed identities:

The fixed identity used to access downstream systems and resource managers is often provided by a preconfigured Windows account, referred to as a service account. With a Microsoft SQL Server™ resource manager, this implies Windows authentication to SQL Server.

Alternatively, some applications use a nominated SQL account (specified by a user name and password in a connection string) to access SQL Server. In this scenario, the database must be configured for SQL authentication.

Page 195 ASP.NET MATERIAL Using multiple trusted identities:

Some resource managers may need to be able to perform slightly more fine-grained authorization, based on the role membership of the caller. For example, you may have two groups of users, one who should be authorized to perform read/write operations and the other read-only operations.

Consider the following approach with SQL Server:

• Create two Windows accounts, one for read operations and one for read/write operations.

More generally, you have separate accounts to mirror application-specific roles. For example, you might want to use one account for Internet users and another for internal operators and/or administrators.

• Map each account to a SQL Server user-defined database role, and establish the necessary database permissions for each role. • Map users to roles within your application and use role membership to determine which account to impersonate before connecting to the database.

Figure 3.2. Using multiple identities to access a database to support more fine- grained authorization

The Impersonation / Delegation Model:

With this model, a service or component (usually somewhere within the logical business services layer) impersonates the client's identity (using operating system-level impersonation) before it accesses the next downstream service. If the next service in line is on the same computer, impersonation is sufficient. Delegation is required if the downstream service is located on a remote computer.

Page 196 ASP.NET MATERIAL As a result of the delegation, the security context used for the downstream resource access is that of the client. This model is typically used for a couple of reasons:

• It allows the downstream service to perform per-caller authorization using the original caller's identity. • It allows the downstream service to use operating system-level auditing features.

As a concrete example of this technique, a middle-tier Enterprise Services component might impersonate the caller prior to accessing a database. The database is accessed using a database connection tied to the security context of the original caller. With this model, the database authenticates each and every caller and makes authorization decisions based on permissions assigned to the individual caller's identity (or the Windows group membership of the caller). The impersonation/delegation model is shown in Figure 3.3.

Figure 3.3. The impersonation/delegation model

Choosing a Resource Access Model:

The trusted subsystem model is used in the vast majority of Internet applications and large-scale intranet applications, primarily for scalability reasons. The impersonation model tends to be used in smaller-scale applications where scalability is not the primary concern and those applications where auditing (for reasons of non-repudiation) is a critical concern.

Advantage of the impersonation / delegation model:

The primary advantage of the impersonation / delegation model is auditing (close to the data). Auditing allows administrators to track which users have attempted to access specific resources. Generally auditing is considered most authoritative if the audits are generated at the precise time of resource access and by the same routines that access the resource.

Page 197 ASP.NET MATERIAL The impersonation / delegation model supports this by maintaining the user's security context for downstream resource access. This allows the back-end system to authoritatively log the user and the requested access.

Disadvantages of the impersonation / delegation model:

The disadvantages associated with the impersonation / delegation model include:

• Technology challenges. Most security service providers don't support delegation, Kerberos is the notable exception.

Processes that perform impersonation require higher privileges (specifically the Actas part of the operating system privilege). This restriction applies to Windows 2000 and does not apply to Windows Server 2003.

• Scalability. The impersonation / delegation model means that you cannot effectively use database connection pooling, because database access is performed by using connections that are tied to the individual security contexts of the original callers. This significantly limits the application's ability to scale to large numbers of users. • Increased administration effort. ACLs on back-end resources need to be maintained in such a way that each user is granted the appropriate level of access. When the number of back-end resources increases (and the number of users increases), a significant administration effort is required to manage ACLs.

Advantages of the trusted subsystem model:

The trusted subsystem model offers the following advantages:

• Scalability. The trusted subsystem model supports connection pooling, an essential requirement for application scalability. Connection pooling allows multiple clients to reuse available, pooled connections. It works with this model because all back-end resource access uses the security context of the service account, regardless of the caller's identity. • Minimizes back-end ACL management. Only the service account accesses back-end resources (for example, databases). ACLs are configured against this single identity. • Users can't access data directly. In the trusted-subsystem model, only the middle-tier service account is granted access to the back-end resources. As a result, users cannot directly access back-end data without going through the application (and being subjected to application authorization).

Page 198 ASP.NET MATERIAL Disadvantages of the trusted subsystem model:

The trusted-subsystem model suffers from a couple of drawbacks:

• Auditing. To perform auditing at the back end, you can explicitly pass (at the application level) the identity of the original caller to the back end, and have the auditing performed there. You have to trust the middle-tier and you do have a potential repudiation risk. Alternatively, you can generate an audit trail in the middle tier and then correlate it with back-end audit trails (for this you must ensure that the server clocks are synchronized). • Increased risk from server compromise. In the trusted-subsystem model, the middle-tier service is granted broad access to back-end resources. As a result, a compromised middle-tier service potentially makes it easier for an attacker to gain broad access to back-end resources.

Flowing Identity:

Distributed applications can be divided into multiple secure subsystems. For example, a front-end Web application, a middle-tier Web service, a remote component, and a database represent four different security subsystems. Each performs authentication and authorization.

You must identify those subsystems that must flow the caller's identity (and associated security context) to the next downstream subsystem in order to support authorization against the original caller.

Application vs. Operating System Identity Flow:

Strategies for flowing identities include using the delegation features of the operating system or passing tickets and/or credentials at the application level. For example:

• To flow identity at the application level, you typically pass credentials (or tickets) using method arguments or stored procedure parameters.

Note GenericPrincipal objects that carry the authenticated caller’s identity do not automatically flow across processes. This requires custom code.

You can pass parameters to stored procedures that allow you to retrieve and process user-specific data. For example:

SELECT CreditLimit From Table Where UserName=”Bob”

This approach is sometimes referred to as a trusted query parameter approach.

Page 199 ASP.NET MATERIAL • Operating system identity flow requires an extended form of impersonation called delegation.

Impersonation and Delegation:

Under typical circumstances, threads within a server application run using the security context of the server process. The attributes that comprise the process' security context are maintained by the process' logon session and are exposed by the process level Windows access token. All local and remote resource access is performed using the process level security context that is determined by the Windows account used to run the server process.

Impersonation:

When a server application is configured for impersonation or uses programmatic impersonation, an impersonation token is attached to the thread used to process a request. The impersonation token represents the security context of the authenticated caller (or anonymous user). Any local resource access is performed using the thread impersonation token that results in the use of the caller's security context.

Delegation:

If the server application thread attempts to access a remote resource, delegation is required. Specifically, the impersonated caller's token must have network credentials. If it doesn't, all remote resource access is performed as the anonymous user (AUTHORITY\ANONYMOUS LOGON).

There are a number of factors that determine whether or not a security context can be delegated. Table 3.1 shows the various IIS authentication types and for each one indicates whether or not the security context of the authenticated caller can be delegated.

Table 3.1. IIS Authentication types

Authentication Can Notes Type Delegate If the anonymous account (by default IUSR_MACHINE) is configured in IIS as a local account, it cannot be delegated unless the local (Web server) and remote computer have Anonymous Depends identical local accounts (with matching usernames and passwords). If the anonymous account is a domain account it can be delegated.

Page 200 ASP.NET MATERIAL If Basic authentication is used with local accounts, it can be delegated if the local accounts on the local and remote Basic Yes computers are identical. Domain accounts can also be delegated. Digest No Integrated Windows authentication either results in NTLM or Kerberos (depending upon the version of operating system on client and server computer). NTLM does not support delegation. Integrated Depends Kerberos supports delegation with a suitably configured Windows environment. For more information, see How To: Implement Kerberos Delegation for Windows 2000 in the References section of this guide. Can be delegated if used with IIS certificate mapping and the certificate is mapped to a local account that is duplicated on the remote computer or is mapped to a domain account. Client This works because the credentials for the mapped account Depends Certificates are stored on the local server and are used to create an Interactive logon session (which has network credentials). Active Directory certificate mapping does not support delegation.

Important Kerberos delegation under Windows 2000 is unconstrained. In other words, a user may be able to make multiple network hops across multiple remote computers. To close this potential security risk, you should limit the scope of the domain account's reach by removing the account from the Domain Users group and allow the account to be used only to log on to specific computers. Note Windows Server 2003 introduces constrained delegation, which can be used to restrict the delegation to a particular service on a particular server.

Role-Based Authorization:

Most .NET Web applications will use a role-based approach for authorization. You need to consider the various role types and choose the one(s) most appropriate for your application scenario. You have the following options:

• .NET roles • Enterprise Services (COM+) roles • SQL Server User Defined Database roles • SQL Server Application roles

Page 201 ASP.NET MATERIAL .NET Roles:

.NET roles are extremely flexible and can be used within Web applications, Web services, or remote components hosted within ASP.NET (and accessed using the HttpChannel).

You can perform authorization using .NET roles either declaratively by using PrincipalPermission demands, or programmatically in code by using imperative PrincipalPermission demands or the IPrincipal.IsInRole method.

.NET roles with Windows authentication:

If your application uses a non-Windows authentication mechanism such as Forms or Passport, you must write code to create a GenericPrincipal object (or a custom IPrincipal object) and populate it with a set of roles obtained from a custom authentication data store such as a SQL Server database.

.NET roles with non-Windows authentication:

If your application uses a non-Windows authentication mechanism such as Forms or Passport, you must write code to create a GenericPrincipal object (or a custom IPrincipal object) and populate it with a set of roles obtained from a custom authentication data store such as a SQL Server database.

Custom IPrincipal objects

The .NET Role-based security mechanism is extensible. You can develop your own classes that implement IPrincipal and IIdentity and provide your own extended role- based authorization functionality.

As long as the custom IPrincipal object (containing roles obtained from a custom data store) is attached to the current request context (using HttpContext.User), basic role- checking functionality is ensured.

By implementing the IPrincipal interface, you ensure that both the declarative and imperative forms of PrincipalPermission demands work with your custom identity. Furthermore, you can implement extended role semantics; for example, by providing an additional method such as IsInMultipleRoles( string [] roles ) which would allow you to test and assert for membership of multiple roles.

Page 202 ASP.NET MATERIAL Enterprise Services (COM+) Roles:

Using Enterprise Services (COM+) roles pushes access checks to the middle tier and allows you to use database connection pooling when connecting to back-end databases. However, for meaningful Enterprise Services (COM+) role-based authorization, your front-end Web application must impersonate and flow the original caller's identity (using a Windows access token) to the Enterprise Services application. To achieve this, the following entries must be placed in the Web application's Web.config file.

If it is sufficient to use declarative checks at the method level (to determine which users can call which methods), you can deploy your application and update role membership using the Component Services administration tool.

If you require programmatic checks in method code, you lose some of the administrative and deployment advantages of Enterprise Services (COM+) roles, because role logic is hard-coded.

SQL Server User Defined Database Roles:

With this approach, you create roles in the database, assign permissions based on the roles and map Windows group and user accounts to the roles. This approach requires you to flow the caller's identity to the back end (if you are using the preferred Windows authentication to SQL Server).

SQL Server Application Roles:

With this approach, permissions are granted to the roles within the database, but SQL Server application roles contain no user or group accounts. As a result, you lose the granularity of the original caller.

With application roles, you are authorizing access to a specific application (as opposed to a set of users). The application activates the role using a built-in stored procedure that accepts a role name and password. One of the main disadvantages of this approach is that it requires the application to securely manage credentials (the role name and associated password).

.NET Roles versus Enterprise Services (COM+) Roles:

The following table presents a comparison of the features of .NET roles and Enterprise Services (COM+) roles.

Page 203 ASP.NET MATERIAL Table 3.2. Comparing Enterprise Services roles with .NET roles

Feature Enterprise Services Roles .NET Roles Component Services Administration Custom Administration Tool Custom data store (for example, Data Store COM+ Catalog SQL Server or Active Directory) Yes Yes [PrincipalPermission( Declarative [SecurityRole("Manager")] SecurityAction.Demand, Role="Manager")] Yes Yes (IPrincipal.IsInRole, and Imperative ContextUtil.IsCallerInRole() additionally Roles.IsUserInRole if you are running ASP.Net 2.0) Class, Interface and Method Level Yes Yes Granularity Yes (using custom IPrincipal Extensible No implementation, and additionally creating a custom role provider if you are running ASP.NET 2.0) Only for components that Available to all derive from ServicedComponent Yes .NET components base class When using WindowsPrincipals, Roles contain Windows group or Role Membership roles ARE Windows groups–no user accounts extra level of abstraction Yes Requires explicit To obtain method level Interface No authorization, an interface must be implementation explicitly defined and implemented

Using .NET Roles:

You can secure the following items with .NET roles:

• Files • Folders • Web pages (.aspx files) • Web services (.asmx files)

Page 204 ASP.NET MATERIAL • Objects • Methods and properties • Code blocks within methods

The fact that you can use .NET roles to protect operations (performed by methods and properties) and specific code blocks means that you can protect access to local and remote resources accessed by your application.

To use .NET roles with a non-Windows authentication mechanism, you must write code to:

• Capture the user's credentials. • Validate the user's credentials against a custom data store such as a SQL Server database. • Retrieve a role list, construct a GenericPrincipal object and associate it with the current Web request.

Note When using the Role Manager feature of ASP.NET 2.0, you do not need to populate the GenericPrincipal class with the role set. The Role Manager feature automatically obtains the role information for the user.

The GenericPrincipal object represents the authenticated user and is used for subsequent .NET role checks, such as declarative PrincipalPermission demands and programmatic IPrincipal.IsInRole checks.

Checking role membership:

The following types of .NET role checks are available:

Important .NET role checking relies upon an IPrincipal object (representing the authenticated user) being associated with the current request. For ASP.NET Web applications, the IPrincipal object must be attached to HttpContext.User. For Windows Forms applications, the IPrincipal object must be attached to Thread.CurrentPrincipal.

• Manual role checks. For fine-grained authorization, you can call the IPrincipal.IsInRole method to authorize access to specific code blocks based on the role membership of the caller. Both AND and OR logic can be used when checking role membership. Additionally, when using the Role Manager feature of ASP.Net 2.0, you can use Role APIs such as Role.IsUserInRole. • Declarative role checks (gates to your methods). You can annotate methods with the PrincipalPermissionAttribute class (which can be shortened to PrincipalPermission), to declaratively demand role membership. These support OR logic only. For example you can demand that a caller is in at least one specific

Page 205 ASP.NET MATERIAL role (for example, the caller must be a teller or a manager). You cannot specify that a caller must be a manager and a teller using declarative checks. • Imperative role checks (checks within your methods). You can call PrincipalPermission.Demand within code to perform fine-grained authorization logic. Logical AND and OR operations are supported.

Choosing an Authentication Mechanism:

This section presents guidance that is designed to help you choose an appropriate authentication mechanism for common application scenarios. You should start by considering the following issues:

• Identities. A Windows authentication mechanism is appropriate only if your application's users have Windows accounts that can be authenticated by a trusted authority accessible by your application's Web server. • Credential management. One of the key advantages of Windows authentication is that it enables you to let the operating system take care of credential management. With non-Windows approaches, such as Forms authentication, you must carefully consider where and how you store user credentials. The two most common approaches are to use: o SQL Server databases o User objects within Active Directory • Identity flow. Do you need to implement an impersonation/delegation model and flow the original caller's security context at the operating system level across tiers? For example, to support auditing or per-user (granular) authorization. If so, you need to be able to impersonate the caller and delegate their security context to the next downstream subsystem, as described in the "Delegation" section earlier in this chapter. • Browser type. Do your users all have Internet Explorer or do you need to support a user base with mixed browser types? Table 3.3 illustrates which authentication mechanisms require Internet Explorer browsers, and which support a variety of common browser types.

Table 3.3. Authentication browser requirements

Requires Authentication Internet Notes Type Explorer Forms No Passport No

Page 206 ASP.NET MATERIAL Kerberos also requires Windows 2000 or later Integrated Windows operating systems on the client and server (Kerberos or Yes computers. For more information, see How To: NTLM) Implement Kerberos Delegation for Windows 2000 in the Reference section of this guide. Basic authentication is part of the HTTP 1.1 Basic No protocol that is supported by virtually all browsers Digest Yes Certificate No Clients require X.509 certificates

Internet Scenarios:

• The basic assumptions for Internet scenarios are: o Users do not have Windows accounts in the server's domain or in a trusted domain accessible by the server. o Users do not have client certificates.

Figure 3.4 shows a decision tree for choosing an authentication mechanism for Internet scenarios.

Figure 3.4. Choosing an authentication mechanism for Internet applications

Forms / Passport comparison:

This section summarizes the relative merits of Forms and Passport authentication.

Advantages of Forms authentication:

• Supports authentication against a custom data store; typically a SQL Server database or Active Directory.

Page 207 ASP.NET MATERIAL • Supports role-based authorization with role lookup from a data store. • Smooth integration with Web user interface. • ASP.NET provides much of the infrastructure.

Advantages of Passport authentication

• Passport is a centralized solution. • It removes credential management issues from the application. • It can be used with role-based authorization schemes. • It is very secure as it is built on cryptography technologies.

Intranet / Extranet Scenarios:

Figure 3.5 shows a decision tree that can be used to help choose an authentication mechanism for intranet and extranet application scenarios.

Figure 3.5. Choosing an authentication mechanism for intranet and extranet applications

Authentication Mechanism Comparison:

The following table presents a comparison of the available authentication mechanisms.

Page 208 ASP.NET MATERIAL

Table 3.4: Available authentication methods

Basic Digest NTLM Kerberos Certs Forms Passport Users need Windows accounts in Yes Yes Yes Yes No No No server's domain Can Supports delegation* Yes No No Yes Yes Yes do Requires Win2K clients and No Yes No Yes No No No servers Credentials passed as clear text Yes No No No No Yes No (requires SSL) Supports non-IE browsers Yes No No No Yes Yes Yes

Summary:

• Designing distributed application authentication and authorization approaches is a challenging task. Proper authentication and authorization design during the early design phases of your application development helps mitigate many of the top security risks. The following summarizes the information in this chapter: o Use the trusted subsystem resource access model to gain the benefits of database connection pooling. o If your application does not use Windows authentication, use .NET role checking to provide authorization. Validate credentials against a custom data store, retrieve a role list and create a GenericPrincipal object. Associate it with the current Web request (HttpContext.User). o If your application uses Windows authentication and doesn't use Enterprise Services, use .NET roles. Remember that for Windows authentication, .NET roles are Windows groups. o If your application uses Windows authentication and Enterprise Services, consider using Enterprise Services (COM+) roles. o For meaningful role-based authorization using Enterprise Services (COM+) roles, the original caller's identity must flow to the Enterprise Services application. If the Enterprise Services application is called from an ASP.NET Web application, this means that the Web application must use Windows authentication and be configured for impersonation. o Annotate methods with the PrincipalPermission attribute to declaratively demand role membership. The method is not called if the caller is not in the specified role and a security exception is generated. o Call PrincipalPermission.Demand within method code (or use IPrincipal.IsInRole, if you are running ASP.NET 2.0 with the Role

Page 209 ASP.NET MATERIAL Manager feature, use Role API such as Roles.IsUserInRole for fine- grained authorization decisions. o Consider implementing a custom IPrincipal object to gain additional role- checking semantics.

• Windows Based Authentication:

Configuring Windows Authentication:

To configure your application to use Integrated Windows authentication, you must use IIS Manager to configure your application's virtual directory security settings and you must configure the element in the Web.config file.

To configure Windows authentication

1. Start Internet Information Services (IIS). 2. Right-click your application's virtual directory, and then click Properties. 3. Click the Directory Security tab. 4. Under Anonymous access and authentication control, click Edit. 5. Make sure the Anonymous access check box is not selected and that Integrated Windows authentication is the only selected check box.

In your application's Web.config file or in the machine-level Web.config file, ensure that the authentication mode is set to Windows as shown here.

... ... ... ...

Using Impersonation with Windows Authentication :

By using impersonation, ASP.NET applications can execute code or access resources with the identity of the authenticated user or a fixed Windows identity. Standard impersonate-level impersonation tokens that are usually created when you enable impersonation allow you to access local resources only. To be able to access remote network resources, you require a delegate-level token. To generate a delegate-level token

Page 210 ASP.NET MATERIAL when you impersonate, you need to use Kerberos authentication and your process account needs to be marked as trusted for delegation in Active Directory.

By default, ASP.NET applications are not configured for impersonation. You can confirm this by reviewing the identity settings in the Machine.config.comments file. %windir%\Microsoft.Net\Framework\{Version}\CONFIG.

The element is configured as follows. Note that impersonation is disabled.

Impersonating the Original Caller with Windows Authentication:

When you configure your application for impersonation, an impersonation token for the authenticated user is attached to the Web request thread. As a result, all local resource access is performed using the caller's identity.

To configure ASP.NET to use Windows authentication with impersonation, use the following configuration.

... ... ... ...

The resulting impersonation token and associated logon session does not have network credentials. If you access this Web site from a browser while logged onto a different machine in the same domain and the Web site attempts to access network resources, you end up with a null session on the remote server and the resource access will fail. To access remote resources, you need delegation.

Impersonating a Fixed Identity with Windows Authentication :

You can configure ASP.NET to impersonate a fixed identity. You specify the credentials of the impersonated identity on the element in the Web.config file as shown here.

Page 211 ASP.NET MATERIAL ... ... ... ...

If you specify credentials on the element, make sure they are stored in encrypted format by using the Aspnet_regiis.exe tool.

Impersonating the Original Caller Programmatically:

If you only require an impersonated identity to access specific resources or perform specific operations and can use your process identity the rest of the time, you can use programmatic impersonation to temporarily enable impersonation.

To temporarily impersonate the authenticated user

This procedure shows you how to temporarily impersonate the original caller by using the Windows token that is passed by IIS to your Web application and is available through the HttpContext object.

1. Check that your ASP.NET application is not configured for impersonation by ensuring that impersonate is set to false on the element in the Web.config file. 2. ... 3. 4. ... 5. 6. 7. ... 8. 9. ...

10. Obtain the authenticated user's Windows token. 11. IIdentity WinId= HttpContext.Current.User.Identity; 12. WindowsIdentity wi = (WindowsIdentity)WinId;

13. Use the authenticated user's Windows token to temporarily impersonate the original user and remove the impersonation token from the current thread when you are finished impersonating. 14. // Temporarily impersonate the original user.

Page 212 ASP.NET MATERIAL 15. WindowsImpersonationContext wic = wi.Impersonate(); 16. try 17. { 18. // Access resources while impersonating. 19. } 20. catch 21. { 22. // Prevent exceptions propagating. 23. } 24. finally 25. { 26. // Revert impersonation. 27. wic.Undo(); 28. }

Authorizing Windows Users:

When you use Windows authentication to authenticate users, you can use the following authorization options:

• File authorization provided by the FileAuthorizationModule. • URL authorization provided by the UrlAuthorizationModule. • Role-based authorization.

Configuring Windows ACLs for File Authorization:

Requests for file types mapped to the ASP.NET ISAPI extension are checked by the FileAuthorizationModule. When you use Windows authentication, the authenticated user's Windows token is compared against the ACL attached to the requested file. For static files types that are not mapped to the ASP.NET ISAPI extension, IIS performs access checks again by using the authenticated user's access token and the ACL attached to the file. You need to configure appropriate ACLs on the file types directly requested by the user and on the files and other Windows resources accessed by your application, as described here:

• Forresources directly requested by the user. For resources such as Web pages (.aspx files) and Web services (.asmx files) directly requested by the user, the authenticated user's Windows access token is compared against the Windows ACL attached to the file. Make sure that the authenticated user is allowed to access the appropriate Web pages and Web services. • For resources that the application accesses. If impersonation is enabled, resources such as files, databases, registry keys, and Active Directory objects are accessed by using the impersonated identity. Otherwise, your application's process identity, such as the Network Service account, is used for resource access.

Page 213 ASP.NET MATERIAL For the resource access attempt to succeed, the ACL attached to these resources must be suitably configured to allow the process account or impersonated identity the access it requests, such as read access, or write access.

Configuring URL Authorization:

When you use Windows authentication, the UrlAuthorizationModule checks the access to requested files and folders based on the authenticated caller's identity. This is true regardless of whether your application is configured for impersonation.

To configure URL authorization, add an element to the Web.config file, and specify the domain name and user or group name when configuring and elements, as shown here.

When you use Windows authentication, user names take the form domainName\userName. Windows groups are used as roles and they take the form domainName\windowsGroupName. Well known local groups such as Administrators and Users are referenced by using the "BUILTIN" prefix as shown here.

Checking Role Membership in Code:

With Windows authentication, the user's Windows group membership can be used to determine the role membership and Window groups become the roles. You can perform role-based authorization in code either by performing explicit role checks (User.IsInRole or Roles.IsUserInRole), or by using PrincipalPermission demands. You can do the latter either imperatively in the body of a method or declaratively by adding attributes to your classes and methods.

To use explicit role checks:

• Use the IPrincipal interface of the User object attached to the current HTTP request. This approach works with ASP.NET versions 1.0, 1.1. and 2.0. When using Windows authentication, make sure to use the domainName\userName

Page 214 ASP.NET MATERIAL format for the user name and the format domainName\groupName for the group name. • if(User.IsInRole(@"DomainName\Manager")) • // Perform restricted operation • else • // Return unauthorized access error.

• Alternatively, use role manager APIs introduced in ASP.NET version 2.0, which supports a similar Roles.IsUserInRole method, as shown here. • if(Roles.IsUserInRole(@"DomainName\Manager")) • // Perform restricted operation • else • // Return unauthorized access error.

To use the role manager API, you must enable role manager. With Windows authentication, you can use the built-in AspNetWindowsTokenRoleProvider, which uses Windows groups as roles. To enable role manager and select this provider, add the following configuration to your Web.config file.

When you use Windows authentication, you can use alternate role providers, such as the AuthorizationStoreRoleProvider and SqlRoleProvider, if you need to store roles in alternate role stores such as Authorization Manager policy stores or SQL Server databases.

To use PrincipalPermission demands

• Construct a PrincipalPermission object, and then call its Demand method to perform authorization. • For fine grained authorization, call PrincipalPermission.Demand within code, as shown here. • using System.Security.Permissions; • ... • // Imperative checks • PrincipalPermission permCheckUser = new PrincipalPermission(@"Domain\Bob", null); • permCheckUser.Demand();

• Alternatively, you can decorate your classes or methods with the PrincipalPermissionAttribute, as shown here.

Page 215 ASP.NET MATERIAL • using System.Security.Permissions; • ... • [PrincipalPermission(SecurityAction.Demand,Role=@"Builtin\Admini strators")].

• Forms Based Authentication:

ASP.NET Forms Authentication:

ASP.NET forms authentication occurs after IIS authentication is completed. You can configure forms authentication with the forms element.

Forms Authentication Configuration:

The default attribute values for forms authentication are shown in the following configuration-file fragment.

The default attribute values are described below:

• loginUrl points to your application's custom logon page. You should place the logon page in a folder that requires Secure Sockets Layer (SSL). This helps ensure the integrity of the credentials when they are passed from the browser to the Web server. • protection is set to All to specify privacy and integrity for the forms authentication ticket. This causes the authentication ticket to be encrypted using the algorithm specified on the machineKey element, and to be signed using the hashing algorithm that is also specified on the machineKey element.

Page 216 ASP.NET MATERIAL • timeout is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie. • name and path are set to the values defined in the application's configuration file. • requireSSL is set to false. This configuration means that authentication cookies can be transmitted over channels that are not SSL-encrypted. If you are concerned about session hijacking, you should consider setting requireSSL to true. • slidingExpiration is set to true to enforce a sliding session lifetime. This means that the session timeout is periodically reset as long as a user stays active on the site. • defaultUrl is set to the Default.aspx page for the application. • cookieless is set to UseDeviceProfile to specify that the application use cookies for all browsers that support cookies. If a browser that does not support cookies accesses the site, then forms authentication packages the authentication ticket on the URL. • enableCrossAppRedirects is set to false to indicate that forms authentication does not support automatic processing of tickets that are passed between applications on the query string or as part of a form POST.

Authorization Configuration:

In IIS, anonymous access is enabled for all applications that use forms authentication. The UrlAuthorizationModule class is used to help ensure that only authenticated users can access a page.

You can configure UrlAuthorizationModule by using the authorization element as shown in the following example.

With this setting, all unauthenticated users are denied access to any page in your application. If an unauthenticated user tries to access a page, the forms authentication module redirects the user to the logon page specified by the loginUrl attribute of the forms element.

Forms Authentication Control Flow:

Figure 1 shows the sequence of events that occur during forms authentication.

Page 217 ASP.NET MATERIAL

Figure 1. Forms authentication control flow

1. The user requests the Default.aspx file from your application's virtual directory. IIS allows the request because anonymous access is enabled in the IIS metabase. ASP.NET confirms that the authorization element includes a tag. 2. The server looks for an authentication cookie. If it fails to find the authentication cookie, the user is redirected to the configured logon page (Login.aspx), as specified by the LoginUrl attribute of the forms element. The user supplies and submits credentials through this form. Information about the originating page is placed in the query string using RETURNURL as the key. The server HTTP reply is as follows: 3. 302 Found Location: 4. http://localhost/FormsAuthTest/login.aspx?RETURNURL= %2fFormAuthTest%2fDefault.aspx

5. The browser requests the Login.aspx page and includes the RETURNURL parameter in the query string. 6. The server returns the logon page and the 200 OK HTTP status code. 7. The user enters credentials on the logon page and posts the page, including the RETURNURL parameter from the query string, back to the server.

Page 218 ASP.NET MATERIAL 8. The server validates user credentials against a store, such as a SQL Server database or an Active Directory user store. Code in the logon page creates a cookie that contains a forms authentication ticket that is set for the session.

In ASP.NET 2.0, the validation of user credentials can be performed by the membership system. The Membership class provides the ValidateUser method for this purpose as shown here:

if (Membership.ValidateUser(userName.Text, password.Text)) { if (Request.QueryString["ReturnUrl"] != null) { FormsAuthentication.RedirectFromLoginPage(userName.Text, false); } else { FormsAuthentication.SetAuthCookie(userName.Text, false); } } else { Response.Write("Invalid UserID and Password"); }

9. For the authenticated user, the server redirects the browser to the original URL that was specified in the query string by the RETURNURL parameter. The server HTTP reply is as follows: 10. 302 Found Location: 11. http://localhost/TestSample/default.aspx

12. Following the redirection, the browser requests the Default.aspx page again. This request includes the forms authentication cookie. 13. The FormsAuthenticationModule class detects the forms authentication cookie and authenticates the user. After successful authentication, the FormsAuthenticationModule class populates the current User property, which is exposed by the HttpContext object, with information about the authenticated user. 14. Since the server has verified the authentication cookie, it grants access and returns the Default.aspx page.

Page 219 ASP.NET MATERIAL FormsAuthenticationModule:

ASP.NET 2.0 defines a set of HTTP modules in the machine-level Web.config file. These include a number of authentication modules as shown here:

... ...

Only one authentication module is used for each request. The authentication module that is used depends on which authentication mode has been specified by the authentication element, usually in the Web.config file in the application's virtual directory.

The FormsAuthenticationModule class is activated when the following element is in the Web.config file.

The FormsAuthenticationModule class constructs a GenericPrincipal object and stores it in the HTTP context. The GenericPrincipal object holds a reference to a FormsIdentity instance that represents the currently authenticated user. You should allow forms authentication to manage these tasks for you. If your applications have specific requirements, such as setting the User property to a custom class that implements the IPrincipal interface, your application should handle the PostAuthenticate event. The PostAuthenticate event occurs after the FormsAuthenticationModule has verified the forms authentication cookie and created the GenericPrincipal and FormsIdentity objects. Within this code, you can construct a custom IPrincipal object that wraps the FormsIdentity object, and then store it in the HttpContext. User property.

Forms Authentication Cookies:

The FormsAuthentication class creates the authentication cookie automatically when the FormsAuthentication.SetAuthCookie or FormsAuthentication.RedirectFromLoginPage methods are called.

The following properties are included in a typical forms authentication cookie:

Page 220 ASP.NET MATERIAL • Name. This property specifies the name of the cookie. • Value. This property specifies value of the cookie.

In a typical forms authentication cookie, the value contains a string representation of the encrypted and signed FormsAuthenticationTicket object. The cookie contains the following properties:

• Expires. This property specifies the expiration date and time for the cookie. Forms authentication only sets this value if your code indicates that a persistent forms-authentication cookie should be issued. • Domain. This property specifies the domain with which the cookie is associated. The default value is null. o HasKeys. This property indicates whether the cookie has subkeys. • HttpOnly. This property specifies whether the cookie can be accessed by client script. In ASP.NET 2.0, this value is always set to true. Internet Explorer 6 Service Pack 1 supports this cookie attribute, which prevents client-side script from accessing the cookie from the document.cookie property. If an attempt is made to access the cookie from client-side script, an empty string is returned. The cookie is still sent to the server whenever the user browses to a Web site in the current domain. • Path. This property specifies the virtual path for the cookie. The default value is "/", indicating root directory. • Secure. This property specifies whether the cookie should only be transmitted over an HTTPS connection. The Secure property should be set to true so that the cookie is protected by SSL encryption. • Version. This property specifies the version number of the cookie.

Creating the Forms Authentication Cookie:

The forms authentication cookie is created by the FormsAuthentication class as follows. Once the user is validated, the FormsAuthentication class internally creates a FormsAuthenticationTicket object by specifying the cookie name; the version of the cookie; the directory path; the issue date of the cookie; the expiration date of the cookie; whether the cookie should be persisted; and, optionally, user-defined data.

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "userName", DateTime.Now, DateTime.Now.AddMinutes(30), // value of time out property false, // Value of IsPersistent property String.Empty, FormsAuthentication.FormsCookiePath);

Page 221 ASP.NET MATERIAL Next, forms authentication uses the Encrypt method for encrypting and signing the forms authentication ticket, if the protection attribute of the forms element is set to All or Encryption. string encryptedTicket = FormsAuthentication.Encrypt(ticket);

The following text shows the process used when the protection attribute is set to All:

• Create a serialized forms authentication ticket. A byte array representation of the ticket is created. • Sign the forms authentication ticket. The message authentication code (MAC) value for the byte array is computed by using the algorithm and key specified by the validation and validationKey attributes of the machineKey element. By default, the SHA1 algorithm is used. • Encrypt forms authentication ticket. The second byte array that has been created is encrypted by using the Encrypt method of the FormsAuthentication class. The Encrypt method internally uses the algorithm and key specified by the decryption and decryptionKey attributes on the machineKey element. ASP.NET version 1.1 uses the 3DES algorithm by default. ASP.NET version 2.0 uses the Rinjdael (AES) algorithm by default. • Create HTTP cookie or query string as appropriate. The encrypted authentication ticket is then added to an HttpCookie object or query string if forms authentication is configured for cookieless authentication. The cookie object is created using the following code: • HttpCookie authCookie = new HttpCookie( • FormsAuthentication.FormsCookieName, • encryptedTicket);

• Set forms authentication cookie as secure. If the forms authentication ticket is configured to use SSL, the HttpCookie. Secure property is set to true. This instructs browsers to only send the cookie over HTTPS connections. • authCookie.Secure = true;

• Set theHttpOnly bit. In ASP.NET 2.0, this bit is always set. • Set appropriate cookie attributes. If needed, set the path, domain and expires attributes of the cookie. • Add the cookie to the cookie collection. The authentication cookie is added to the cookie collection to be returned to the client browser. • Response.Cookies.Add(authCookie);

Page 222 ASP.NET MATERIAL Each time a subsequent request is received after authentication, the FormsAuthenticationModule class retrieves the authentication ticket from the authentication cookie, decrypts it, computes the hash value, and compares the MAC value to help ensure that the cookie has not been tampered with. Finally, the expiration time contained inside of the forms authentication ticket is verified.

Note ASP.NET does not depend on the expiration date of the cookie because this date could be easily forged.

Role Authorization:

In ASP.NET 2.0, role authorization has been simplified. You no longer need to retrieve role information when the user is authenticated or add role details to the authentication cookie. The .NET Framework 2.0 includes a role management API that enables you to create and delete roles, and add users to and remove users from roles. The role management API stores its data in an underlying data store that it accesses through an appropriate role provider for that data store. The following role providers are included with the .NET Framework 2.0 and can be used with forms authentication:

• SQL Server. This is the default provider and it stores role information in a SQL Server database. • Authorization Manager (AzMan). This provider uses an AzMan policy store in an XML file, in Active Directory, or in Active Directory Application Mode (ADAM) as its role store. It is typically used in an intranet or extranet scenario where Windows authentication and Active Directory are used for authentication.

. Cookieless Forms Authentication:

ASP.NET 2.0 supports cookieless forms authentication. This feature is controlled by the cookieless attribute of the forms element. This attribute can be set to one of the following four values:

• UseCookies. This value forces the FormsAuthenticationModule class to use cookies for transmitting the authentication ticket. • UseUri. This value directs the FormsAuthenticationModule class to rewrite the URL for transmitting the authentication ticket. • UseDeviceProfile. This value directs the FormsAuthenticationModule class to look at the browser capabilities. If the browser supports cookies, then cookies are used; otherwise, the URL is rewritten. • AutoDetect. This value directs the FormsAuthenticationModule class to detect whether the browser supports cookies through a dynamic detection mechanism. If the detection logic indicates that cookies are not supported, then the URL is rewritten.

Page 223 ASP.NET MATERIAL If your application is configured to use cookieless forms authentication and the FormsAuthentication.RedirectFromLoginPage method is being used, then the FormsAuthenticationModule class automatically sets the forms authentication ticket in the URL. The section of the URL that is in parentheses contains the data that the cookie would usually contain. This data is removed by ASP.NET during request processing. This step is performed by the ASP.NET ISAPI filter and not in an HttpModule class. If you read the Request.Path property from an .aspx page, you won't see any of the extra information in the URL. If you redirect the request, the URL will be rewritten automatically.

• Passport Authentication Provider

Passport authentication is a centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites. This benefits the user because it is no longer necessary to log on to access new protected resources or sites. If you want your site to be compatible with Passport authentication and authorization, this is the provider you should use. This topic provides some introductory material about Microsoft .NET Passport and the ASP.NET support for it. For more information, see the Passport documentation located at http://www.passport.com/business. In order to access the documentation, you must get a Passport and register.

Passport is a cookies-based authentication service. A sample transaction conversation using Passport authentication might look similar to the following:

1. A client issues an HTTP GET request for a protected resource, such as http://www.contoso.com/default.aspx. 2. The client's cookies are examined for an existing Passport authentication ticket. If the site finds valid credentials, the site authenticates the client. If the request does not include a valid authentication ticket, the server returns status code 302 and redirects the client to the Passport Logon Service. The response includes a URL in the query string that is sent to the Passport logon service to direct the client back to the original site. 3. The client follows the redirect, issues an HTTP GET request to the Passport logon server, and transmits the query string information from the original site. 4. The Passport logon server presents the client with a logon form. 5. The client fills out the form and does a POST back to the logon server, using Secure Sockets Layer (SSL).

Page 224 ASP.NET MATERIAL 6. The logon server authenticates the user and redirects the client back to the original URL (http://www.contoso.com/default.aspx). The response contains an encrypted Passport cookie in the query string. 7. The client follows the redirect and requests the original protected resource again, this time with the Passport cookie. 8. Back on the originating server, the PassportAuthenticationModule detects the presence of the Passport cookie and tests for authentication. If successful, the request is then authenticated.

Subsequent requests for protected resources at the site are authenticated at the originating server using the supplied ticket. Passport also makes provisions for ticket expiration and reusing tickets on other member sites.

Passport uses the Triple DES encryption scheme. When member sites register with Passport, they are granted a site-specific key. The Passport logon server uses this key to encrypt and decrypt the query strings passed between sites.

The ASP.NET PassportAuthenticationModule provides a wrapper around the .NET Passport SDK for ASP.NET applications, and provides Passport authentication services and profile information from an IIdentity-derived class called PassportIdentity.

As is the case with WindowsIdentity, the primary purpose of handling the PassportAuthentication_OnAuthenticate event is to attach a custom IPrincipal object to the context. A special IIdentity-derived class called PassportIdentity provides an interface to the Passport profile information and methods to encrypt and decrypt Passport authentication tickets.

To implement Passport authentication in an ASP.NET application:

1. Download, install, and configure the .NET Passport SDK from http://www.passport.com/business. You must complete a registration form to obtain the SDK. Windows Server 2003 includes the .NET Passport SDK and does not require this step. 2. Set up Passport as the authentication mode in the application configuration file as follows.

3. Using the Passport documentation and the .NET Passport SDK functionality, implement Passport authentication and authorization.

Page 225 ASP.NET MATERIAL XML WEB SERVICES

Introduction:

It may be necessary to have your in-process COM components run on a different server than Microsoft® Internet Information Server (IIS), using Active Server Pages (ASP) technology to create an instance of your object and execute your application. An example of this would be the creation of a distributed (n-tier) environment in which you separate your components from the main Web server, therefore making your application scalable while taking system load off the main Web server.

In this article, I would like to present a solution for managing your in-process COM components, using Microsoft Transaction Server (MTS), a sample Microsoft Visual Basic® component, and ASP technology. We will take advantage of an n-tier architecture on two different servers running MTS. One server will host the in-process COM components under MTS, while the other server will run IIS to handle the incoming HTTP requests.

An MTS component is a type of COM component that executes in the MTS run-time environment. In addition to the COM requirements, MTS requires that the component be a dynamic-link library (DLL). Components that are implemented as executable files (.exe files) cannot execute in the MTS run-time environment. For example, if you build a Remote Automation server executable file, you must rebuild it as a DLL.

Exercise caution when registering a standard COM component (one developed without regard to MTS) to execute under MTS control.

First, ensure that references are safely passed between contexts.

Second, if the component uses other components, consider running them under MTS. Rewrite the code for creating objects in these components to use CreateInstance.

You can call MTS components from ASP files. You can create an MTS object from an ASP file by calling Server.CreateObject. Note that if the MTS component has implemented the OnStartPage and OnEndPage methods, the OnStartPage method is called at this time.

You can run your MTS components in-process with IIS, but be aware that if MTS encounters an unexpected internal error condition or an unhandled application error, such as a general-protection fault inside a component method call, it immediately results in a failfast, thus terminating the process and IIS.

Page 226 ASP.NET MATERIAL If both the server and client computer are running MTS, you can distribute a package by "pulling" and "pushing" components between one or more computers. Pushing components means creating remote component entries on remote computers. Once the remote component entries are created, you have to add those component entries to your Remote Components folder on your local machine (pull the components).

The following diagram illustrates pushing and pulling components to configure a remote computer running MTS.

You can push and pull components only if a shared network directory has been established for storage and delivery of DLLs and type library files. (You can choose any shared directory as long as the component files are contained within one of the folders or subfolders of the shared directory.) The MTS Explorer will automatically locate available shared network directories on servers. On a given server you can have multiple shared directories to access different sets of component files.

Figure 1.

Page 227 ASP.NET MATERIAL Requirements:

• MTS needs to be installed on both local and remote machines. • You must log on using a Microsoft Windows NT® account that is a member of the Administrator's role of the System Package on the target computer. • The target computer's System Package identity must map to a Windows NT account that is in the Reader role for your System Package. • Security must be enabled for the System Package on both computers.

MTS Packages:

Before MTS can host an in-process component in its process space, it needs to have a package created. The package, which can easily be created in the MTS Explorer, is a collection of components that run in the same process.

Creating packages is the final step in the development process. Package developers and advanced system and Web administrators use the MTS Explorer to create and deploy packages. You use the Explorer to implement the package and component configuration that is determined during development of the application.

Packages define the boundaries for a server process running on a server computer. For example, if you group a sales component and a purchasing component in two different packages, these two components will run in separate processes with process isolation. Therefore, if one of the server processes terminates unexpectedly (such as an application fatal error), the other package can continue to execute in its separate process.

A big advantage of using MTS packages is that you can specify a package identity, and all the components contained in the same package will use that identity when accessing and launching its components. This is very useful when the authenticated user (e.g., anonymous) does not have sufficient permissions to access and launch certain components.

On the Local Machine:

We wrote an ActiveX DLL with Visual Basic, using the following class and one method that returns the user context by calling the GetUserName API:

Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long Public Function WhoAmI() As String Dim sBuff$ Dim lConst& Dim lRet&

Page 228 ASP.NET MATERIAL Dim sName As String lConst& = 199 sBuff$ = Space$(200) lRet& = GetUserName(sBuff$, lConst&) WhoAmI = Trim$(Left$(sBuff$, lConst&)) End Function

After compiling and registering the component on the local machine, we need to create an empty package to host the remote component within the MTS Explorer.

To create an empty package

1. In the left pane of MTS Explorer, select the computer for which you want to create a package. 2. Open the Packages Installed folder for that computer. 3. On the Action menu, click New. You can also select the Package Installed folder and either right-click and select New and then Package from the menu, or select the Create a new object button on the MTS toolbar. 4. Use the Package wizard to install either a pre-built package or to create an empty package. If you create an empty package, you must add components and roles before it will be functional. 5. Click the Create an empty package button. 6. Type a name for the new package, and click Next. 7. Specify the package identity in the Set Package Identity dialog box, and then click the Finish button.

Page 229 ASP.NET MATERIAL

Figure 2.

The default selection for package identity is Interactive User. The interactive user is the user that logged on to the server computer on which the package is running. If nobody is logged on to that server computer, any requests to execute this package will fail, therefore it is recommended to specify a different user. You can select a different user by selecting the This user option and entering a specific Windows NT user or group.

In many deployment scenarios, it is preferable to run a package as a Windows NT user account. If a package runs as a single Windows NT user account, you can configure database access for that account rather than for every client that uses the package. Permitting access to accounts rather than individual clients improves the scalability of your application.

Page 230 ASP.NET MATERIAL When you would like to access network resources within the same NT domain, you'll need to specify an existing NT domain user account; otherwise, you'll have to copy the local NT user account onto the each network resource you'd like to access.

By defining an identity, you are able to change user context between the user making the request and the user running the component. This way you can overcome the "double- hop" problem when using NTLM Authentication on the server.

On the Remote Machine:

Once the local component entries are created, you have to add those component entries to your Remote Components folder on your remote machine (pull the components).

To add remote components, you must first add the appropriate computer or computers to your MTS Explorer and then add your components to the remote computer's Remote Components folder.

Be sure that the remote components you want to add to your server are not already registered on that server. This usually happens when you're migrating from a centralized environment using only one server to a distributed environment using multiple servers. You can easily unregister existing components by using the regsvr32 command with the /u switch.

To add components to the remote computer's Remote Components folder

1. Add the remote computer by selecting the Computers folder and clicking New in the Action menu. 2. Type a name for the computer you want to add, and then click OK. If you do not know the name, you can click the Browse button to select a computer. 3. In the MTS Explorer, open the Remote Components folder of the computer to which you want to add remote components. 4. On the Action menu, click New. You can also right-click and select New and then Component from the menu. 5. In the dialog box that appears, select the remote computer and package that contain the component you want to invoke remotely. 6. From the Available Components list, select the component that you want to invoke remotely, and click the down arrow (Add). This adds the component and the computer on which it resides to the Components to configure on box. If you click the Details checkbox, the Remote Computer, Package, and Path for DLLs are displayed in the Components to configure ondialog box. 7. Click OK.

Page 231 ASP.NET MATERIAL

Figure 3.

Creating the ASP File:

Now that we have done all the necessary steps to register the component with MTS, we can write an ASP file with the following code written in Visual Basic Scripting Edition (VBScript):

<%@ Language=VBScript %> <% Set oWhoAmIObject = Server.CreateObject ("WhoAmIComponent.WhoAmIClass") Response.Write "Who Am I: " & CStr(oWhoAmIObject.WhoAmI()) & "
" Set oWhoAmIObject = Nothing %>

In this script we create an instance of our component using Server.CreateObject with the corresponding PROGID. You can find this PROGID in the MTS explorer under Remote Components. Now that we have created an instance of our object, we can call our method and write the results back to the client. We need to be sure that after usage of our object instance, we do our own clean up by setting the object to Nothing.

Note We are instantiating our object in Page Scope. Using Page Scope will prevent us from using more system resources than necessary; it will create and destroy the object

Page 232 ASP.NET MATERIAL within the running page, therefore releasing the used memory and threads. If you need to maintain state between HTTP requests, you should still use Page Scope to create instances of your objects, but store state information such as variables into Session Scope. Another alternative to maintain state is to store variables in hidden form fields.

The last thing we need to do is to save this ASP file to the virtual directory on the IIS machine. We're now able to execute this ASP file from a browser, as shown in Figure 4.

Figure 4. The ASP file as viewed in a browser.

Our request is being executed on the IIS machine, which in turn will make a request to MTS to create an instance of our object. Since MTS has this component registered as a remote component it will call the MTS package running on our local server, which will load the requested DLL into its memory space, create an instance of the requested object, and have the ASP code execute methods on it. Finally, we release our object instance, and we have finished our page.

DCOM versus Web Services

DCOM Introduction:

DCOM is based on the original Distributed Computing Environment (DCE) standard Remote Procedure Call (RPC) infrastructure and was created as an extension of Component Object Model (COM) to allow the creation of server objects on remote machines. In order for COM to create remote objects, the COM libraries need to know the network name of the server. Once the server name and CLSID (a globally unique identifier representing a COM Class within the server) are known, the Service Control Manager (SCM) on the client machine connects to the SCM on the server machine and requests creation of the remote machine's server object. Because DCOM is an extension of COM, it relies on the registry and COM libraries to supply the type library information of the object to create on the remote server machine. The remote server name is either

Page 233 ASP.NET MATERIAL configured in the registry or passed as an explicit parameter to a CoCreateInstanceEx call (in Visual Basic, this would be a CreateObject call).

Sub StartIE() Dim strProgID As String Dim oIE As InternetExplorer

StrProgID = "InternetExplorer.Application.1"

Set oIE=CreateObject(strProgID, "Defiant.waz.com")

End Sub

The DCOM configuration tool (Dcomcnfg.exe) is provided as an alternative way to set the remote machine name and security settings rather than editing the registry directly. Some configuration is usually done on the both the client and server machines. Security settings are configured on the server machine, whereas the remote machine name is configured on the client machine.

After the release of MTS, Microsoft Windows® 2000, and COM+, remote object activation became a little easier. Developers could install their components (in process and out of process) as configured server application components under COM+ or as server packages in MTS. COM+ and MTS provided the surrogate server process that allowed activation of in process components from remote clients. Both MTS and COM+ facilitate the export of a client proxy in the form of a setup program. Once exported, the proxy setup could be run on the client machines, installing all necessary type library registration and remote server name entries into the registry and the COM+ catalog. Once a remote object activation request is made, the SCM uses the type library information on the client to create a proxy object that would then be used to marshal invocation calls to its corresponding stub object on the remote server.

But DCOM wasn't perfect; it introduced new complexities. Like COM, whenever a server-side component is updated using DCOM, the type library information changes due to binary incompatibility. With DCOM, these changes need to be propagated to existing client machines. DCOM doesn't provide a mechanism for dynamically updating and binding to type library information; such information is stored in the registry, or with COM+ in the COM+ catalog. DCOM is a "chatty" protocol, pinging clients regularly to see if the clients are still alive. And because it doesn't support batch operations, it takes almost a dozen roundtrips to the remote server to complete a single method call. Using DCOM through firewalls becomes problematic because it dynamically allocates one port per process (configurable through the registry) and requires UPD and TCP ports 135-139 to be open. An alternative for enabling DCOM through firewalls exists by defining Tunneling TCP/IP as the underlying transport protocol. This allows DCOM to operate through some firewalls via port 80. But it's not very reliable, doesn't work through all

Page 234 ASP.NET MATERIAL firewalls, and introduces other limitations (lack of callback support, etc.). DCOM has certainly evolved over the years, in an effort to accommodate the demands of a changing environment. But because of its roots in older binary and component-based protocols, it still fails to deliver the flexibility needed in today's enterprise. DCOM is still inefficient, cumbersome to deploy and requires a fair amount of manual maintenance.

XML Web Services Introduction:

XML Web services are based on open Web standards that are broadly supported and are used for communication and data formats. XML Web services provide the ability to expose application logic as URI-addressable resources, available to any client in a platform-independent way. COM-style type library information is no longer required on the client's machine and the Dcomcnfg.exe utility is no longer needed for distributed application configuration because Web services are self-describing. Any clients incorporating open Web standards for communication and data formatting (HTTP and XML) can query dynamically for Web service information and retrieve an XML document describing the location and interfaces supported by a particular XML Web service. These open standards make Web services indifferent to the operating system, object model, and programming language used. Web services are accessible to disparate systems, supporting application interoperability to an unprecedented level thanks to the ubiquity of HTTP and XML.

Instead of binary communication methods between applications, Web services use XML- encoded messages. Because XML-based messaging is used for the data interchange, a high level of abstraction exists between a Web service implementation and the client. This frees the client from needing to know anything about a Web service except for its location, method signatures, and return values. Additionally, most Web services are exposed and accessed via HTTP, virtually eliminating firewall issues.

Web services are not the ideal solution for all application models. Because it usually uses the HTTP transport and XML encoding, it's not as efficient or reliable as a binary protocol. On local Intranets, WANs, and LANs, .NET Remoting is a more appropriate solution.

For Web services to provide a level of interoperability, loosely coupled programming models, and communication, they depend on an infrastructure that provides the following standards-based protocols:

• SOAP : The explicit messaging protocol used in Web service message exchanges. Although HTTP is used by XML Web services to provide the SOAP message transport protocol, it is not presumed. SMTP may be used with SOAP as well. XML is the format in which the message is serialized before being bound to the transport protocol.

Page 235 ASP.NET MATERIAL • WSDL : Web Service Description Language (WSDL 1.1) is the grammar describing the location and interfaces that a particular Web service supports. A Web service uses it to deliver an XML-formatted document to any requesting client. In the COM world, WSDL can be seen as synonymous to a type library. WSDL is considered the "contract" for a Web service. • DISCO : This is a Web Service Discovery mechanism. DISCO is the grammar used to describe the Uniform Resource Identifier (URI) of a Web service and contains references to the WSDL location. It usually resides at the root of a Web application and exists as an XML-formatted file. • UDDI : Universal Description Discovery and Integration is the directory for all Web services. This is a protocol that allows businesses to publish their developed Web services to a central directory so that they can be easily found and consumed by other business clients. • XML : Extensible Markup Language is a commonly used language for Internet- ready documents and development. Data is returned from a Web service in XML. If the Web service is invoked using SOAP, the parameters are also sent to the Web service method in XML.

A common scenario for a client that consumes application logic from a Web service might be (see Figure 1):

1. The client queries a UDDI directory over HTTP for the location of a Web service. 2. The client queries the Web service over HTTP for the location of the Web service's WSDL location via DISCO. This information is returned to the client in an XML-formatted message. 3. The client retrieves the WSDL information for the Web service. This information is returned in an XML message using the WSDL grammar. The client uses the WSDL information to dynamically determine the interfaces and return types available from the Web service. 4. The client makes XML/SOAP-encapsulated message calls to the Web service that conform to the WSDL information.

Page 236 ASP.NET MATERIAL

Figure 1. Web Service infrastructure example

DCOM versus Web Services:

DCOM enabled software developers to create applications that span multiple machine, network, and location boundaries, allowing scalability and ease-of-distribution across multiple tiers. Although additional complexity was introduced into the development effort, most of the benefits provided by DCOM (e.g., location independence, security and scalability) were realized to varying degrees. After the release of MTS and COM+, DCOM became easier to implement and became the standard protocol employed among

Page 237 ASP.NET MATERIAL most Microsoft solution providers. Later, Microsoft Application Center was released and provided load balancing and fault tolerance to COM+ components.

As the Internet evolves, the nature and scope of distributed applications must change to meet the underlying business needs. Businesses must integrate their applications with those that reside on heterogeneous platforms, and those that are built and deployed with varying programming models. Additionally, businesses need to communicate and expose their services to global clients and partners.

To address these needs, XML Web services were introduced as part of ASP.NET, which is part of the .NET Framework. Web services are based on open Internet standards, such as HTTP, XML, and SOAP. Using these open standards, Web services deliver application functionality across the Web to any type of client, on any platform.

Although XML Web services is the enabling technology, it is Visual Studio .NET that encapsulates its ease of use for developers. Visual Studio .NET provides a robust environment that allows the easy creation, deployment, and maintainability of applications developed using XML Web services.

• Role of WSDL-.NET Support for Xml Web Services:

WSDL is a specification defining how to describe web services in a common XML grammar. WSDL describes four critical pieces of data:

• Interface information describing all publicly available functions • Data type information for all message requests and message responses • Binding information about the transport protocol to be used • Address information for locating the specified service

In a nutshell, WSDL represents a contract between the service requestor and the service provider, in much the same way that a Java interface represents a contract between client code and the actual Java object. The crucial difference is that WSDL is platform- and language-independent and is used primarily (although not exclusively) to describe SOAP services.

Using WSDL, a client can locate a web service and invoke any of its publicly available functions. With WSDL-aware tools, you can also automate this process, enabling applications to easily integrate new services with little or no manual code. WSDL therefore represents a cornerstone of the web service architecture, because it provides a

Page 238 ASP.NET MATERIAL common language for describing services and a platform for automatically integrating those services.

This chapter covers all aspects of WSDL, including the following topics:

• An overview of the WSDL specification, complete with detailed explanations of the major WSDL elements • Two basic WSDL examples to get you started • A brief survey of WSDL invocation tools, including the IBM Web Services Invocation Framework (WSIF), SOAP::Lite, and The Mind Electric's GLUE platform • A discussion of how to automatically generate WSDL files from existing SOAP services • An overview of using XML Schema types within WSDL, including the use of arrays and complex types

The WSDL Specification:

WSDL is an XML grammar for describing web services. The specification itself is divided into six major elements:

Definitions: The definitions element must be the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here. Types: The types element describes all the data types used between the client and server. WSDL is not tied exclusively to a specific typing system, but it uses the W3C XML Schema specification as its default choice. If the service uses only XML Schema built-in simple types, such as strings and integers, the types element is not required. A full discussion of the types element and XML Schema is deferred to the end of the chapter. Message: The message element describes a one-way message, whether it is a single message request or a single message response. It defines the name of the message and contains zero or more message part elements, which can refer to message parameters or message return values. PortType: The portType element combines multiple message elements to form a complete one-way or round-trip operation. For example, a portType can combine one request and one response message into a single request/response operation, most

Page 239 ASP.NET MATERIAL

commonly used in SOAP services. Note that a portType can (and frequently does) define multiple operations. Binding: The binding element describes the concrete specifics of how the service will be implemented on the wire. WSDL includes built-in extensions for defining SOAP services, and SOAP-specific information therefore goes here. Service: The service element defines the address for invoking the specified service. Most commonly, this includes a URL for invoking the SOAP service.

To help you keep the meaning of each element clear, Figure 6-1 offers a concise representation of the WSDL specification. As you continue reading the remainder of the chapter, you may wish to refer back to this diagram.

Figure 6-1. The WSDL specification in a nutshell

In addition to the six major elements, the WSDL specification also defines the following utility elements:

Documentation: The documentation element is used to provide human-readable documentation and can be included inside any other WSDL element. Import: The import element is used to import other WSDL documents or XML Schemas. This enables more modular WSDL documents. For example, two WSDL documents can import the same basic elements and yet include their own service elements to make the same service available at two physical addresses. Note, however, that not all WSDL tools support the import functionality as of yet.

Page 240 ASP.NET MATERIAL • Client Apps for WebServices :

We use an external web service from our application. It was working fine with out any issues, but from the past two days we are getting the error “The request failed with HTTP status 401: Unauthorized”. We got one more error while debugging with fiddler “your Web browser is sending WWW-Authenticate header field that the Web server is not configured to accept”. There are no code changes in our app and the target web service too.

In our IIS 6.0 and windows server 2003 (latest service packs applied) we have the following settings

1. Integrated Windows Authentication Checked

2. Enable Anonymous Access is unchecked

3. App pool runs under a service account.

4. Web.config configuration

A sample code is mentioned below. If we run the code from Visual studio, it works fine with out issues. But when the code is built, published and deployed on a web server and access the site from a client(Web Browser), we get the error “The request failed with HTTP status 401: Unauthorized” when the application hits the web service.

We have tried the following codes to replace System.Net.CredentialCache.DefaultCredentials also, but it is not working 1)System.Net.CredentialCache cache = new System.Net.CredentialCache(); cache.Add(new Uri("https://xxx/xxx.asmx"), "NTLM", System.Net.CredentialCache.DefaultCredentials.GetCredential(new Uri("https://xxx/xxx.asmx"), "NTLM")); webProxy.Credentials = cache; 2) webProxy.Credentials = new System.Net.NetworkCredential(“uname”,”pwd”,”domain”)-This worked but we cant use it,since uid and pwd needs to be hard coded. 3) webProxy.UseDefaultCredentials = true; webProxy.PreAuthenticate = true;

Issue seems to be appearing in the bold text portion below.

Page 241 ASP.NET MATERIAL protected void Button1_Click(object sender, EventArgs e) { try { bool flag = true; String GetIO = ""; TrialService.OService webProxy = new TrialService.OService(); webProxy .Url = "https://xxx/xxx.asmx"; if (flag) { ImpersonateUser(); } webProxy .Credentials = System.Net.CredentialCache.DefaultCredentials; System.Xml.XmlNode xmlNode = webProxy .OBlock(); GetIO = xmlNode.OuterXml; TextBox1.Text = GetIO; } catch (Exception ex) { TextBox1.Text = ex.Message; } }

*Code for Impersonate User *

private void ImpersonateUser() { System.Security.Principal.WindowsPrincipal wp = (System.Security.Principal.WindowsPrincipal)System.Threading.Thread.CurrentPrincipa l; System.Security.Principal.WindowsIdentity windowsIdentity = (System.Security.Principal.WindowsIdentity)p.Identity; wc = windowsIdentity.Impersonate();

}

Page 242 ASP.NET MATERIAL • WSDL Utility :

The Web Services Description Language tool generates code for XML Web services and XML Web service clients from WSDL contract files, XSD schemas, and .discomap discovery documents.

Remarks:

Argument Description The URL to a WSDL contract file (.wsdl), XSD schema file (.xsd), or URL discovery document (.disco). Note that you cannot specify a URL to a .discomap discovery document. The path to a local WSDL contract file (.wsdl), XSD schema file (.xsd), or discovery document (.disco or .discomap).

Note: Path Wsdl.exe does not retrieve includes and imports from the network when it is given a local file. To enable Wsdl.exe to retrieve network resources while processing a local file, pass a URL to the local file. For example, the following file uses the network to retrieve necessary resources: wsdl File:///E:/Customers/WSDLS/Accounts.wsdl /out:proxy.cs Option Description /appsettingurlkey:key Specifies the configuration key to use to read the default value for the URL property when generating code. When or using the /parameters option, this value is the element and contains a string. /urlkey:key Specifies the base URL to use when calculating the URL /appsettingbaseurl:baseurl fragment. The tool calculates the URL fragment by converting the relative URL from the baseurl argument to or the URL in the WSDL document. You must specify the /appsettingurlkey option with this option. When using the /baseurl:baseurl /parameters option, this value is the element and contains a string. Specifies the domain name to use when connecting to a server that requires authentication. When using /d[omain]:domain the /parameters option, this value is the element and contains a string. /l[anguage]:language Specifies the language to use for the generated proxy class. You can specify CS (C#; default), VB (Visual Basic), JS (JScript) or VJS (Visual J#) as the language argument. You can also specify the fully-qualified name of a class that

Page 243 ASP.NET MATERIAL implements the System.CodeDom.Compiler.CodeDomProvider Class. When using the /parameters option, this value is the element and contains a string. Specifies the namespace for the generated proxy or template. The default namespace is the global namespace. When using /n[amespace]:namespace the /parameters option, this value is the element and contains a string. This element must be in the parameters file. Suppresses the Microsoft startup banner display. When using /nologo the /parameters option, this value is the element and contains either true or false. /order Generates explicit order identifiers on particle members. Specifies the file (or directory) in which to save the generated proxy code. You can also specify a directory in which to create this file. The tool derives the default file /o[ut]:filename or name from the XML Web service name. The tool saves directoryname generated datasets in different files. When using the /parameters option, this value is the element and contains a string. Reads command-line options from the specified XML file. Use this option to pass the Wsdl.exe tool a large number of options at one time. Short form is /par:. Option elements are /parameters contained inside a element. For details, see the Remarks section. Displays errors in a format similar to the error reporting format used by language compilers. When using /parsableerrors the /parameters option, this value is the element and is either true or false. Specifies the password to use when connecting to a server that requires authentication. When using the /parameters /p[assword]:password option, this value is the element and contains a string. Specifies the protocol to implement. You can specify SOAP (default), HttpGet, HttpPost, or a custom protocol specified /protocol:protocol in the configuration file. When using the /parameters option, this value is the element and contains a string. /proxy:URL Specifies the URL of the proxy server to use for HTTP requests. The default is to use the system proxy setting. When using the /parameters option, this value is the

Page 244 ASP.NET MATERIAL element and contains a string. /proxydomain:domain Specifies the domain to use when connecting to a proxy server that requires authentication. When using or the /parameters option, this value is the element and contains a string. /pd:domain /proxypassword:password Specifies the password to use when connecting to a proxy server that requires authentication. When using or the /parameters option, this value is the element and contains a string. /pp:password /proxyusername:username Specifies the user name to use when connecting to a proxy server that requires authentication. When using or the /parameters option, this value is the element and contains a string. /pu:username Generates an abstract class for an XML Web service based on the contracts. The default is to generate client proxy /server classes. When using the /parameters option, this value is a

• Caching with Web services :

Introduction:

Despite advancements in network and processor speeds, performance remains a key concern among application developers. So whether you are writing an XML Web service, pushing image bitmaps to a video card, or even engineering that next great processing chip, you will invariably want to consider utilizing a universal mechanism for improving performance: a cache.

In this At Your Service column, we will look at how you as a developer and consumer of XML Web services can utilize caching. We'll take a look at ways you can do application- level caching with ASP.NET, and will take a look at HTTP caching and its application for XML Web services. Finally, we will look at how we can take the sample MSDN

Page 248 ASP.NET MATERIAL Pencil Company's Discovery service and implement a caching strategy that makes sense for providing a pencil catalog that is updated daily.

Questions to Ponder When Considering Caching Options:

There are a number of ways you could implement various caching capabilities when creating an XML Web service or consuming an XML Web service. However, not all mechanisms for implementing a cache will effectively enhance performance, or even offer the perception of enhanced performance. You must analyze what makes sense in your particular usage scenario. Here are some questions you will want to ask yourself when considering caching functionality for your XML Web service:

How much of my data is dynamic?

It is hardly a foregone conclusion that caching is always a good idea. For instance, if the data returned from an XML Web service is always different, then caching may not help much. However, just because data is dynamic, it doesn't mean that caching is out of the question. If even a portion of the response is relatively static, caching could improve your Web server's performance. Consider a scenario where information is changing, but not changing with each and every request? If you are receiving hundreds of requests a second for your temperature service, for example, you might want to send back cached data for most requests, and only update the data every 5 minutes or so.

Is my data private?

In many cases an XML Web service will deal with user-specific data. This tends to decrease the usefulness of caching—but don't write off caching just because you are dealing with user-specific data. Say your XML Web service has a small number of users; it might make sense to cache information for each user, particularly if the user might request the same information multiple times. Even if a user does not request the same information every time, there may be a common instance of a class that could be referenced for each request from that same user. Be careful when caching private information, however, because bugs in this kind of code may allow private data to be compromised. To play it safe, it might be wise for your code to enforce access restrictions.

Does my XML Web service use resources that I can share between requests?

Caching is not limited to simply caching responses. You may be able to gain significant performance enhancements by caching any sort of application data or resources. It might make sense to keep around a dataset, for instance, to handle multiple queries. The

Page 249 ASP.NET MATERIAL response data may vary depending upon the specific queries on the dataset, but the dataset data itself may remain the same for many requests.

Can I predict the use of future resources?

Consider the usage scenarios for your XML Web service. Are there behaviors that you can predict? Say, for instance, that an XML Web service allows consumers to search for a particular article, and then allows them to download that article. It may make sense to assume that once a successful search has been performed for an article, a download request will soon follow. Your XML Web service can start the potentially lengthy process of loading the article into memory (perhaps from a file or a database), so that it is all set to respond once it receives the request to download the article.

Where do I cache my XML Web service's data?

The correct answer to this question may often be, "everywhere." But what are the different options for caching data? To answer this question let's take a look at the potential XML Web service scenario shown in Figure 1.

Page 250 ASP.NET MATERIAL Figure 1. Caching possibilities for one XML Web service scenario

The figure starts in the upper left with an end user browsing to the Web site located in the yellow box. Unbeknownst to the user, the Web site sits behind an HTTP proxy server. The Web server then makes a SOAP request to a Web service in a different organization (represented by the green box). The SOAP request also goes through an HTTP proxy. The first Web service must then forward the request to a second, internal Web service, the internal Web service queries a Microsoft® SQL Server for the data required, and the response is finally returned. The SQL data is used to build the internal Web service response, and the internal Web service response is used to build the response to the initial Web service. The Web site uses the Web service response to create an HTML page that is returned to the end-user browser.All this happens through the various proxies and routers along the way. So where can the response data be cached? At every point in this scenario: The SQL Server could cache query results. The internal Web service could cache the SQL query results. The initial Web service could cache the results from the internal Web service, and the green organization's HTTP proxy could cache the results as well. The Web server could cache the Web service's response. The yellow organization's proxy could cache the Web server's response, and the end-user's browser could cache the HTML page.

When will my data expire?

One of the key problems when designing caching strategies is determining when the data in the cache should be removed from the cache. Sometimes this is fairly simple to determine, since a process that updates the data may run at regular intervals. However, there may be other situations where the data is updated at relatively random intervals. In either case, the key is to figure out the optimal time interval for updating the cache, so that a balance can be achieved between the harm of returning stale data against the performance improvements provided by returning cached information. Once you have figured out this optimal interval, you can include that information with your data, so that the caching systems can update their data appropriately.

How do I notify consumers of my XML Web service that my data will expire?

The answer to this question depends upon how you are doing your caching. It may make sense for the client application to cache the data. If this is the case, then you need to inform the client application when the data expires. Presumably, applications will need you to include expiration information in the data being returned. For your Web service, this may mean adding a field to the XML response that specifically states an expiration time.If you are depending on other pre-built solutions for performing your cache, these usually provide mechanisms for indicating an expiration time. In the case of using HTTP caching, you can set the HTTP headers that indicate to proxies and client systems when the data expires. ASP.NET includes a cache class that you can insert data into. When

Page 251 ASP.NET MATERIAL inserting the data, you have the ability to specify when the data will be removed from the cache.

Can I depend on the data being in the cache?

The short answer is, no. Almost every caching mechanism ever designed has an algorithm for removing old information from the cache. Data can be removed because it expired, but it can also be removed because it has not been accessed recently and there is other data to be added to the relatively limited cache resource. Therefore, most caching mechanisms do not guarantee that data will remain in the cache. This is particularly true of shared caching mechanisms, such as HTTP proxy caches, or even ASP.NET caches.

What ramifications will there be if consumers of your XML Web service do not use cached data?

There are a number of reasons why data may not be cached. As mentioned above, it could simply be that higher priority data replaced your application's data in the shared cache. It could also be that the developer writing the code to access your XML Web service is not being responsible about reusing data previously acquired. When designing your XML Web service, take into account the possibility for performance improvements based off of caching scenarios, but also allow for cases where your data does not get cached for any number of reasons. You will need to be able to deal with situations where caching is not working optimally.

• Proxy with Asynchronous Methods:

Every Web method on a Web service proxy class has an asynchronous counterpart. The proxy class automatically generates asynchronous methods and a corresponding event for every Web method. When the asynchronous method is called, it executes on another thread and raises its corresponding event when it returns. You can execute code when an asynchronous method returns by creating a handler for its corresponding event.

To call a Web method asynchronously with Visual Basic:

1. Declare an instance of the Web service proxy class using the WithEvents keyword, as shown below: 2. Dim WithEvents myWebService As New Service1. 3. In the Code Editor, use the Handles keyword to create an event handler for the MethodCompleted event that corresponds to the method you want to call. For example, if you were calling a method called HelloWorld asynchronously, you would create a method similar to the following:

Page 252 ASP.NET MATERIAL Private Sub HelloWorldComplete(ByVal sender As Object, _ ByVal completed As localhost.HellowWorldCompletedEventArgs) _ Handles myWebService.HelloWorldCompleted ' Insert code to implement the method here End Sub

4. Call the Web method using the MethodAsync form of the method. For example, if you were calling a Web method called HelloWorld asynchronously, it would look as follows:

HelloWorldAsync

Note that the return value of the method is available in the Result property of the EventArgs.

To call a Web method asynchronously with C#:

1. Declare an instance of the Web service proxy class, as shown below:

private localhost.Service1 myWebService = new localhost.Service1 ();

In the Code Editor, add an event handler for the MethodCompleted event that corresponds to the method you want to call. For example, if you were calling a method called HelloWorld asynchronously, you would create a method similar to the following: private void HelloWorldCompleted(Object sender, localhost.HelloWorldCompletedEventArgs Completed) { // Insert code to implement the method here }

2. In the constructor for the class, add the MethodCompleted event handler to the list of handlers for that event, as shown below:

private void Form1_Load(object sender, EventArgs e) { myWebService.HelloWorldCompleted += new localhost.HelloWorldCompletedEventHandler(HelloWorldCompleted ); }

3. Call the Web method using the MethodAsync form of the method. For example, if you were calling a Web method called HelloWorld asynchronously, it would look as follows:

Page 253 ASP.NET MATERIAL HelloWorldAsync();

• Web Service wire Formats-HTTP Post:

Binary protocols such as DCOM consist of a method request layer riding on top of a proprietary communication protocol. Such protocols are not conducive to creating universally available XML Web services. This does not preclude you from using such protocols in an XML Web service scenario, but the drawback of using them is that such protocols depend on the specific architectures of their underlying systems and therefore limit the spectrum of potential clients.

Alternatively, you can construct XML Web services to work with one or more open protocols, such as a combination of HTTP and SOAP. As you would expect, the infrastructure required to support different protocols will vary.

XML Web services are not limited to providing remote procedure call (RPC) access. They can also be built to exchange structured information, such as purchase orders and invoices, and can be used to automate and connect internal and external business processes.

HTTP-GET and HTTP-POST:

HTTP-GET and HTTP-POST are standard protocols that use HTTP (Hypertext Transfer Protocol) verbs for the encoding and passing of parameters as name/value pairs, along with the associated request semantics. Each consists of a series of HTTP request headers that among other things define what the client is requesting from the server, which responds with a series of HTTP response headers and the requested data if successful.

HTTP-GET passes its parameters in the form of urlencoded text using the MIME type application/x-www-form-urlencoded, which is appended to the URL of the server handling the request. Urlencoding is a form of character encoding that ensures that the passed parameters consist of conforming text, such as encoding a space as %20. The appended parameters are also referred to as a query string.

Similar to HTTP-GET, HTTP-POST parameters are also urlencoded. However, instead of being passed as part of the URL, the name/value pairs are passed inside the actual HTTP request message.

SOAP:

Page 254 ASP.NET MATERIAL SOAP is a simple, lightweight XML-based protocol for exchanging structured and type information on the Web. The overall design goal of SOAP is to keep it as simple as possible, and to provide a minimum of functionality. The protocol defines a messaging framework that contains no application or transport semantics. As a result, the protocol is modular and very extensible.

By traveling over standard transport protocols, SOAP is able to leverage the existing open architecture of the Internet and gain easy acceptance by any arbitrary system capable of supporting the most basic Internet standards. You could view the infrastructure required to support a SOAP-compliant XML Web service as rather simplistic, yet powerful, since it adds relatively little to the existing infrastructure of the Internet and still facilitates universal access to the services built with SOAP.

The SOAP protocol specification consists of four main parts. The first part defines a mandatory extensible envelope for encapsulating data. The SOAP envelope defines a SOAP message and is the basic unit of exchange between SOAP message processors. This is the only mandatory part of the specification.

The second part of the SOAP protocol specification defines optional data-encoding rules for representing application-defined data types and directed graphs, and a uniform model for serializing non-syntactic data models.

The third part defines an RPC-style (request/response) message exchange pattern. Each SOAP message is a one-way transmission. Although SOAP's roots are in RPC, it is not limited to being a request/response mechanism. XML Web services often combine SOAP messages to implement such patterns, but SOAP does not mandate a message exchange pattern and this part of the specification is also optional.

The fourth part of the specification defines a binding between SOAP and HTTP. However, this part is also optional. You can use SOAP in combination with any transport protocol or mechanism that is able to transport the SOAP envelope, including SMTP, FTP, or even a floppy disk.

For the SOAP specification, see the W3C Web site (http://www.w3.org/TR/soap).

• HTTP Post & Get-SOAP Envelope :

SOAP and HTTP GET and POST:

Page 255 ASP.NET MATERIAL All of the recent discussion about when, where and how to use HTTP GET and POST with SOAP has led me to go back and reevaluate the use of SOAP over HTTP and the use of the various core HTTP operations.

First, let's look at the core HTTP 1.1 operations....

Operation Description OPTIONS "Represents a request for information about the communication options available on the request/response chain identified by the Request-URI". In Web Services, this could be interpreted as a request for the WSDL description of the Service. GET "The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data- producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process." HEAD "The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response" POST "The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line" PUT "The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server." DELETE "The DELETE method requests that the origin server delete the resource identified by the Request-URI." TRACE "The TRACE method is used to invoke a remote, application-layer loop- back of the request message." CONNECT "This specification reserves the method name CONNECT for use with a proxy that can dynamically switch to being a tunnel"

Looking these over, there are a couple of things to consider. First, the "resource" identified by the HTTP Request URI is the Web Service itself, not the data that the Web service deals with. The Web Service is a data-producing resource.

That said, a SOAP HTTP GET operation implies a request for the Web Service to produce a SOAP message. (Example 1)

Example 1: SOAP HTTP GET operation

Page 256 ASP.NET MATERIAL Request GET /StockQuoteService?symbol=IBM HTTP/1.1 Host: www.ibm.com Response HTTP/1.1 200 OK Content-Type: application/soap-xml; charset="utf-8" Content-Length: nnnn ...

The HTTP POST operation is a bit strange when it comes to Web services, but based on the language used to describe the POST operation semantics within the HTTP specification, it is extremely clear that the use of POST for a RPC invocation is clearly very wrong. That said, other than GET, there is no other core HTTP Operation that can be used for RPC invocations, therefore, I would go so far as to propose a new HTTP method called "INVOKE".

The INVOKE operation indicates that the operation indicated by the HTTP data entity (the SOAP Envelope) should be invoked against the Web service indicated by the URI. If the INVOKE operation results in a response SOAP Envelope, the HTTP server should respond with a 200 OK response that contains the resulting SOAP envelope. If no response SOAP Envelope is created, the HTTP server should respond with a 204 No Content response.

Example 2: SOAP HTTP INVOKE operation Request INVOKE /StockQuoteService HTTP/1.1 Host: ww.ibm.com Content-Type: application/soap-xml; charset="utf-8" Content-Length: nnnn ... Response HTTP/1.1 200 OK Content-Type: application/soap-xml; charset="utf-8" Content-Length: nnnn ...

Going through this process, we see a number of interesting side effects of applying the various HTTP core operations to Web services.

For example, the PUT and DELETE operations actually map to the deployment and undeployment of Web services. In other words, when you do a "DELETE" against a URI that indicates a Web service, the Web service should be deleted. When you do a "PUT" against a URI, the Web service is deployed.

Page 257 ASP.NET MATERIAL The OPTIONS HTTP method would probably be best for returning the WSDL description for a Web Service since the WSDL is what would be used to express the communication options for the Web Service.

The bottom line is, I'm starting to agree that using HTTP POST for SOAP RPC invocations is not the proper approach. Creating a new INVOKE operation would be.

• UDDI Registry:

-UDDI (Universal Description, Discovery, and Integration) is an XML-based registry for businesses worldwide to list them on the Internet. Its ultimate goal is to streamline online transactions by enabling companies to find one another on the Web and make their systems interoperable for e-commerce. UDDI is often compared to a telephone book's white, yellow, and green pages. The project allows businesses to list themselves by name, product, location, or the Web services they offer.

Microsoft, IBM, and Ariba spearheaded UDDI. The project now includes 130 companies, including some of the biggest names in the corporate world. Compaq, American Express, SAP AG, and Ford Motor Company are all committed to UDDI, as is Hewlett-Packard, whose own XML-based directory approach, called e-speak, is now being integrated with UDDI.

While the group does not refer to itself as a standards body, it does offer a framework for Web services integration. The UDDI specification utilizes World Wide Web Consortium (W3C) and Internet Engineering Task Force (IETF) standards such as XML, HTTP, and Domain Name System (DNS) protocols. It has also adopted early versions of the proposed Simple Object Access Protocol (SOAP) messaging guidelines for cross platform programming.

In November 2000, UDDI entered its public beta-testing phase. Each of its three founders - Microsoft, IBM, and Ariba - now operates a registry server that is interoperable with servers from other members. As information goes into a registry server, it is shared by servers in the other businesses. The UDDI beta is scheduled to end in the first quarter of 2001. In the future, other companies will act as operators of the UDDI Business Registry.

UDDI registration is open to companies worldwide, regardless of their size.

Learn more about UDDI (Universal Description, Discovery and Integration) Mule architect sees REST with rising, UDDI fading: Dan Diephouse, the creator of XFire and software architect at MuleSource Inc., discusses the advantages in using REST

Page 258 ASP.NET MATERIAL and the Atom Publishing Protocol. Boubez: SOA virtualization, SLAs and access control policy: WS-Policy for SOA is good to go but work remains to bring access control and service level agreement policy language specifications, says Toufic Boubez. Anne Thomas Manes: Why SOA needs UDDI now: The original definition of Web services included SOAP, WSDL and UDDI, but the latter was often ignored. UDDI v3.0 is emerging as a key standard for SOA registry and repository. Burton: IBM SOA registry/repository competes with UDDI: The good news is that IBM has produced a technologically solid registry/repository, says a Burton Group report, but the bad news is that it largely ignores UDDI. Utterly UDDI: UDDI stands for Universal Description, Discovery and Integration. Learn all you ever needed to know about UDDI with our white papers, articles, news stories and expert responses. Free UDDI advice: Got questions about UDDI? Systinet CTO Adam Blum is here to lend his expertise. Read his previous answers and pose your own UDDI question anonymously. UDDI Learning Guide: This guide explains what UDDI is, how it's used, and how it fits into the world of Web services. Check back often for updates and new additions. UDDI Crash Course: Need a quick knowledge fix on UDDI? This week we present UDDI articles, tutorials, examples, tips, tools, white papers, expert advice and more to pump up your UDDI know-how. Divorcing SOA and Web services: Jason Bloomberg gives a history of the evolution of SOA and Web services and discusses the common misconception that they are the same thing.

• Securing Web Services :

Web services are used by an increasing number of companies as they expose products and services to customers and business partners through the Internet and corporate extranets. The security requirements for these service providers are of paramount importance. In some cases, primarily intranet or extranet scenarios where you have a degree of control over both endpoints, the platform-based security services provided by the operating system and Internet Information Services (IIS) can be used to provide point-to-point security solutions. However, the message based architecture of Web services and the heterogeneous environments that span trust boundaries in which they are increasingly being used pose new challenges. These scenarios require security to be addressed at the message level to support cross-platform interoperability and routing through multiple intermediary nodes.

Page 259 ASP.NET MATERIAL Web Services Security (WS-Security) is the emerging security standard designed to address these issues. Microsoft has released Web Services Enhancements (WSE) 2.0 for Microsoft .NET 1.1 and WSE 3.0 for .NET 2.0, which supports WS-Security and a related family of emerging standards. WSE allows you to implement message level security solutions including authentication, encryption and digital signatures.

Security Engineering Approach:

Patterns & practices Security Engineering includes specific security-related activities that help you meet your application security objectives as shown in Figure 1.

Security Overlay

Figure 1. Security activities in the application development life cycle

There is a core set of activities common to application development approaches, such as architecture and design reviews, code reviews and deployment reviews. patterns & practices Security Engineering extends these proven core activities to create security specific activities. These activities include:

• Security objectives. • Threat modeling. • Security design guidelines. • Security architecture and design reviews. • Security code reviews.

Page 260 ASP.NET MATERIAL • Security testing. • Security deployment reviews.

Security Engineering Overviews:

To design, build, and deploy secure applications, you must integrate security into your application development life cycle and adapt your current software engineering practices and methodologies to include specific security-related activities. The following overview shows you how to integrate security into your application development:

Security Objectives:

Setting objectives helps you scope and prioritize your work by setting boundaries and constraints. Setting security objectives helps you identify where to start, how to proceed, and when you are done.

Security Design Guidelines:

Creating design guidelines is a common practice at the start of an application project to guide development and share knowledge across the team. Effective design guidelines for security organize security principles, practices, and patterns by actionable categories. See the following security design guidelines resource:

Threat Modeling:

Threat modeling is an engineering technique that can help you identify threats, attacks, vulnerabilities, and countermeasures that could affect your application. You can use threat modeling to shape your application's design, meet your company's security objectives, and reduce risk. See the following Threat Modeling resource:

Security Architecture and Design Reviews:

Security architecture and design reviews are an effective way to identify problems in your application design. By using pattern-based categories and a question-driven approach, you simplify evaluating your design against root cause security issues. See the following security architecture and design review resources.

Security Code Reviews:

Page 261 ASP.NET MATERIAL Many security defects are found during code reviews. Analyzing code for security defects includes knowing what to look for and how to look for it. Security code reviews optimize reviewing code for common security issues. See the following security code review resources:

Security Deployment Reviews:

When you deploy your application during your build process or staging process, you have an opportunity to evaluate runtime characteristics of your application in the context of your infrastructure. Deployment reviews for security focus on evaluating your security design and configuration of your application, host, and network. See the following deployment review resources:

Security Guidelines:

You can use Security Guidelines guidance modules to support the activities above. Security Guidelines are specific, actionable recommendations at the implementation level. Each recommendation is presented to address "what to do", "why", and "how." The recommendations are principle-based and they are organized using pattern-based categories for easy consumption.

Security Practices:

You can use Security Practices guidance modules to support the activities above. Security Practices are proven and emerging practices expressed as precisely as possible. Each practice is presented using a problem and solution format and the set of practices are organized using pattern-based categories.

• IP Address & Domain Registration:

This issue can occur if one of the network adapters is attached to an external network (such as the Internet) on the multihomed domain controller, and if Lightweight Directory Access Protocol (LDAP) and Kerberos traffic between the internal and external networks is partially or completely restricted because of a Proxy, ISA Server,NATServer.

In this scenario, network adapters on the multihomed domain controllers are registering both the inside and outside Internet Protocol (IP) addresses with the DNS server. DNS name resolution lookup requests return records in a "round robin" fashion, alternating the internal and external IP addresses. Replication operations require multiple

Page 262 ASP.NET MATERIAL lookup requests of SRV records. In this case, half of the DNS lookup requests return an IP address that cannot be contacted, and the replication operation fails.

To resolve this issue:

1. Disable registration on the outside network adapter on the multihomed domain controller. To do so:

a. Click Start, click Settings, and then click Network and Dial-Up Connections. b. Right-click the outside local area network (LAN) connection, and then click Properties. c. Click TCP/IP, and then click Properties. d. Click Advanced, and then click to clear the Register DNS for this connection check box. 2. Disable the round robin functionality on the DNS server. To do so:

a. Click Start, click Settings, click Administrative Tools, and then click DNS. b. Open the properties for the DNS server's name. c. Click the Advanced tab, and then click to clear the Enable round robin check box. 2. Remove the existing entries in DNS. To do so:

a.

Browse to the following location:

Under DNS\DNS Servername\Forward Lookup Zones\Domain Name

• Remove Host (A) record entries that refer to the domain controller's computer name for the outside network adapter IP addresses. • Remove Host (A) record entries for the same name as the parent folder for the network adapter IP addresses.

• Start the DNS Management Console, right-click the server name, and then click Properties. • Click the Interfaces tab, and then remove the external IP address so that DNS does not listen on it. • Open a command prompt, type ipconfig /flushdns, press ENTER, type ipconfig /registerdns, and then press ENTER. • Change the binding order of your network adapters so that the Internal adapter is the first bound adapter. To do this, follow these steps:

Page 263 ASP.NET MATERIAL • Click Start, click Settings, and then click Network and Dial-Up Connections. 1. On the Advanced menu, click Advanced. 2. Verify that the internal network adapter is listed first in the Connections box.

• SSL[Secured Socket Layer]-SOAP Header:

SA: See security association (SA).

SAD: See security association database (SAD).

Salt: An additional random quantity, specified as input to an encryption function that is used to increase the strength of the encryption.

Sanitized name: The form of a certification authority (CA) name that is used in file names and in other contexts where character sets are restricted. The process of sanitizing the CA name is necessary to remove characters that are illegal for file names, registry key names, or distinguished name (DN) values, or that are illegal for technology-specific reasons.

SASL: The Simple Authentication and Security Layer, as specified in [RFC2222]. This is an authentication mechanism used by the Lightweight Directory Access Protocol (LDAP).

Schedule: The frequency at which data replicates.

Schema: The set of attributes and object classes that govern the creation and update of objects.

Schema container: The root object of the schema NC.

Schema naming context (schema NC): A specific type of naming context (NC) or an instance of that type. A forest has a single schema NC, which is replicated to each domain controller (DC) in the forest. No other NC replicas can contain these objects. Each attribute and class in the forest's schema is represented as a corresponding object in the forest's schema NC.

Schema object: An object that defines an attribute or an object class. Schema objects are contained in the schema naming context (NC).

Page 264 ASP.NET MATERIAL Scope of management (SOM): An Active Directory site, domain, or organizational unit container. These containers contain user and computer accounts that can be managed through Group Policy. These SOMs are themselves associated with Group Policy objects (GPOs), and the accounts within them are considered by the Group Policy Protocol [MS- GPOL] to inherit that association.

Scoped Group Policy object (GPO) distinguished name (DN): A Group Policy object (GPO) distinguished name (DN) where the set of "CN=" elements is prepended with "CN=User" for the user policy mode of Policy Application and with "CN=Machine" for computer policy mode.

Scoped Group Policy object (GPO) path: A Group Policy object (GPO) path appended with "\User" for the user policy mode of policy application, and "\Machine" for the computer policy mode.

Screen coordinates: Coordinates relative to the top-left corner of the screen, which has the coordinates (0,0).

SCSI: See small computer system interface (SCSI).

SCSI logical unit number (LUN): logical unit number (LUN).

SCSI port number: A number that uniquely identifies a port on a small computer system interface (SCSI) disk controller. Each SCSI disk controller may support multiple SCSI bus attachments or ports for connecting SCSI devices to a computer.

SCSI protocol: An architecture for SCSI, consisting of a group of standards created and maintained by the Technical Committee (T10) of the InterNational Committee on Information Technology Standards (INCITS).

SD: See security descriptor.

Secret key: A symmetric encryption key shared by two entities, such as between a user and the domain controller (DC), with a long lifetime. A password is a common example of a secret key. When used in a context that implies Kerberos only, a principal's secret key.

Secret object: An element of the Local Security Authority (LSA) Policy Database, which contains a value that is secret in that access to it is strictly controlled through cryptographic protections and restrictive access control mechanisms.

Sector: The smallest addressable unit of a disk.

Page 265 ASP.NET MATERIAL Secure channel: An authenticated remote procedure call (RPC) connection between two machines in a domain with an established security context used for signing and encrypting RPC packets.

Secure desktop: Only trusted processes running as SYSTEM are allowed to run on the secure desktop.

Secure/Multipurpose Internet Mail Extensions (S/MIME): A standard for encrypted and digitally signed electronic mail that allows users to send encrypted messages and authenticate received messages.

Secure Sockets Layer (SSL): A security protocol that supports confidentiality and integrity of messages in client and server applications communicating over open networks. SSL uses two keys to encrypt data—a public key known to everyone and a private or secret key known only to the recipient of the message. SSL supports server and, optionally, client authentication using X.509 certificates (for more information, see [X509]). The SSL protocol is precursor to Transport Layer Security (TLS). The TLS version 1.0 specification is based on SSL version 3.0.

Security account manager (SAM) built-in database: Microsoft-specific terminology for the part of the user account database that contains account information (such as account names and passwords) for accounts and groups that are pre-created at the database installation.

Security association (SA): A simplex "connection" that provides security services to the traffic carried by it. See [RFC4301] for more information.

Security association database (SAD): A database that contains parameters that are associated with each established (keyed) security association.

Security context: (1) An abstract data structure that contains authorization information for a particular security principal in the form of a collection of security identifiers (SIDs). One SID identifies the principal specifically, whereas others may represent other capabilities. A server uses the authorization information in a security context to check access to requested resources.

(2) An association of mutually established cryptographic keys with a key identifier.

Security descriptor: A data structure containing the security information associated with a securable object. A security descriptor identifies an object's owner by its security identifier (SID).

Page 266 ASP.NET MATERIAL If access control is configured for the object, its security descriptor contains a discretionary access control list (DACL) with SIDs for the security principals who are allowed or denied access. Applications use this structure to set and query an object's security status. The security descriptor is used to guard access to an object as well as to control which type of auditing takes place when the object is accessed.

Security identifier (SID): An identifier for security principals in Windows that is used to identify an account or a group. Conceptually, the SID is composed of an account authority portion (typically a domain) and a smaller integer representing an identity relative to the account authority, termed the relative identifier (RID). The SID format is specified in [MS-DTYP] section 2.4.2; a string representation of SIDs is specified in [MS-DTYP] section 2.4.2 and [MS-WSO] section 3.1.2.1.3.

Security policy: In the form of a collection of security policy settings, the policy itself is an expression of administrative intent regarding how computers and resources on a network should be secured.

Security policy database (SPD): A database that specifies the policies that determine the disposition of all IP traffic inbound or outbound from a host or security gateway.

Security policy settings: Contained in security policies, the policy settings are the actual expression of how various security-related parameters on the computer are to be configured.

Security principal: (1) A unique entity identifiable through cryptographic means by at least one key. A security principal often corresponds to a human user but can also be a service offering a resource to other security principals. Sometimes referred to simply as a "principal".

(2) An identity that can be used to regulate access to resources, as specified in [MS- WSO]. A security principal can be a user, a computer, or a group that represents a set of users.

Security principal name (SPN): The name that identifies a security principal (for example, machinename$@domainname for a machine joined to a domain or username@domainname for a user). Domainname is resolved using the Domain Name System (DNS).

Security principal object: An object that corresponds to a security principal. A security principal object contains an identifier, used by the system and applications to name the principal, and a secret that is shared only by the principal. In Active Directory, a security principal object has the objectSid attribute. In Active Directory, the user, computer, and

Page 267 ASP.NET MATERIAL group object classes are examples of security principal object classes (though not every group object is a security principal object).

Security protocol: A protocol that performs authentication and possibly additional security services on a network.

Security provider: A pluggable security module that is specified by the protocol layer above remote procedure call (RPC), and will cause RPC to use this module to secure messages in a communication session with the server. Sometimes referred to as an authentication service. For more information, see [C706] and [MS-RPCE].

Security support provider (SSP): A dynamic-link library (DLL) that implements the Security Support Provider Interface (SSPI) by making one or more security packages available to applications. Each security package provides mappings between an application's SSPI function calls and an actual security model's functions. Security packages support security protocols such as Kerberos authentication and NTLM.

Security Support Provider Interface (SSPI): A Windows-specific API implementation that provides the means for connected applications to call one of several security providers to establish authenticated connections and to exchange data securely over those connections. This is the Windows equivalent of Generic Security Services (GSS)-API, and the two families of APIs are on-the-wire compatible.

Security token: An opaque message or data packet produced by a Generic Security Services (GSS)-style authentication package and carried by the application protocol. The application has no visibility into the contents of the token.

Seed file or seed data: A file or files on the client that are used to supply data for reconstructing the source file. Remote differential compression (RDC) may use an arbitrary number of seed files in the process of copying a single source file. Sometimes called just "seed". Selecting seed files is implementation-specific, but can be guided by using similarity traits.

Selective single master: A replication mode in which changes from only a single machine propagate to other machines.

Self-signed certificate: A certificate that is signed by its creator and verified using the public key contained in it. Such certificates are also termed root certificates.

Semisynchronous operation: An operation that is executed on the server side while the client is regularly checking to see if there is no response available from the server.

Page 268 ASP.NET MATERIAL Sequence ID: A monotonically increasing 8-bit identifier for packets. This is typically represented as a field named bSeq in packet structures.

Serial storage architecture (SSA) bus: Serial storage architecture (SSA) is a standard for high-speed access to high-capacity disk storage. An SSA bus is implemented to the SSA standard.

Serialize: The process of taking an in-memory data structure, flat or otherwise, and turning it into a flat stream of bytes. See also, marshal.

Server: (1) A computer on which the remote procedure call (RPC) server is executing.

(2) A replicating machine that sends replicated files to a partner (client). The term "server" refers to the machine acting in response to requests from partners that want to receive replicated files.

(3) A DirectPlay System application that is hosting a DirectPlay game session. In the context of DirectPlay 8, the term is reserved for hosts using client/server mode.

Server-activated object (SAO): A server object that is created on demand in response to a client request. See also marshaled server object.

Server authentication: A mode of authentication in which only the server in the transaction proves its identity.

Server challenge: A 64-bit nonce generated on the server side.

Server Group Policy object (GPO) distinguished name (DN): A Group Policy object (GPO) distinguished name (DN) that uses a specific server in the Lightweight Directory Access Protocol (LDAP) path syntax, as specified in [RFC2251], where the server name is a domain controller (DC) that is located as specified in [MS-NRPC] section 3.5.5.2.2.

Server Group Policy object (GPO) path: A Group Policy object (GPO) path in which the Distributed File System (DFS) path contains a server name in the Distributed File System (DFS) path syntax and where the server name is a domain controller (DC).

Server locator: Enables exporting of entries to the remote procedure call (RPC) name service.

Server Message Block (SMB): A protocol that is used to request file and print services from server systems over a network. The SMB protocol extends the CIFS protocol with additional security, file, and disk management support. For more information, see [CIFS] and [MS-SMB].

Page 269 ASP.NET MATERIAL Server object: A class of object in the config NC. A server object can have an nTDSDSA object as a child.

Server role: The state of a domain controller (DC), which can be one of two values— primary DC or backup DC.

Server-scoped Group Policy object (GPO) distinguished name (DN): A scoped Group Policy object (GPO) distinguished name (DN) with a server name included in the path, as is the case for a server GPO DN.

Server-scoped Group Policy object (GPO) path: A Group Policy object (GPO) path with a server name included in the path, as is the case for a server GPO path.

Service: A process or agent that is available on the network, offering resources or services for clients. Examples of services include file servers, Web servers, and so on.

Service account: A stored set of attributes that represent a principal that provides a security context for services.

Service for User (S4U): Microsoft-specific extensions to the Kerberos protocol that allow a service to obtain a Kerberos service ticket for a user that has not authenticated to the key distribution center (KDC). S4U includes S4U2proxy and S4U2self.

Service for User to Proxy (S4U2proxy): An extension that allows a service to obtain a service ticket on behalf of a user to a different service.

Service for User to Self (S4U2self): An extension that allows a service to obtain a Kerberos service ticket to itself. The service ticket contains the user's groups and can therefore be used in authorization decisions.

Service principal: An entity that represents a service at the key distribution center (KDC). The service principal has a name and an associated key. A subclass of principal, a service principal generally does not correspond to a human user of the system, but rather to an automated service providing a resource, such as a file server.

Service principal name (SPN): The name by which a client uniquely identifies an instance of a service for mutual authentication. See [SPNNAMES] for more information about SPN format and composing a unique SPN. Also see [RFC1964] section 2.1.1.

Service provider: A module that abstracts details of underlying transports for generic DirectPlay message transmission. Each DirectPlay message is transmitted by a DirectPlay service provider. The service providers that shipped with DirectPlay 4 are modem, serial, IPX, and TCP/IP.

Page 270 ASP.NET MATERIAL Service (SRV) resource record: A domain name system (DNS) resource record used to identify computers that host specific services, as specified in [RFC2782]. SRV resource records are used to locate domain controllers (DCs) for Active Directory.

Service set identifier (SSID): A sequence of characters that names a wireless local area network (WLAN).

Service ticket: A ticket for any service other than the ticket-granting service (TGS). A service ticket serves only to classify a ticket as not a ticket-granting ticket (TGT) or cross-realm TGT, as specified in [RFC4120].

Session: (1) In Kerberos, an active communication channel established through Kerberos that also has an associated cryptographic key, message counters, and other state.

(2) In Server Message Block (SMB), a persistent-state association between an SMB client and SMB server. A session is tied to the lifetime of the underlying NetBIOS or TCP connection.

(3) In the Challenge-Handshake Authentication Protocol (CHAP), a session is a lasting connection between a peer and an authenticator.

(4) In the Workstation service, an authenticated connection between two computers.

(5) An active communication channel established through NTLM, that also has an associated cryptographic key, message counters, and other state.

(6) In OleTx, a transport-level connection between a Transaction Manager and another Distributed Transaction participant over which multiplexed logical connections and messages flow. A session remains active so long as there are logical connections using it.

Session key: A relatively short-lived symmetric key (a cryptographic key negotiated by the client and the server based on a shared secret). A session key's lifespan is bounded by the session to which it is associated. A session key should be strong enough to withstand cryptanalysis for the lifespan of the session.

Session layer: The fifth layer in the Open Systems Interconnect (OSI) architectural model as defined by the International Organization for Standardization (ISO). The session layer is used for establishing a communication session, implementing security, and performing authentication. The session layer responds to service requests from the presentation layer and issues service requests to the transport layer.

Page 271 ASP.NET MATERIAL Session Multiplex Protocol (SMUX): An entity on a network that implements the Secure Socket Tunneling Protocol (SSTP) and that listens for Secure Socket Tunneling Protocol (SSTP) connections over TCP port 443.

Session security: The provision of message integrity and/or confidentiality to a session.

SHA-1 hash: A hashing algorithm as specified in [FIPS180-2] that was developed by the National Institute of Standards and Technology (NIST) and the National Security Agency (NSA).

Shadow copy: A duplicate of data held on a volume at a well-defined instant in time.

Share: A resource offered by a Common Internet File System (CIFS) server for access by CIFS clients over the network. A share typically represents a directory tree and its included files (referred to commonly as a "disk share" or "file share") or a printer (a "print share"). If the information about the share is saved in persistent store (for example, Windows registry) and reloaded when a file server is restarted, then the share is referred to as a "sticky share". Some share names are reserved for specific functions and are referred to as special shares:

• IPC$, reserved for interprocess communication. • ADMIN$, reserved for remote administration. • A$, B$, C$ (and other local disk names followed by a dollar sign), assigned to local disk devices. share connect: The act of establishing authentication and shared state between a Common Internet File System (CIFS) server and client that allows a CIFS client to access a share offered by the CIFS server.

Shell: Part of the Windows user interface (UI) that organizes and controls user access to a wide variety of objects necessary for running applications and managing the operating system. The most numerous are the folders and files that reside on computer storage media. There are also a number of virtual objects such as network printers and other computers. The shell organizes these objects into a hierarchical namespace and provides an API to access them.

Shell link: A data object that contains information used to access another object in the shell's namespace—that is, any object visible through Windows Explorer. The types of objects that can be accessed through shell links include files, folders, disk drives, and printers. A shell link allows an application to access an object from anywhere in the namespace. The application does not need to know the current name and location of the object.

Page 272 ASP.NET MATERIAL Shell shortcut: A shell link that has a shortcut icon; however, the terms shell link and shell shortcut are often used interchangeably.

SID: See security identifier.

Signal: In OleTx, the act of communicating an event between facets inside a transaction manager.

Signature: A structure that contains a hash and block chunk size. The hash field is 16 bytes, and the chunk size field is a 2-byte unsigned integer.

Signature file: A file containing the signatures of another (source) file. There is a simple header that identifies the type of the file as a signature file, the size of the header itself, and the remote differential compression (RDC) library version number. Following the header are the signatures from the source file in the order they are generated from the chunks.

Signing certificates: The certificate that represents the identity of an entity (for example, a certificate authority (CA), a Web server or an S/MIME mail author) and is used to verify signatures made by the private key of that entity. For more information, see [RFC3280].

Similarity data: Information about a file that can be used to determine an appropriate seed file to select to reduce the amount of data transferred. Similarity data can be computed in any implementation-specific way.

Similarity traits: Similarity data consists of one or more traits. Each trait summarizes an independent feature of a file. The features are computed by taking min-wise independent hash functions of a file's signatures. Similarity traits are used in selecting seed files.

Simple and Protected GSS-API Negotiation Mechanism (SPNEGO): An authentication mechanism that allows Generic Security Services (GSS) peers to determine whether their credentials support a common set of GSS-API security mechanisms, to negotiate different options within a given security mechanism or different options from several security mechanisms, to select a service, and to establish a security context among themselves using that service. SPNEGO is specified in [RFC4178].

Simple Mail Transfer Protocol (SMTP): A TCP/IP protocol used in sending and receiving e-mail.

Simple volume: A volume whose data exists on a single partition.

Page 273 ASP.NET MATERIAL Single-instance storage (SIS): An NTFS feature that implements links with the semantics of copies for files stored on an NTFS volume. SIS uses copy-on-close to implement the copy semantics of its links.

Single-phase commit: An optimization of the Two-Phase Commit Protocol in which a transaction manager delegates the right to decide the outcome of a transaction to its only subordinate participant. This optimization can result in an In Doubt outcome. site: An Active Directory term that defines a set of one or more TCP/IP subnets, where the subnets have high connectivity as measured in terms of latency (low) and bandwidth (high). By defining sites (represented by site objects) an administrator can easily configure Active Directory access and replication topology to take advantage of the physical network. When users log on, Active Directory clients find domain controllers (DCs) that are in the same site as the user or are near the same site if there is no DC in the site. For more information, see [MS-ADTS].

Site coverage: The set of sites for which a domain controller (DC) is responsible, as configured by the administrator.

Site distinguished name (DN): The distinguished name for an object in Active Directory that represents a site.

Site object: An object of class site, representing a site.

Site of domain controller (DC): The site object that is an ancestor of the DC's nTDSDSA object.

Site settings object: For a given site with site object s, its site settings object o is the child of s such that o is of class nTDSSiteSettings and the RDN of o is CN=NTDS site settings.

SKU: See Stock Keeping Unit (SKU).

Slow sync: The nominator for a synchronization subprotocol that is used to perform a consistency check between the databases of two partners.

Small computer system interface (SCSI): A set of standards for physically connecting and transferring data between computers and peripheral devices.

Small computer system interface (SCSI) bus: A standard for connecting peripheral devices to a computer. A SCSI bus is an implementation of this standard.

Page 274 ASP.NET MATERIAL Smart card: A portable device that is shaped like a business card and is embedded with a memory chip and either a microprocessor or some non-programmable logic. Smart cards are often used as authentication tokens and for secure key storage. Smart cards used for secure key storage have the ability to perform cryptographic operations with the stored key without allowing the key itself to be read or otherwise extracted from the card.

SMB connection: A transport connection between a Server Message Block (SMB) client and an SMB server. The SMB connection is assumed to provide reliable in-order message delivery semantics. An SMB connection can be established over any available SMB transport that is supported by both the SMB client and the SMB server, as specified in [MS-CIFS].

SMB dialect: There are several different versions and subversions of the Server Message Block (SMB) protocol. A particular version of the SMB protocol is referred to as an SMB dialect. Different SMB dialects can include both new SMB messages as well as changes to the fields and semantics of existing SMB messages used in other SMB dialects. When an SMB client connects to an SMB server, the client and server negotiate the SMB dialect to be used.

SMB session: An authenticated user connection established between an SMB client and an SMB server over an SMB connection. There can be multiple active SMB sessions over a single SMB connection. The Uid field in the SMB packet header distinguishes the various sessions.

SMTP: See Simple Mail Transfer Protocol (SMTP).

Snapshot: The point in time at which a shadow copy of a volume is made.

SOAP: A lightweight protocol for exchanging structured information in a decentralized, distributed environment. SOAP uses XML technologies to define an extensible messaging framework, which provides a message construct that can be exchanged over a variety of underlying protocols. The framework has been designed to be independent of any particular programming model and other implementation-specific semantics. SOAP 1.2 supersedes SOAP 1.1.

SOAP 1.1: Version 1.1 of the SOAP (Simple Object Access Protocol) standard. For the complete definition of SOAP 1.1, see [SOAP1.1].

SOAP 1.2: Version 1.2 of the SOAP standard. Some examples of changes introduced in SOAP 1.2 include an updated envelope structure, as well as updates to the structure and sematics for SOAP faults. The binding framework was also updated to allow binding to non-HTTP transports. Starting with version 1.2, SOAP is no longer an acronym. See also SOAP.

Page 275 ASP.NET MATERIAL SOAP action: The HTTP request header field used to indicate the intent of the SOAP request, using a URI value. See [SOAP1.1] section 6.1.1 for more information.

SOAP body: A container for the payload data being delivered by a SOAP message to its recipient. See [SOAP1.2-1/2007] section 5.3 for more information.

SOAP envelope: A container for SOAP message information and the root element of a SOAP document. See [SOAP1.2-1/2007] section 5.1 for more information.

SOAP fault: A container for error and status information within a SOAP message. See [SOAP1.2-1/2007] section 5.4 for more information.

SOAP fault code: The algorithmic mechanism for identifying a SOAP fault. See [SOAP1.2-1/2007] section 5.6 for more information.

SOAP fault detail: A string containing a human-readable explanation of a SOAP fault, which is not intended for algorithmic processing. See [SOAP1.2-1/2007] section 5.4.5 for more information.

SOAP header: A mechanism for implementing extensions to a SOAP message in a decentralized manner without prior agreement between the communicating parties. See [SOAP1.2-1/2007] section 5.2 for more information.

SOAP header block: The XML block containing the SOAP header entries within a SOAP header. See [SOAP1.2-1/2007] section 5.2.1 for more information.

SOAP message: An XML document consisting of a mandatory SOAP envelope, an optional SOAP header, and a mandatory SOAP body. See [SOAP1.2-1/2007] section 5 for more information.

SOAP mustUnderstand attribute: A global, Boolean attribute that is used to indicate whether a header entry is mandatory or optional for the recipient to process. See [SOAP1.2-1/2007] section 5.2.3 for more information.

Software installation package: A file that describes other files and metadata necessary to describe an application's executable files and state and to install that application. Also referred to as a "package".

Software installation package modification: A file that allows an administrator to specify configuration for an application that is installed on the client through a software installation package.

Page 276 ASP.NET MATERIAL Software maintenance utility: An application that allows users to perform software management activities such as installation, uninstallation, or inventory of applications available through the software installation extension.

Software package container distinguished name (DN): A DN of the form "CN=Packages," where is a class store container DN.

Software package distinguished name (DN): A DN of the form "CN=,CN=Packages,", where is a class store container DN and is a curly braced GUID string.

Software scripts path: A file system path to a directory with a path of the form "\Applications", where is a scoped GPO path.

Source file, source data: A file on a server that is to be copied by remote differential compression (RDC). Sometimes referred to as "source".

Sparse file: A file that has regions of data containing all zeros and in which some of the zero regions do not have disk space allocated for them.

SPD: See security policy database.

SPN: See service principal name.

Spool file: A representation of application content data than can be processed by a print driver. Common examples are enhanced metafile format and XML paper specification. For more information, see [MSDN-META] and [MSDN-XMLP].

SSL: See Secure Sockets Layer (SSL).

SSL/TLS handshake: The process of negotiating and establishing a connection protected by SSL or TLS. For more information, see [SSL3] and [RFC2246].

Staging file: The backup of the changed file or folder. It encapsulates the data and attributes associated with a replicated file or folder. By creating the staging file, File Replication Service (FRS) ensures that file data can be supplied to partners regardless of any activity that might prevent access to the original file. The staging files can be compressed to save disk space and network bandwidth during replication.

Stamp: Information that describes an originating update by a domain controller (DC). The stamp is not the new data value; the stamp is information about the update that created the new data value. A stamp is often called metadata, because it is additional information that "talks about" the conventional data values. A stamp contains the

Page 277 ASP.NET MATERIAL following pieces of information: the unique identifier of the DC that made the originating update; a sequence number characterizing the order of this change relative to other changes made at the originating DC; a version number identifying the number of times the data value has been modified; and the time when the change occurred.

Standalone CA: A certificate authority (CA) that is not a member of a domain. For more information, see [MSFT-PKI].

Standalone machine: A machine that is not a domain member or a domain controller (DC).

Standard user: A user that does not have administrative rights defined in its token and is a member of the users group. Users are prevented from making accidental or intentional system-wide changes but can perform normal daily computer tasks.

State machine: A model of computing behavior composed of a specified number of states, transitions between those states, and actions to be taken. A state stores information about past transactions as it reflects input changes from the startup of the system to the present moment. A transition (such as connecting a network share) indicates a state change and is described by a condition that would need to be fulfilled to enable the transition. An action is a description of an activity that is to be performed at a given moment.

There are several action types:

• Entry action: Performed when entering the state. • Exit action: Performed when exiting the state. • Input action: Performed based on the present state and input conditions. • Transition action: Performed when executing a certain state transition.

Statement of health (SoH): A collection of data generated by a system health entity, as specified in [MS-SOH], which defines the health state of a machine. The data is interpreted by a Health Policy Server, which determines whether the machine is healthy or unhealthy according to the policies defined by an administrator.

Statement of health (SoH) client: A synonym for system health entity.

Statement of health response (SoHR): A collection of data that represents the evaluation of the statement of health (SoH) according to network policies, as specified in [MS-SOH].

Station (STA): Any device that contains an IEEE 802.11 conformant medium access control and physical layer (PHY) interface to the wireless medium (WM).

Page 278 ASP.NET MATERIAL Station management entity (SME): In general, a station management entity (SME) is regarded as responsible for functions such as the gathering of layer-dependent status from the various layer management entities and setting the value of layer-specific parameters. An SME would typically perform such functions on behalf of general system management entities and would implement standard management protocols.

Stock Keeping Unit (SKU): A unique code that refers to a particular manufactured object or source of revenue. An SKU can refer to a retail product (software in a box that is sold through a channel), a subscription program (such as MSDN), or an online service (such as MSN).

Stored procedure: A function/method that predefines a set of T-SQL commands that resides in a database server and is available to be called by client applications.

StoreMaster: The single agent responsible for performing certain updates to file-link information stored in VolumeTable and FileTable within an Active Directory Table (ADT). For more information on VolumeTable and FileTable, see [MSDLT].

Stream: A sequence of bytes written to a file on the NTFS file system. Every file stored on a volume that uses the NTFS file system contains at least one stream, which is normally used to store the primary contents of the file. Additional streams within the file may be used to store file attributes, application parameters, or other information specific to that file. Every file has a default data stream, which is unnamed by default. That data stream, and any other data stream associated with a file, may optionally be named.

Strict NDR/NDR64 data consistency check: A set of related rules for data validation during processing of an octet stream.

Structural class: See structural object class.

Structural object class: An object class that is not an 88 object class and can be instantiated to create a new object.

Sub-authentication: Optional and additional authentication functionality, usually provided by extending an authentication algorithm.

Sub-authentication package: An optional component that provides additional authentication functionality. If a sub-authentication package is installed, the authentication package calls the sub-authentication package before returning its authentication result. The request to verify by a sub-authentication package is indicated by the ParameterControl field of the LogonInformation parameter (see [MS-APDS] section 3.1.5.2.1, Verifying Responses with Sub-Authentication Packages).

Page 279 ASP.NET MATERIAL Subkey: A child node in the logical tree of the hierarchical data store.

Subnet site: The association of a site with a particular client, based on the client's IP address.

Subordinate transaction manager: A role taken by a transaction manager that is responsible for voting on the outcome of an atomic transaction. A subordinate transaction manager coordinates the voting and notification of its subordinate participants on behalf of its superior transaction manager. When communicating with those subordinate participants, the subordinate transaction manager acts in the role of superior transaction manager. The root transaction manager is never a subordinate transaction manager. A subordinate transaction manager has exactly one superior transaction manager.

SubRequest: A request within a SYNC_VOLUME or SEARCH request.

Superclasses and subclasses: Types of common Information Model (CIM) classes. A subclass is derived from a superclass. The subclasses inherit all features of its superclass but can add new features or redefine existing ones. A superclass is the CIM class from which a CIM class inherits.

Superior transaction manager: A role taken by a transaction manager that is responsible for gathering outcome votes and providing the final transaction outcome. A root transaction manager can act as a superior transaction manager to a number of subordinate transaction managers. A transaction manager can act as both a subordinate transaction manager and a superior transaction manager on the same transaction.

Symbolic link: A symbolic link is a reparse point that points to another file system object . The object being pointed to is called the target. Symbolic links are transparent to users; the links appear as normal files or directories, and can be acted upon by the user or application in exactly the same manner. Symbolic links can be created using the FSCTL_SET_REPARSE_POINT request as specified in [MS-FSCC] section 2.3.53. They can be deleted using the FSCTL_DELETE_REPARSE_POINT request as specified in [MS-FSCC] section 2.3.5. Implementing symbolic links is optional for a file system.

Symmetric algorithm: A cryptographic algorithm that uses one secret key that may be shared between authorized parties. The key must be kept secret between communicating parties. The same key is used for both encryption and decryption. For an introduction to this concept and terminology, see [CRYPTO] section 1.5, [IEEE1363] section 3, and [SP800-56A] section 3.1.

Symmetric encryption: An encryption method that uses the same cryptographic key to encrypt and decrypt a given message.

Page 280 ASP.NET MATERIAL Symmetric key: A secret key used with a cryptographic symmetric algorithm. The key needs to be known to all communicating parties. For an introduction to this concept, see [CRYPTO] section 1.5.

Synchronous operation: An operation that is executed on the server side while the client is waiting for the response message.

System access control list (SACL): An access control list (ACL) that controls the generation of audit messages for attempts to access a securable object. The ability to get or set an object's SACL is controlled by a privilege typically held only by system administrators.

System command: A message that is sent to a window or notification icon via its system menu, or via a keyboard shortcut. Common system commands include minimize, maximize, move, and so on. system directory: A directory that contains system files comprising the operating system. system health entity: The entity on a machine that can generate a statement of health (SoH) for the machine and consume the corresponding statement of health response (SoHR).

System menu: See window menu. system partition: A partition that contains the boot loader needed to invoke the operating system on the boot partition. A system partition must also be an active partition. It can be, but is not required to be, the same partition as the boot partition. system volume (SYSVOL): A shared directory that stores the server copy of the domain's public files that must be shared for common access and replication throughout a domain.

Page 281 ASP.NET MATERIAL

MASTER PAGES

Need of a Master Page, Basics of a Master Page, Content Page:

Introduction:

One attribute of a well-designed website is a consistent site-wide page layout. Take the www.asp.net website, for example. At the time of this writing, every page has the same content at the top and bottom of the page. As Figure 1 shows, the very top of each page displays a gray bar with a list of Microsoft Communities. Beneath that is the site logo, the list of languages into which the site has been translated, and the core sections: Home, Get Started, Learn, Downloads, and so forth. Likewise, the bottom of the page includes information about advertising on www.asp.net, a copyright statement, and a link to the privacy statement.

Page 282 ASP.NET MATERIAL

Figure 01:

Another attribute of a well-designed site is the ease with which the site's appearance can be changed. Figure 1 shows the www.asp.net homepage as of March 2008, but between now and this tutorial's publication, the look and feel may have changed. Perhaps the menu items along the top will expand to include a new section for the MVC framework. Or maybe a radically new design with different colors, fonts, and layout will be unveiled. Applying such changes to the entire site should be a fast and simple process that does not require modifying the thousands of web pages that make up the site.

Creating a site-wide page template in ASP.NET is possible through the use of master pages. In a nutshell, a master page is a special type of ASP.NET page that defines the markup that is common among all content pages as well as regions that are customizable on a content page-by-content page basis. (A content page is an ASP.NET page that is bound to the master page.) Whenever a master page's layout or formatting is changed, all of its content pages' output is likewise immediately updated, which makes applying site- wide appearance changes as easy as updating and deploying a single file (namely, the master page).

This is the first tutorial in a series of tutorials that explore using master pages. Over the course of this tutorial series we:

• Examine creating master pages and their associated content pages, • Discuss a variety of tips, tricks, and traps, • Identify common master page pitfalls and explore workarounds, • See how to access the master page from a content page and vice-a-versa, • Learn how to specify a content page's master page at runtime, and • Other advanced master page topics.

Page 283 ASP.NET MATERIAL These tutorials are geared to be concise and provide step-by-step instructions with plenty of screen shots to walk you through the process visually. Each tutorial is available in C# and Visual Basic versions and includes a download of the complete code used.

This inaugural tutorial starts with a look at master page basics. We discuss how master pages work, look at creating a master page and associated content pages using Visual Web Developer, and see how changes to a master page are immediately reflected in its content pages. Let's get started!

Understanding How Master Pages Work:

Building a website with a consistent site-wide page layout requires that each web page emit common formatting markup in addition to its custom content. For example, while each tutorial or forum post on www.asp.net have their own unique content, each of these pages also render a series of common

elements that display the top-level section links: Home, Get Started, Learn, and so on.

There are a variety of techniques for creating web pages with a consistent look and feel. A naive approach is to simply copy and paste the common layout markup into all web pages, but this approach has a number of downsides. For starters, every time a new page is created, you must remember to copy and paste the shared content into the page. Such copying and pasting operations are ripe for error as you may accidentally copy only a subset of the shared markup into a new page. And to top it off, this approach makes replacing the existing site-wide appearance with a new one a real pain because every single page in the site must be edited in order to use the new look and feel.

Prior to ASP.NET version 2.0, page developers often placed common markup in User Controls and then added these User Controls to each and every page. This approach required that the page developer remember to manually add the User Controls to every new page, but allowed for easier site-wide modifications because when updating the common markup only the User Controls needed to be modified. Unfortunately, Visual Studio .NET 2002 and 2003 - the versions of Visual Studio used to create ASP.NET 1.x applications - rendered User Controls in the Design view as gray boxes. Consequently, page developers using this approach did not enjoy a WYSIWYG design-time environment.

The shortcomings of using User Controls were addressed in ASP.NET version 2.0 and Visual Studio 2005 with the introduction of master pages. A master page is a special type of ASP.NET page that defines both the site-wide markup and the regions where associated content pages define their custom markup. As we will see in Step 1, these regions are defined by ContentPlaceHolder controls. The ContentPlaceHolder control simply denotes a position in the master page's control hierarchy where custom content can be injected by a content page.

Page 284 ASP.NET MATERIAL Note: The core concepts and functionality of master pages has not changed since ASP.NET version 2.0. However, Visual Studio 2008 offers design-time support for nested master pages, a feature that was lacking in Visual Studio 2005. We will look at using nested master pages in a future tutorial.

Figure 2 shows what the master page for www.asp.net might look like. Note that the master page defines the common site-wide layout - the markup at the top, bottom, and right of every page - as well as a ContentPlaceHolder in the middle-left, where the unique content for each individual web page is located.

Figure 02: A Master Page Defines the Site-Wide Layout and the Regions Editable on a Content Page-by-Content Page Basis

Once a master page has been defined it can be bound to new ASP.NET pages through the tick of a checkbox. These ASP.NET pages - called content pages - include a Content control for each of the master page's ContentPlaceHolder controls. When the content page is visited through a browser the ASP.NET engine creates the master page's control

Page 285 ASP.NET MATERIAL hierarchy and injects the content page's control hierarchy into the appropriate places. This combined control hierarchy is rendered and the resulting HTML is returned to the end user's browser. Consequently, the content page emits both the common markup defined in its master page outside of the ContentPlaceHolder controls and the page-specific markup defined within its own Content controls. Figure 3 illustrates this concept.

Page 286 ASP.NET MATERIAL

Figure 03: The Requested Page's Markup is Fused into the Master Page.

Now that we have discussed how master pages work, let's take a look at creating a master page and associated content pages using Visual Web Developer.

Page 287 ASP.NET MATERIAL Note: In order to reach the widest possible audience, the ASP.NET website we build throughout this tutorial series will be created using ASP.NET 3.5 with Microsoft's free version of Visual Studio 2008, Visual Web Developer 2008. If you have not yet upgraded to ASP.NET 3.5, don't worry - the concepts discussed in these tutorials work equally well with ASP.NET 2.0 and Visual Studio 2005. However, some demo applications may use features new to the .NET Framework version 3.5; when 3.5-specific features are used, I include a note that discusses how to implement similar functionality in version 2.0. Do keep in mind that the demo applications available for download from each tutorial target the .NET Framework version 3.5, which results in a Web.config file that includes 3.5- specific configuration elements. Long story short, if you have yet to install .NET 3.5 on your computer then the downloadable web application will not work without first removing the 3.5-specific markup from Web.config.

Step 1: Creating a Master Page:

Before we can explore creating and using master and content pages, we first need an ASP.NET website. Start by creating a new file system-based ASP.NET website. To accomplish this, launch Visual Web Developer and then go to the File menu and choose New Web Site, displaying the New Web Site dialog box (see Figure 4). Choose the ASP.NET Web Site template, set the Location drop-down list to File System, choose a folder to place the web site, and set the language to Visual Basic. This will create a new web site with a Default.aspx ASP.NET page, an App_Data folder, and a Web.config file.

Page 288 ASP.NET MATERIAL

Figure 04: Create a New File System-Based Web Site .

Next, add a master page to the site in the root directory by right-clicking on the Project name, choosing Add New Item, and selecting the Master Page template. Note that master pages end with the extension .master. Name this new master page Site.master and click Add.

Page 289 ASP.NET MATERIAL

Figure 05: Add a Master Page Named Site.master to the Website.

Adding a new master page file through Visual Web Developer creates a master page with the following declarative markup:

<%@ Master Language="VB" CodeFile="Site.master.vb" Inherits="Site" %> Untitled Page

The first line in the declarative markup is the @Master directive . The @Master directive is similar to the @Page directive that appears in ASP.NET pages. It defines the server-side language (VB) and information about the location and inheritance of the master page's code-behind class.

The DOCTYPE and the page's declarative markup appears beneath the @Master directive. The page includes static HTML along with four server-side controls:

Page 290 ASP.NET MATERIAL

• A Web Form (the

) - because all ASP.NET pages typically have a Web Form - and because the master page may include Web controls that must appear within a Web Form - be sure to add the Web Form to your master page (rather than adding a Web Form to each content page). • A ContentPlaceHolder control named ContentPlaceHolder1 - this ContentPlaceHolder control appears within the Web Form and serves as the region for the content page's user interface. • A server-side element - the element has the runat="server" attribute, making it accessible through server-side code. The element is implemented this way so that the page's title and other -related markup may be added or adjusted programmatically. For example, setting an ASP.NET page's Title property changes the element rendered by the <head> server control. • A ContentPlaceHolder control named head - this ContentPlaceHolder control appears within the <head> server control and can be used to declaratively add content to the <head> element.</p><p>This default master page declarative markup serves as a starting point for designing your own master pages. Feel free to edit the HTML or to add additional Web controls or ContentPlaceHolders to the master page. </p><p>Note: When designing a master page make sure that the master page contains a Web Form and that at least one ContentPlaceHolder control appears within this Web Form.</p><p>Creating a Simple Site Layout:</p><p>Let's expand Site.master's default declarative markup to create a site layout where all pages share: a common header; a left column with navigation, news and other site-wide content; and a footer that displays the "Powered by Microsoft ASP.NET" icon. Figure 6 shows the end result of the master page when one of its content pages is viewed through a browser. The red circled region in Figure 6 is specific to the page being visited (Default.aspx); the other content is defined in the master page and therefore consistent across all content pages.</p><p>Page 291 ASP.NET MATERIAL</p><p>Figure 06: The Master Page Defines the Markup for the Top, Left, and Bottom Portions.</p><p>To achieve the site layout shown in Figure 6, start by updating the Site.master master page so that it contains the following declarative markup:</p><p><%@ Master Language="VB" CodeFile="Site.master.vb" Inherits="Site" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page css" />

Lessons

  • TODO

News

  • TODO

Page 292 ASP.NET MATERIAL

The master page's layout is defined using a series of

HTML elements. The topContent
contains the markup that appears at the top of each page, while the mainContent, leftContent, and footerContent
s are used to display the page's content, the left column, and the "Powered by Microsoft ASP.NET" icon, respectively. In addition to adding these
elements, I also renamed the ID property of the primary ContentPlaceHolder control from ContentPlaceHolder1 to MainContent.

The formatting and layout rules for these assorted

elements is spelled out in the Cascading Stylesheet (CSS) file Styles.css, which is specified via a element in the master page's element. These various rules define the look and feel of each
element noted above. For example, the topContent
element, which displays the "Master Pages Tutorials" text and link, has its formatting rules specified in Styles.css as follows:

#topContent { text-align: right; background-color: #600; color: White; font-size: x-large; text-decoration: none; font-weight: bold; padding: 10px; height: 50px; }

If you are following along at your computer, you will need to download this tutorial's accompanying code and add the Styles.css file to your project. Similarly, you will also need to create a folder named Images and copy the "Powered by Microsoft ASP.NET" icon from the downloaded demo website to your project.

Creating a Master Page Using an Existing Design Template:

Over the years I've built a number of ASP.NET web applications for small- to medium- sized companies. Some of my clients had an existing site layout they wanted to use; others hired a competent graphics designer. A few entrusted me to design the website layout. As you can tell by Figure 6, tasking a programmer to design a website's layout is usually as wise as having your accountant perform open-heart surgery while your doctor does your taxes.

Fortunately, there are innumerous websites that offer free HTML design templates - Google returned more than six million results for the search term "free website templates." One of my favorite ones is OpenDesigns.org. Once you find a website template you like, add the CSS files and images to your website project and integrate the template's HTML into your master page.

Step 2: Creating Associated Content Pages:

With the master page created, we are ready to start creating ASP.NET pages that are bound to the master page. Such pages are referred to as content pages.

Page 293 ASP.NET MATERIAL

Let's add a new ASP.NET page to the project and bind it to the Site.master master page. Right-click on the project name in Solution Explorer and choose the Add New Item option. Select the Web Form template, enter the name About.aspx, and then check the "Select master page" checkbox as shown in Figure 7. Doing so will display the Select a Master Page dialog box (see Figure 8) from where you can choose the master page to use.

Figure 07: Add a New Content Page.

Page 294 ASP.NET MATERIAL

Figure 08: Select the Site.master Master Page.

As the following declarative markup shows, a new content page contains a @Page directive that points back to its master page and a Content control for each of the master page's ContentPlaceHolder controls.

<%@ Page Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="About.aspx.vb" Inherits="About" Title="Untitled Page" %>

When rendering a content page, the ASP.NET engine must fuse the page's Content controls with its master page's ContentPlaceHolder controls. The ASP.NET engine determines the content page's master page from the @Page directive's MasterPageFile attribute. As the above markup shows, this content page is bound to ~/Site.master.

Because the master page has two ContentPlaceHolder controls - head and MainContent - Visual Web Developer generated two Content controls. Each Content control references a particular ContentPlaceHolder via its ContentPlaceHolderID property.

Where master pages shine over previous site-wide template techniques is with their design-time support. Figure 9 shows the About.aspx content page when viewed through

Page 295 ASP.NET MATERIAL Visual Web Developer's Design view. Note that while the master page content is visible, it is grayed out and cannot be modified. The Content controls corresponding to the master page's ContentPlaceHolders are, however, editable. And just like with any other ASP.NET page, you can create the content page's interface by adding Web controls through the Source or Design views.

Figure 09: The Content Page's Design View Displays Both the Page-Specific and Master Page Contents.

Adding Markup and Web Controls to the Content Page:

Take a moment to create some content for the About.aspx page. As you can see in Figure 10, I entered an "About the Author" heading and a couple of paragraphs of text, but feel free to add Web controls, too. After creating this interface, visit the About.aspx page through a browser.

Page 296 ASP.NET MATERIAL

Figure 10: Visit the About.aspx Page Through a Browser.

It is important to understand that the requested content page and its associated master page are fused and rendered as a whole entirely on the web server. The end user's browser is then sent the resulting, fused HTML. To verify this, view the HTML received by the browser by going to the View menu and choosing Source. Note that there are no frames or any other specialized techniques for displaying two different web pages in a single window.

Binding a Master Page to an Existing ASP.NET Page:

As we saw in this step, adding a new content page to an ASP.NET web application is as easy as checking the "Select master page" checkbox and picking the master page. Unfortunately, converting an existing ASP.NET page to a master page is not as easy.

To bind a master page to an existing ASP.NET page you need to perform the following steps:

Page 297 ASP.NET MATERIAL

1. Add the MasterPageFile attribute to the ASP.NET page's @Page directive, pointing it to the appropriate master page. 2. Add Content controls for each of the ContentPlaceHolders in the master page. 3. Selectively cut and paste the ASP.NET page's existing content into the appropriate Content controls. I say "selectively" here because the ASP.NET page likely contains markup that's already expressed by the master page, such as the DOCTYPE, the element, and the Web Form.

For step-by-step instructions on this process along with screen shots, check out Scott Guthrie's Using Master Pages and Site Navigation tutorial. The "Update Default.aspx and DataSample.aspx to use the Master Page" section details these steps.

Because it is much easier to create new content pages than it is to convert existing ASP.NET pages into content pages, I recommend that whenever you create a new ASP.NET website add a master page to the site. Bind all new ASP.NET pages to this master page. Don't worry if the initial master page is very simple or plain; you can update the master page later.

Step 3: Updating the Master Page's Markup:

One of the primary benefits of master pages is that a single master page may be used to define the overall layout for numerous pages on the site. Therefore, updating the site's look and feel requires updating a single file - the master page.

To illustrate this behavior, let's update our master page to include the current date in at the top of the left column. Add a Label named DateDisplay to the leftContent

.

Lessons

  • TODO

News

  • TODO

Next, create a Page_Load event handler for the master page and add the following code:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load DateDisplay.Text = DateTime.Now.ToString("dddd, MMMM dd") End Sub

The above code sets the Label's Text property to the current date and time formatted as the day of the week, the name of the month, and the two-digit day (see Figure 11). With this change, revisit one of your content pages. As Figure 11 shows, the resulting markup is immediately updated to include the change to the master page.

Page 298 ASP.NET MATERIAL

Figure 11: The Changes to the Master Page are Reflected When Viewing the a Content Page.

Summary:

Master pages enable ASP.NET developers to design a consistent site-wide layout that is easily updateable. Creating master pages and their associated content pages is as simple as creating standard ASP.NET pages, as Visual Web Developer offers rich design-time support.

The mater page example we created in this tutorial had two ContentPlaceHolder controls, head and MainContent. We only specified markup for the MainContent ContentPlaceHolder control in our content page, however. In the next tutorial we look at using multiple Content controls in the content page. We also see how to define default markup for Content controls within the master page, as well as how to toggle between using the default markup defined in the master page and providing custom markup from the content page.

Page 299 ASP.NET MATERIAL LOCALIZATION AND GLOBALIZATION

• Introduction to mobile Programming:

The mobile controls provided by ASP .NET target, as the name suggests, mobile devices (cell phones, Palms, etc.). This article will give you an idea of how to develop mobile web applications using ASP .NET and the Microsoft Visual Studio .NET environment. It will describe some of the most important mobile specific controls but won't go deep into the subject. At the end we'll also take a look at the Pocket PC Emulator 2002 which is included in Visual Studio .NET.

The ways mobile pages are organized differ from the classic web pages that you see on your computer. One mobile page is represented by a Form and a typical file (MobileWebForm1.aspx) can contain multiple forms, therefore multiple pages. This way when you open a page with the WAP browser actually multiple pages will be loaded (represented by forms) and when you click a link to one of the other forms there will be no loading time because they are in the same page. There is a good reason for this. Some WAP browsers disconnect after they retrieve the webpage to save the battery of the mobile phone and the money if the connection is charged per minute. This way they won't have to reconnect every time a new form is loaded, if it is located in the same file.

Create a new ASP .NET Mobile Web Application project in Visual Studio .NET.

MobileWebForm1.aspx is created with a form on it:

Page 300 ASP.NET MATERIAL

Also if you look in the HTML code you can see the tags that define this form:

If you wish, you can add some content to it and view it on your mobile phone:

Hello visitor!

If you don't have one (do you live in a cave?) you can compile and see the result in the IE window. Or you could download a simulator like the popular Openwave. The result is nothing extraordinary, just some simple text.

Earlier in the article I said that an ASP .NET mobile page can contain multiple forms. In the following example we add a second form, Form2 and we link to it from Form1:

Hello visitor!

- About us

Page 301 ASP.NET MATERIAL

About us

Here goes some information about the website.

The linking is not done with the typical tag. Of course, after the code is compiled the HTML actually uses an tag but that's its job and not ours. As you can see the linking to the other form is done exactly like when using anchors.

The result in the Openwave simulator is the following:

When you click that link you get to Form2 which displays the text "About us. Here goes

Page 302 ASP.NET MATERIAL some information about the website."

Displaying a graphic on a mobile phone is as easy as displaying it in a usual web browser. You don't use an tag, but this one:

The List control:

This is a basic control that you'll be using in almost any WAP website. It provides sufficient functionality to prove itself useful. Let's see it in action.

First add a link to the Form that includes the control:

- Get product list

As you can see here, "Get product list" links to Form3, so let's create this form:

Product list

Let's add to this form a specific ASP .NET mobile control - List.

Product list

Currently we have the following products for sale:

Page 303 ASP.NET MATERIAL

If you run this application you can see that the result is just a simple list of the products we entered, if you look at the source code in Internet Explorer you can see that it's created with the help of a table. So what's so special about this control? Well depending on which device the page containing the control is opened, it will be displayed differently. For example on the web browser the list is created using a HTML table, while on a WML browser it will be created much simpler, by separating the items with
tags.

Another feature of Lists is that you can bind them to different data sources, like databases or XML files.

The AdRotator control:

Banner advertisements on WAP page appeared a short while after WAP was born. The AdRotator mobile control acts in the same way as the original AdRotator control does. The mobile control has a very useful feature - you can choose to display one type of image for typical computer browsers and other type of image for WML browsers.

The Calendar control:

Let's take a look at another mobile control - the Calendar. Adding a functional calendar to a WAP page was a very difficult task in the past, but with the Calendar control it's just a matter of dragging and dropping.

So add a new link in Form1 that points to a new form, Form4:

- Calendar

Page 304 ASP.NET MATERIAL

Also add Form4 now:

Calendar

If you drag and drop the Calendar control from the Toolbox inside Form4, the following tag will be added:

The calendar control offers great functionality, of course a bit limited for WAP devices. The most important event of this control is called Calendar_SelectionChanged() and, as the name implies, occurs when the visitor selects a date on the calendar.

You could build an entire mobile website based on this control. For example the user picks a day on the calendar and he can see the TV guide for that day, or the movies that run at some cinema.

The SelectionList control:

This control acts exactly as a typical DropDown control and also looks like one. Only that it can be made to look like a ListBox also, or like a radio control, or checkbox, or a ListBox that allows multiple items to be selected. This control can change its functionality by changing one of its properties called SelectType.

Page 305 ASP.NET MATERIAL

Also the tags generated by this control are different depending on the devices on which the page is loaded. On an usual computer browser it would display the typical HTML controls. Whereas on a WML browser it would be rendered using WML compatible tags. From a cell phone browser the visitor will have to select the item he wants by using the numeric key pad or by navigating to the wished item.

Pocket PC 2002 Emulator:

This emulator comes with the Microsoft Visual Studio .NET package and it's a really nice software to play with if you don't own a Pocket PC. After you're tired of playing with it you can use it for more productive purposes, developing and testing applications and web applications with it. You can fire up this emulator from the Tools menu, Connect to Device item. Choose Pocket PC 2002 Emulator (Default). You probably noticed there's a Windows CE .NET emulator also. Click Connect and the emulator should start in a few seconds. The first thing you'll want to do is set up your internet connection on it. You can do that from the Start menu -> Settings -> Connections tab -> Connections icon.

Aside from the fact that this emulator is a very useful tool for testing your Pocket PC applications, you can also use it to see how your ASP .NET mobile pages look like on the Internet Explorer mobile browser. Open the MobileWebForm we created earlier in this article to see how the forms and controls we added look like on this device. Here's the calendar,forexample.

Page 306 ASP.NET MATERIAL

You can apply some stylesheet to it so it will look much better than it does now.

So this emulator can also be used for testing web application, not just Windows mobile applications. A useful tool along with the emulators from Openwave and your WAP enabled cell phone. Using these you can develop flawless mobile applications.

• Mobile Asp.Net Architecture:

Mobile Application Architecture:

Although ASP.NET integrates technology to make ASP.NET mobile Web application development follow the same paradigm as traditional Web application development, the architecture's primary intent is not to allow you to create single pages that can target browsers in both desktop and mobile devices. You can create adapters for individual ASP.NET or for mobile Web server controls that allow these controls to render for both desktop and mobile device browsers, but the limitations of browsers on mobile devices often mean that pages designed for desktop browsers do not translate very well to mobile device browsers.

For example, if you create an ASP.NET Web page that includes a site header, a navigation bar along the top of the page, a secondary navigation structure along the side

Page 307 ASP.NET MATERIAL of the page, and then content in the rest of the page, the page will render as designed in a desktop browser. In that case, there is usually ample space to render all the controls and still provide a scrollable content area. However, in many mobile device browsers, this layout would be impossible. Many mobile devices have a smaller screen area than desktop monitors, so even navigation becomes a multi-step process in which the user must click several controls to get to page content.

Presentation logic follows a similar pattern. For example, when the user fills in a Web form using a desktop browser, the user can see many controls on the screen at once. When the form is validated on the server, validation errors can be displayed next to the controls. With a mobile device, form input and validation can be much harder to display in a format is usable. Additionally, for mobile devices you might choose to provide shortcuts that allow the user to fill in information with less typing because the device might be difficult to type on.

For these reasons, it is recommended that you create separate pages in your ASP.NET Web application for use in desktop and mobile device browsers. A page developed specifically for mobile device browsers allows you to break down presentation logic into smaller pieces that work better for the device's display area and input hardware. When considering building such pages, therefore, you should use mobile Web server controls if your application must support a wide range of mobile devices, support browsers that do not use HTML, or support devices with limited display and input capabilities.

Mobile Web Server Controls:

The ASP.NET 2.0 System.Web.Mobile namespace is devoted specifically to mobile Web development. You can create a mobile Web page from the MobilePage base class and add mobile Web server controls from the System.Web.Mobile namespace. Mobile Web server controls have a number of specialized adapters in the framework and are therefore especially geared to developing mobile Web applications that target a wide range of mobile devices.

ASP.NET Web Server Controls and the Unified Adapter Architecture:

All ASP.NET 2.0 Web server controls adhere to the unified adapter architecture. This means that all controls can render and behave differently depending on the requesting device by calling a custom adapter that provides appropriate behaviors for that device, such as creating the proper markup language. If an adapter is configured in the browser definitions file for the requesting device or browser, ASP.NET calls the adapter at each life cycle stage of a Web server control. The adapter can then adjust rendered output and handle any device-specific view state logic or device idiosyncrasies. Browser definition files can be found in the Browsers folder of the .NET Framework Config directory or in the App_Browsers folder of a Web application.

Page 308 ASP.NET MATERIAL You can create custom adapters for each device and have the ASP.NET page framework use those adapters when a specific device accesses your page.

Choosing Custom Adapters or Mobile Controls:

For most page developers, using the mobile Web server controls and creating pages that inherit from MobilePage is the recommended approach to mobile development. These controls support many mobile devices such as cell phones. ASP.NET includes mobile Web server controls for a wide variety of general Web development and mobile-specific needs. Additionally, mobile control device adapters already exist for major devices and their markup languages.

Microsoft will continue to provide adapter updates for the mobile Web server controls when major markup languages evolve. This allows you to support new markup languages with the same controls that you are already using. For example, if you are creating an e- commerce site that supports desktop browsers as well as a large array of mobile devices, the recommended approach is to create a set of ASP.NET pages that inherit from the Page class and a separate set of pages that inherit from the MobilePage base class and use mobile controls. This provides you with mobile support without having to create custom adapters.

The mobile Web server controls also follow the unified adapter architecture, so if you need to, you can create your own custom adapters or modify existing ones where new devices dictate new behavioral requirements in mobile Web server controls.

There are scenarios where using ASP.NET Web server controls and writing custom adapters makes sense. These typically will be applications for rich desktop browsers where browser behavior variations are required, or for applications to be targeted by a constrained device class for which mobile controls and their feature set is not warranted. One example might be if you were creating an insurance claim application that had a browser-based interface for office use and a rich-device interface for field use. Your application could then use the same base page classes for both the regular pages and the rich-device pages. You would then need to create custom adapters only for the device that was deployed in the field.

A benefit of creating custom adapters for the ASP.NET Web server controls is therefore that you can use the Page base class for your Web pages and be able to take full advantage of the ASP.NET 2.0 feature set.

Page 309 ASP.NET MATERIAL • MMIT [Microsoft Mobile Internet Toolkit]:

Introduction:

The ASP.NET Mobile controls are formerly known as the Microsoft Mobile Internet Toolkit (MMIT). Mobile controls extend the power of the .NET Framework and Visual Studio to build Mobile Web applications.

The ASP.NET Mobile controls reduce the work required for developers to target a wide variety of browsers by eliminating the need to write and maintain numerous web applications each targeted to a specific browser.

The ASP.NET Mobile controls render the appropriate markup (HTML 3.2, WML 1.1, cHTML. XHTML) while dealing with different screen sizes, orientations and device capabilities.

Mobile Web Forms Controls:

Mobile Web Forms Controls generate markup language for different devices. These are ASP.NET server side controls that provide user interface elements such as:

• List • Command • Call • Calendar • Form • Panel • Image, etc. The Mobile controls generate the correct markup for the device that makes the request at execution time. As a result, you can write a Mobile application once and access it from multiple devices.

Because these Mobile controls are based on the ASP.NET controls, you can leverage your current desktop development skill set when creating mobile applications.

You can also reuse the same business logic and data access code that you use in your desktop application. Mobile and desktop Web Forms can reside in the same Visual Studio .NET project. This makes an application faster to develop and lowers your maintenance cost.

Mobile Web forms controls are as follows:

Page 310 ASP.NET MATERIAL

Figure 1: Mobile Web Form Controls.

Creating Mobile Web Form Controls:

There are the following steps for creating the Mobile Web Form Controls.

Step 1: For creating a Mobile Web project open the new Web site in Microsoft visual studio 2005. You will get the following window.

Page 311 ASP.NET MATERIAL

Figure 2: Open New Website.

Step 2: After open the New Website, go to the Solution Explorer right click on the Website and click on Add New item then you will get the following window:

Figure 3: Add New Item in Solution Explorer. Step 3: Add a mobile Web Forms page to the project. You will see the following code-

Page 312 ASP.NET MATERIAL <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

Step 4: Drag a Mobile Web Forms control onto the form. Suppose we want to print Name and Address of any user in the Textbox. Then we drag two Textbox and two labels. Label is optional. The source code is as follows:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl2.ascx.cs"Inherits="WebUserControl2"%> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls"Assembly="System.Web.Mobile" %>

User name Address

In the following figure two Labels and two Textbox are drag from the Mobile controls. So the design view of the source code is as follows:

Figure 4: Design view of the above source code. Step 5: Double-click the control to write the logic.

Page 313 ASP.NET MATERIAL Step 6: Rebuild the application.

Step 7: Run the application.

Mobile Internet Designer:

The Mobile Internet Designer extends the Visual Studio .NET IDE to create Mobile applications. After you install the Mobile Internet Designer, you can create and develop your Mobile application in the same way that you would develop a Windows Forms or Web Forms application.

The Mobile Internet Designer makes it fast and easy to build and maintain Mobile Web applications.

DeviceCapabilityMechanism:

Accurate information about the display capabilities of the target device is essential for the successful rendering of Mobile controls. Mobile controls need the following information about a device:

• Markup language (HTML, WML, cHTML) • Browser • Number of display lines • Cookie support • Screen size The Mobile Internet Toolkit adds these mobile device capabilities to the server's machine.config file (desktop ASP.NET applications use this file to maintain device and browser information).

Advanced Features: Extensibility

Device adapter includes in the Mobile Internet Toolkit for a variety of mobile devices.

Through the device capabilities mechanism The Mobile Internet Toolkit supports device adapters for additional devices. You can create new aggregate controls from existing Mobile controls.

Conclusion:

The Mobile Internet Toolkit provides the technology and tools to build, deploy, and maintain sophisticated Mobile applications quickly. Additional device support can be added using the Mobile Internet Toolkit's extensibility features.

Page 314 ASP.NET MATERIAL • Creating Mobile ASP.NET Page

ASP.NET Mobile Controls Overview:

Writing dynamic, high-performance mobile Web applications has never been easier.

Over the past few years, the world has seen an explosion of new wireless devices, such as cell phones, pagers, and personal digital assistants (PDAs), which enable users to browse Web sites at any time from any location. Developing applications for these devices is challenging for the following reasons:

• Different markup languages are necessary, including HTML for PDAs, wireless markup language (WML) for wireless application protocol (WAP) cell phones, and compact HTML (cHTML) for Japanese i-mode phones. • Devices have different form factors. For example, devices have varying numbers of display lines, horizontal or vertical screen orientation, and color or black and white displays. • Devices have different network connectivity, ranging from 9.6 KB cellular connections to 11 MB Wireless LANs. • Devices have different capabilities. Some devices can display images, some can make phone calls, and some can receive notification messages.

The Microsoft Mobile Internet Toolkit addresses these challenges by isolating them from the details of wireless development. Thus, developers can quickly and easily build a single, mobile Web application that delivers appropriate markup for a wide variety of mobile devices.

Figure 1. The Hello, World program renders to both a cell phone and a Pocket PC

Page 315 ASP.NET MATERIAL The Mobile Internet Toolkit contains:

• Mobile Web Forms Controls that generate markup language for different devices. • Mobile Internet Designer that works with the Visual Studio .NET integrated design environment (IDE) to provide a drag-and-drop mobile development environment. • Browser Capabilities that are rich enough to extend ASP.NET device capabilities to mobile devices. • QuickStart Tutorial with sample code. • Developer Documentation. • Device adapter code samples.

Mobile Web Forms Controls:

The mobile Web Forms controls are ASP.NET server-side controls that provide user interface elements such as list, command, call, calendar, and so on. At execution time, the mobile controls generate the correct markup for the device that makes the request. As a result, you can write a mobile application once and access it from multiple devices.

Because these mobile controls are based on the ASP.NET controls, you can leverage your current desktop development skill set when creating mobile applications. You can also reuse the same business logic and data access code that you use in your desktop application. Mobile and desktop Web Forms can reside in the same Visual Studio .NET project. This makes an application faster to develop and lowers your maintenance cost.

The following example provides just a taste of programming with mobile controls. In this example, the Hello, World program creates a mobile Web Forms page with a single form on it. That form contains a Label control with the string: “Hello, Mobile World”.

<%@ Page language="C#" Inherits="System.Web.UI.MobileControls.MobilePage" %> <%@ Register TagPrefix="Mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

Hello, Mobile World

In Figure 1 above, you can see how this code renders on different devices. The first device is a cell phone running a WAP browser that supports WML. The second device is Pocket PC running an HTML browser.

Page 316 ASP.NET MATERIAL The Mobile Internet Toolkit also enables you to customize the markup that is generated by mobile controls for a specific device. You can designate templates and styles for a specific device within the mobile page.

Mobile Internet Designer:

The Mobile Internet Designer extends the Visual Studio .NET IDE to create mobile applications. After you install the Mobile Internet Designer, you can create and develop your mobile application in the same way that you would develop a Windows Forms or Web Forms application. The Mobile Internet Designer leverages the traditional Visual Studio design environment so that you can:

• Create a mobile Web project. • Add a mobile Web Forms page to the project. • Drag a mobile Web Forms control onto the form. • Double-click the control to write the logic. • Rebuild the application. • Run the application.

The Mobile Internet Designer makes it fast and easy to build and maintain mobile Web applications. In addition, it enables today's desktop developers to quickly learn how to create mobile applications by using Visual Studio .NET.

The following illustration shows a mobile application developed in Visual Studio .NET with the Mobile Internet Designer.

Figure 2. Device Capability Mechanism

Page 317 ASP.NET MATERIAL Accurate information about the display capabilities of the target device is essential for the successful rendering of mobile controls. At a minimum, mobile controls need the following information about a device:

• Markup language (HTML, WML, cHTML) • Browser • Number of display lines • Cookie support • Screen size

The Mobile Internet Toolkit adds these mobile device capabilities to the server's machine.config file (desktop ASP.NET applications use this file to maintain device and browser information).

Advanced Features: Extensibility:

In addition to adding device characteristics, the Mobile Internet Toolkit includes device adapters for a variety of mobile devices. The device capabilities information in the machine.config file allows device adapters to optimize markup for specific devices. You can create new aggregate controls from existing mobile controls. The Mobile Internet Toolkit supports device adapters for additional devices through the device capabilities mechanism.

Conclusion:

The Mobile Internet Toolkit provides the technology and tools to build, deploy, and maintain sophisticated mobile applications quickly. Tight integration with Visual Studio .NET ensures that developers can leverage their existing desktop skill set and produce mobile applications. Additional device support can be added using the Mobile Internet Toolkit's extensibility features.

Page 318 ASP.NET MATERIAL SITE NAVIGATION

ASP.NET Site Navigation Overview:

You can use ASP.NET site-navigation features to provide a consistent way for users to navigate your site. As your site grows, and as you move pages around in the site, it can become difficult to manage all of the links. ASP.NET site navigation enables you to store links to all of your pages in a central location, and render those links in lists or navigation menus on each page by including a specific Web server control.

To create a consistent, easily managed navigation solution for your site, you can use ASP.NET site navigation. ASP.NET site navigation offers the following features:

• Site maps You can use a site map to describe the logical structure of your site. You can then manage page navigation by modifying the site map as pages are added or removed, instead of modifying hyperlinks in all of your Web pages. • ASP.NET controls You can use ASP.NET controls to display navigation menus on your Web pages. The navigation menus are based on the site map. • Programmatic control You can work with ASP.NET site navigation in code to create custom navigation controls or to modify the location of information that is displayed in a navigation menu. • Access rules You can configure access rules that display or hide a link in your navigation menu. • Custom site-map providers You can create custom site-map providers that allow you to work with your own site-map back end (for example, a database where you store link information) and plug your provider into the ASP.NET site- navigation system.

How Site Navigation Works:

With ASP.NET site navigation, you describe the layout of your site as a hierarchy. For example, a fictional online computer store might have a site comprised of eight pages, which are laid out in the following manner.

Home Products Hardware Software Services Training Consulting Support

Page 319 ASP.NET MATERIAL To use site navigation, start by creating a site map, or a representation of your site. You can describe the hierarchy of your site in an XML file, but other options are also available.

After you create a site map, you can display the navigation structure on an ASP.NET page by using a site-navigation control.

Site-Map Load Process:

The default ASP.NET site-map provider loads site-map data as an XML document and caches it as static data when the application starts. An excessively large site-map file can use a lot of memory and CPU power at load time. The ASP.NET site-navigation features depend on file notifications to keep navigation data up-to-date. When a site-map file is changed, ASP.NET reloads the site-map data. Make sure you configure any virus- scanning software so that it does not modify site-map files.

Site-Navigation Controls:

Creating a site map that reflects the structure of your site is one part of the ASP.NET site- navigation system. The other part is to display your navigation structure in your ASP.NET Web pages so that users can move easily around your site. You can easily build navigation into your pages by using the following ASP.NET site-navigation controls:

• SiteMapPath This control displays a navigation path — which is also known as a breadcrumb or eyebrow — that shows the user the current page location and displays links as a path back to the home page. The control provides many options for customizing the appearance of the links. • TreeView This control displays a tree structure, or menu, that users can traverse to get to different pages in your site. A node that contains child nodes can be expanded or collapsed by clicking it. • Menu This control displays an expandable menu that users can traverse to get to different pages in your site. A node that contains child nodes is expanded when the cursor hovers over the menu.

If you add a SiteMapPath control to the Training page from the online computer store in the preceding example, the SiteMapPath control will display something like the following, with Home and Services rendered as hyperlinks:

You can use the SiteMapPath control to create site navigation without code and without explicit data binding. The control can read and render the site-map information automatically. However, if necessary, you can also customize the SiteMapPath control with code.

Page 320 ASP.NET MATERIAL The SiteMapPath control allows users to navigate backward from the current page to pages higher in the site hierarchy. However, the SiteMapPath control does not allow you to navigate forward from the current page to another page deeper in the hierarchy. The SiteMapPath control is useful in newsgroup or message-board applications when users want to see the path to the article that they are browsing.

With the TreeView or Menu controls, users can open nodes and navigate directly to a specific page. These controls do not directly read the site map, as the SiteMapPath control does. Instead, you add a SiteMapDataSource control to a page that can read the site map. You then bind the TreeView or Menu control to the SiteMapDataSource control, resulting in the site map being rendered on the page. The TreeView control will display something like the following:

Site-Navigation API:

You can use navigation controls to add site navigation to your pages with little or no code, but you can also work with site navigation programmatically. When your Web application runs, ASP.NET exposes a SiteMap object that reflects the site-map structure. All of the members of the SiteMap object are static. The SiteMap object, in turn, exposes a collection of SiteMapNode objects that contain properties for each node in the map. (When you use the SiteMapPath control, the control works with the SiteMap and SiteMapNode objects to render the appropriate links automatically.)

You can use the SiteMap, SiteMapNode, and SiteMapProvider objects in your own code to traverse the site-map structure or create a custom control to display site-map data. You cannot write to the site map, but you can alter site-map nodes in the instance of the object.

Relationships Between Site-Navigation Components:

The following illustration shows the relationships between the ASP.NET site-navigation components.

Page 321 ASP.NET MATERIAL

Page 322 ASP.NET MATERIAL ASP.NET AJAX

Microsoft Ajax Overview:

When you build an Ajax application, you provide your users with a richer and more responsive user experience. You can use Ajax features to enhance server-based ASP.NET Web Forms applications by using server-side ASP.NET controls, such as the UpdatePanel control.

This topic focuses on enhancing server-based ASP.NET Web Forms applications.

Why Use Microsoft Ajax Features?

Web Forms applications that use Ajax features offer the following features:

• Familiar interactive UI elements such as progress indicators, tooltips, and pop-up windows. • Improved efficiency for Web Forms application, because significant parts of a Web page's processing can be performed in the browser. • Partial-page updates that refresh only the parts of the Web page that have changed. • Client integration with ASP.NET application services for forms authentication, roles, and user profiles. • Auto-generated proxy classes that simplify calling Web service methods from client script. • The ability to customize server controls to include client capabilities. • Support for the most popular browsers, which includes Microsoft Internet Explorer, Mozilla , and Apple .

Architecture of Microsoft Ajax Applications:

A Microsoft Ajax Web application consists of either a client-only solution or a client and server solution. A client-only solution uses Microsoft Ajax Library but does not use any ASP.NET server controls. For instance, an HTML can include script elements that reference the Microsoft Ajax Library .js files. The Microsoft Ajax Library allows Ajax applications to perform all processing on the client. A client and server solution consists of using both the Microsoft Ajax Library and ASP.NET server controls.

The following illustration shows the functionality that is included in the client-script libraries and server components that are included with .NET Framework 4.

Page 323 ASP.NET MATERIAL Microsoft Ajax client and server architecture:

The illustration shows the functionality of the client-based Microsoft Ajax Library, which includes support for creating client components, browser compatibility, and networking and core services. The illustration also shows the functionality of server-based Microsoft Ajax features, which include script support, Web services, application services, and server controls. The following sections describe the illustration in more detail.

Microsoft Ajax Client Architecture:

The client architecture includes libraries for component support, browser compatibility, networking, and core services.

Components:

Client components enable rich behaviors in the browser without postbacks. Components fall into three categories:

• Components, which are non-visual objects that encapsulate code. • Behaviors, which extend the behavior of existing DOM elements. • Controls, which represent a new DOM element that has custom behavior.

Page 324 ASP.NET MATERIAL The type of component that you use depends on the type of client behavior you want. For example, a watermark for an existing text box can be created by using a behavior that is attached to the text box.

Browser Compatibility:

The browser compatibility layer provides Microsoft Ajax scripting compatibility for the most frequently used browsers (including Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari). This enables you to write the same script regardless of which supported browser you are targeting.

Networking:

The networking layer handles communication between script in the browser and Web- based services and applications. It also manages asynchronous remote method calls. In many scenarios, such as partial-page updates that use the UpdatePanel control, the networking layer is used automatically and does not require that you write any code.

The networking layer also provides support for accessing server-based forms authentication, role information, and profile information in client script. This support is also available to Web applications that are not created by using ASP.NET, as long as the application has access to the Microsoft Ajax Library.

Core Services:

The Ajax client-script libraries in ASP.NET consist of JavaScript (.js) files that provide features for object-oriented development. The object-oriented features included in the Microsoft Ajax client-script libraries enable a high level of consistency and modularity in client scripting. The following core services are part of the client architecture:

• Object-oriented extensions to JavaScript, such as classes, namespaces, event handling, inheritance, data types, and object serialization. • A base class library, which includes components such as string builders and extended error handling. • Support for JavaScript libraries that are either embedded in an assembly or are provided as standalone JavaScript (.js) files. Embedding JavaScript libraries in an assembly can make it easier to deploy applications and can help solve versioning issues.

Page 325 ASP.NET MATERIAL Debugging and Error Handling:

The core services include the Sys.Debug class, which provides methods for displaying objects in readable form at the end of a Web page. The class also shows trace messages, enables you to use assertions, and lets you break into the debugger. An extended Error object API provides helpful exception details with support for release and debug modes.

Globalization

The Ajax server and client architecture in ASP.NET provides a model for localizing and globalizing client script. This enables you to design applications that use a single code base to provide UI for many locales (languages and cultures). For example, the Ajax architecture enables JavaScript code to format Date or Number objects automatically according to culture settings of the user's browser, without requiring a postback to the server.

Ajax Server Architecture:

The server pieces that support Ajax development consist of ASP.NET Web server controls and components that manage the UI and flow of an application. The server pieces also manage serialization, validation, and control extensibility. There are also ASP.NET Web services that enable you to access ASP.NET application services for forms authentication, roles, and user profiles.

Script Support:

Ajax features in ASP.NET are commonly implemented by using client script libraries that perform processing strictly on the client. You can also implement Ajax features by using server controls that support scripts sent from the server to the client.

You can also create custom client script for your ASP.NET applications. In that case, you can also use Ajax features to manage your custom script as static .js files (on disk) or as .js files embedded as resources in an assembly.

Ajax features include a model for release and debug modes. Release mode provides error checking and exception handling that is optimized for performance, with minimized script size. Debug mode provides more robust debugging features, such as type and argument checking. ASP.NET runs the debug versions when the application is in debug mode. This enables you to throw exceptions in debug scripts while minimizing the size of release code.

Script support for Ajax in ASP.NET is used to provide two important features:

Page 326 ASP.NET MATERIAL • The Microsoft Ajax Library, which is a type system and a set of JavaScript extensions that provide namespaces, inheritance, interfaces, enumerations, reflection, and additional features. • Partial-page rendering, which updates regions of the page by using an asynchronous postback.

Localization:

The Microsoft Ajax architecture builds on the foundation of the ASP.NET 2.0 localization model. It provides additional support for localized .js files that are embedded in an assembly or that are provided on disk. ASP.NET can serve localized client scripts and resources automatically for specific languages and regions.

Web Services:

With Ajax functionality in an ASP.NET Web page, you can use client script to call both ASP.NET Web services (.asmx) and Windows Communication Foundation (WCF) services (.svc). The required script references are automatically added to the page, and they in turn automatically generate the Web service proxy classes that you use from client script to call the Web service.

You can also access ASP.NET Web services without using Microsoft Ajax server controls (for example, if you are using a different Web development environment). To do so, in the page, you can manually include references to the Microsoft Ajax Library, to script files, and to the Web service itself. At run time, ASP.NET generates the proxy classes that you can use to call the services.

Application Services:

Application services in ASP.NET are built-in Web services that are based on ASP.NET forms authentication, roles, and user profiles. These services can be called by client script in an Ajax-enabled Web page, by a Windows client application, or by a WCF-compatible client.

Server Controls:

Ajax server controls consist of server and client code that integrate to produce rich client behavior. When you add an Ajax-enabled control to an ASP.NET Web page, the page automatically sends supporting client script to the browser for Ajax functionality. You can provide additional client code to customize the functionality of a control, but this is not required.

Page 327 ASP.NET MATERIAL The following list describes the most frequently used Ajax server controls.

Control Description Manages script resources for client components, partial-page rendering, localization, globalization, and custom user scripts. The ScriptManager ScriptManager control is required in order to use the UpdatePanel, UpdateProgress, and Timer controls. However, the ScriptManager control is not required when creating a client-only solution. Enables you to refresh selected parts of the page, instead of refreshing the UpdatePanel whole page by using a synchronous postback. Provides status information about partial-page updates in UpdatePanel UpdateProgress controls. Performs postbacks at defined intervals. You can use the Timer control to Timer post the whole page, or use it together with the UpdatePanel control to perform partial-page updates at a defined interval.

You can also create custom ASP.NET server controls that include Ajax client behaviors. Custom controls that enhance the capabilities of other ASP.NET Web controls are referred to as extendercontrols

Ajax Control Toolkit:

The Ajax Control Toolkit contains controls that you can use to build highly responsive and interactive Ajax-enabled Web applications. These controls do not require knowledge of JavaScript or Ajax. They are designed using concepts that are familiar to ASP.NET Web Forms application developers. Using the Ajax Control Toolkit, you can build Ajax- enabled ASP.NET Web Forms applications and ASP.NET MVC Web applications by dragging the controls from the Visual Studio Toolbox onto a page. The Ajax Control Toolkit is an open-source project that is part of the CodePlex Foundation. For more information, see the Ajax Control Toolkit on the CodePlex Web site.

INTRODUCTION TO VISUAL STUDIO 2008

Page 328 ASP.NET MATERIAL

This introduce the main features of the Visual Basic 2008 Express Edition, and walks you through some of the most common tasks you’ll be doing as you create your programs. You’ll be more familiar with the development environment and able to get started creating your first application.

Some of the topics covered :

• Setup • Creating a Project • The Windows Form Designer • Writing Visual Basic code • Compiling, Running and Saving your project • Errors and Debugging • Project Files, Properties and Customization • Data • Where to go from here

In This Section:

Installation and Setup Essentials

Find out about side-by-side support for earlier Visual Studio versions, the features available in each edition, and other information related to installing and maintaining Visual Studio.

Introducing Visual Studio

Find out more about what's new in Visual Studio, learn more about the .NET Framework, and find pointers on how to get started with this version of Visual Studio.

Application Development in Visual Studio

Find out about designing, developing, debugging, testing, deploying, and managing applications created by using Visual Studio.

Windows-based Applications, Components, and Services

Page 329 ASP.NET MATERIAL Decide which tools and technologies to use when you build applications and components, and also what items that you can create with Visual Studio.

.NET Framework Programming in Visual Studio

Learn how to use the .NET Framework when you develop applications in Visual Basic, and Visual C#.

Visual Basic

Learn what's new in Visual Basic, and discover how to use Visual Basic to develop applications.

Visual C#

Learn what's new in Visual C#, and discover how to use Visual C# to develop applications.

Visual C++

Find out about what's new in Visual C++ and discover how to use Visual C++ to develop applications.

JScript

Find out about JScript, a true object-oriented scripting language.

Visual Web Developer

Learn about Visual Web Developer and discover how to use Visual Web Developer to create Web applications.

Visual Studio Tools for Office

Find out how to create business applications that collect, analyze, adjust, or present information, and that take advantage of the functionality of Microsoft Office.

Smart Device Development

Learn how to develop software that runs on Windows CE-based smart devices such as Pocket PCs and Smartphones.

Page 330 ASP.NET MATERIAL Tools and Features

Read about Crystal Reports, programming for Windows Server features, and Application Verifier.

Visual Studio SDK

Find out about the Visual Studio Software Development Kit (SDK), which provides extensibility options and toolkits.

Visual Studio Tools for Applications 2.0

Lets you customize existing applications by using Visual Basic and Visual C# to create add-ins.

Visual Studio and .NET Framework Glossary

Read through definitions for common terms used in the .NET Framework.

Related Sections

Deciding Which Technologies and Tools To Use

Learn about the tools and technologies available to create various types of applications by using Visual Studio.

Page 331 ASP.NET MATERIAL WCF [Windows Communication Foundation]

Windows Communication Foundation:

Windows Communication Foundation (WCF) is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments.

In This Section:

Guide to the Documentation A set of suggested topics to read, depending on your familiarity (novice to well- acquainted) and requirements.

Conceptual Overview The larger concepts behind WCF.

Getting Started Tutorial A set of walkthrough topics that introduces you to the experience of programming WCF applications.

Basic WCF Programming A set of primer topics that you should understand to become a proficient WCF programmer.

WCF Feature Details Topics that let you choose which WCF feature or features you need to employ.

Extending WCF Topics that describe extending or customizing WCF to suit your unique requirements.

Guidelines and Best Practices Topics that can help you to avoid mistakes and to create reusable applications.

WCF Administration and Diagnostics Topics that describe a set of WCF functionalities that can help you monitor the different stages of an application’s life and diagnose problems.

WCF System Requirements A list of WCF requirements.

Page 332 ASP.NET MATERIAL Operating System Resources Required by WCF A list of the resources that are provided by the operating system.

Troubleshooting Setup Issues Describes how to troubleshoot WCF setup issues.

Windows Communication Foundation Glossary Glossary terms used in WCF.

WCF Samples Downloadable samples that provide working code projects that demonstrate features and programming techniques for WCF.

WCF Tools Tools that help you to create and debug WCF applications.

General Reference Topics that document the XML elements used to configure services and client applications.

Feedback and Community Information about sending your comments or sharing information with others interested in WCF.

Windows Communication Foundation Privacy Information (Version 3.0) Information on a feature-by-feature basis about what WCF applications reveal about end users.

Reference:

System.Runtime.Serialization

System.Runtime.Serialization.Configuration

System.IdentityModel.Claims

System.IdentityModel.Policy

System.IdentityModel.Selectors

System.ServiceModel.Security.Tokens

System.ServiceModel

Page 333 ASP.NET MATERIAL System.ServiceModel.Channels

System.ServiceModel.Configuration

System.ServiceModel.Security

System.ServiceModel.Description

System.IdentityModel.Tokens

System.ServiceModel.MsmqIntegration

System.ServiceModel.PeerResolvers

System.Xml

System.ServiceModel.Dispatcher

System.IO.Log

System.ServiceModel.Activation

Page 334 ASP.NET MATERIAL INTRODUCTION TO SILVER LIGHT

What is Silverlight?

Silverlight is a browser plug-in that that extends the web development experience far beyond the limitations of plain HTML and JavaScript. Being a Microsoft product, you might expect it to work best (or only) on Windows and Internet Explorer. So you may be pleasantly surprised to know that it works equally well on Windows and on the Mac, and it also works equally well on the Firefox and Safari web browsers. Since Silverlight is a client side technology, it doesn't matter what backend server software or platform you're running - even Apache/Linux will do just fine.

Version 1.0

Silverlight version 1.0 - scheduled for release this summer - is very comparable to Adobe Flash. It delivers high performance multimedia and animation capabilities that can blend seamlessly with HTML. It's capable of playing a variety of audio and video file formats, such as MP3, WMA, and WMV. It handles streaming quite well, so media can start playing immediately without having to wait for the entire file to download.

Silverlight's user interface is defined with a subset of XAML - an XML format shared with Windows Presentation Foundation (WPF). This facilitates vector based animations, a claim that goes beyond Flash's current capabilities. Silverlight's compiled object model can be navigated via JavaScript for seamless interaction between embedded Silverlight components and the page that hosts them.

When users encounter a Silverlight 1.0 enhanced web page for the first time, they'll be prompted with the quick & easy installation that's only about a 1.2 megabyte download.

Version 1.1:

While the multimedia and animation capabilities of Silverlight 1.0 are certainly great for graphic designers, Silverlight version 1.1 (currently in alpha) starts to provide the kind of business oriented functionality that the majority of web developers need.

Probably the most exciting feature of version 1.1 is the built-in cross platform subset of the .NET Framework. While you can still mix in as much (or as little) JavaScript as you'd like, you'll now have the option of running your own fully compiled .NET code within IE, Firefox, or Safari. Those developers who hate JavaScript should be thrilled to know they can now write their client side code in C#, VB.NET, or any other .NET

Page 335 ASP.NET MATERIAL language. This .NET code can interact with the browser's object model so it can manipulate the page's HTML in addition to interacting with any Silverlight user interface that may be embedded in the page. You'll now be able to replace slow performing JavaScript code with fully compiled .NET code that could easily execute hundreds of times faster.

A variety of useful classes are included in Silverlight 1.1 for working with cutting edge technologies like LINQ, generics, multithreading, and invocation of Windows Communication Foundation (WCF) web services. There's also support for XML manipulation, networking, I/O, collections, globalization, and JSON serialization.

ASP.NET support is also provided for things like personalization, profiles, role membership, and invocation of ASMX web services. On a related note, the next release of ASP.NET is expected to include a variety of tools for easing Silverlight development, including built-in controls that make it easy to embed Silverlight content.

Unfortunately there are currently no definite plans to include any significant number of controls in Silverlight 1.1 - not even a basic button control is currently in the mix. They do at least provide a control class that can be used to build your own controls, and alternately it's not terribly difficult to make basic controls using XAML and some custom code - but certainly we'd prefer not to have to write such basic code. Luckily there are several controls available in the separate Silverlight 1.1 Alpha SDK download.

Since Silverlight 1.1 is still only in alpha, its uncertain exactly what other functionality may ultimately make it into the release version. The current download size for this far more functional version of Silverlight hovers at around 4MB.

Future Versions:

From my conversations with Silverlight mastermind Scott Guthrie and his merry band of genius underlings, they've got a lot of mouthwatering functionality planned for upcoming versions of Silverlight. General themes include a rich set of built-in controls, data binding support, XLINQ, RSS, Xml Serialization, support, and improved layout management. And that's just for starters.

In general the vision is to transform Silverlight from its current 1.0 state of multimedia powerhouse into a highly productive business tool capable of powering rich applications of virtually every kind.

Even with all this extra functionality, Silverlight's team has a long term secret goal of keeping the download size under 5MB. Shhhh! Don't tell anybody!

Page 336 ASP.NET MATERIAL Development Tools:

Currently the lack of polished tools for developing Silverlight applications is its biggest hindrance. The next version of Visual Studio (codenamed Orcas) is expected to ship with rich Silverlight support. However, the current beta version of Orcas clearly still needs a lot of work before achieving this goal. If you're brave enough to be tinkering with the Orcas beta then you might as well download the Silverlight Tools Alpha add-on to try out its Silverlight development capabilities.

Microsoft's new Expression suite of products is currently closer to being in a finished state. They are presently more polished and less buggy than Orcas. Specifically, Expression Blend is probably the most valuable Expression product for Silverlight development. However, be forewarned that the Expression suite is intended more for graphic designers than software developers. Therefore Visual Studio-oriented developers should expect a significant learning curve.

Summary:

Silverlight is a brilliant idea that still has a ways to go before it reaches its potential. Nevertheless, it should definitely be on every web developer's radar. It's a distinct possibility that Silverlight could be the future of web development. Imagine a world where web developers no longer deal with HTML, and instead write rich, compiled .NET code that runs everywhere as ubiquitously as HTML does now. If Microsoft plays its cards right, this will happen.

References:  Silverlight's web site  Silverlight download  Silverlight documentation  Free video tutorials  Visual Studio "Orcas" Beta 1  Microsoft Silverlight Tools Alpha for Visual Studio codename “Orcas” Beta 1  Microsoft Expression Blend 2 Free Trial  Microsoft ASP.NET Futures

Page 337