Writing a Custom HTTP Handler

Every resource processed by ASP.NET is processed by an actor called an HTTP handler. For example, web pages with the extension .aspx are processed by a page handler, while stand-alone web services with the extension .asmx are processed by a SOAP handler. All these classes are implementations of the IHttpHandler interface. When you associate your custom file type with the ASP.NET runtime, as shown in the previous section, you have to tell ASP.NET how to process this resource. The way to do this...

Creating an HTTP Handler for NonHTML Content

Some of the most interesting HTTP handlers don't generate HTML. Instead, they render different types of content, such as images. This approach gives you the flexibility to retrieve or generate your content programmatically, rather than relying on fixed files. For example, you could read the content for a large ZIP file from a database record and use Response.BinaryWrite to send it to the client. Or, you could get even more ambitious and use your HTTP handler to dynamically create a ZIP archive...

Querying Data in an Asynchronous Page

The data source controls don't have any asynchronous support. However, many of the underlying ADO.NET classes, including SqlCommand and SqlDataReader, have asynchronous support. The following page takes advantage of the BeginReader and EndReader methods of the SqlDataReader. To allow the asynchronous query, you need to explicitly enable it in the connection string, as shown in the following snippet from the web.config file lt add name NorthwindAsync connectionString Data Source localhost...

Summary Vfv

In this chapter, you took a closer look at what constitutes an ASP.NET application. After learning more about the life cycle of an application, you learned how to code global application event handlers with the global.asax file and how to set application configuration with the web. config file. Finally, you learned how to use separately compiled components in your web pages and how to extend the HTTP pipeline with your own handlers and modules.

Converting the DataSet to XML

Using the XML methods of the DataSet is quite straightforward, as you'll see in the next example. This example uses two GridView controls on a page. The first DataSet is filled directly from the Employees table of the Northwind database. The code isn't shown here because it's similar to what you've seen in the previous chapters. The second DataSet is filled using XML. Here's how it works once the DataSet has been created, you can generate an XML schema file describing the structure of the...

Concurrency

Update errors can be caused by all the usual factors a timeout waiting for a connection, a network error, and so on but the most common update error is a concurrency problem. By default, update commands use optimistic concurrency, which attempts to match every value. This runs into immediate trouble when two users make overlapping changes. If you attempt to update a record, and that record no longer has the initial set of values you retrieved, the update fails with an...

Type Editors

So far you've seen how type converters can convert various data types to strings for representation in the Properties window. But some data types don't rely on string editing at all. For example, if you need to set an enumerated value such as BorderStyle , you can choose from a drop-down list of all the values in the enumeration. More impressively, if you need to set a color, you can choose from a drop-down color picker. And some properties have the ability to break out of the Properties window...

A File Browser

Using the concepts you've learned so far, it's quite straightforward to put together a simple file-browsing application. Rather than iterating through collections of files and directories manually, this example handles everything using the GridView and some data binding code. Figure 12-1 shows this program in action. f. Untitled Page - Windows Internet Explorer k - - - gj htt jbo tl0a WtM4FfcftnHV,a K X Pi' Movs Up I Qrrr nnV ivirwDj.Jprej rW ASF fiFTn V MOB pm ISWVfT Movs Up I Qrrr nnV...

Custom Expression Builders

One of the most innovative features of expressions is that you can create your own expression builders that plug into this framework. This is a specialized technique that, while impressive, isn't always practical. As you'll see, custom expressions make the most sense if you're developing a feature that you want to use to extend more than one web application. For example, imagine you want a way to create a custom expression builder that allows you to insert random numbers. You want to be able to...

Script Injection Attacks

Often, developers aren't aware of the security vulnerabilities they introduce in a page. That's because many common dangers including script injection and SQL injection are surprisingly easy to stumble into. To minimize these risks, technology vendors such as Microsoft strive to find ways to integrate safety checks into the programming framework itself, thereby insulating application programmers. One attack to which web pages are commonly vulnerable is a script injection attack. A script...

Post Injection Attacks

Savvy users might realize there's another potential avenue for attack with web controls. Although parameterized commands prevent SQL injection attacks, they don't prevent attackers from adding malicious values to the data that's posted back to the server. Left unchecked, this could allow attackers to submit control values that wouldn't otherwise be possible. For example, imagine you have a list that shows orders made by the current user. A crafty attacker could save a local copy of the page,...

Adding a Web Reference

You consume a web service in a Silverlight application in much the same way that you consume one in a full-fledged.NET application. The first step is to create a proxy class by adding a Visual Studio web reference. Note Before you begin, you need to know the correct URL for your web service. When testing your application, Visual Studio loads the test web server at a randomly chosen port. To add a web reference, you need to know this port. To find out what it is, run your website just before you...

Applying a Simple Theme

To add a theme to your project, select Website gt Add New Item or Project gt Add New Item and choose Skin File. Visual Studio will warn you that skin files need to be placed in a sub-folder of the App_Themes folder and will ask you if that's what you intended. If you choose Yes, Visual Studio will create a folder with the same name as your theme file. You can then rename the folder and the file to whatever you'd like to use. Figure 16-5 shows an example with a theme that contains a single skin...

A Custom Hotspot

The ImageMap control supports any HotSpot-derived hotspot class. ASP.NET includes exactly three, which correspond to the three basic types of lt area gt shapes defined in the HTML standard. However, you can create your own hotspots by deriving your own custom class from HotSpot. Obviously, a custom hotspot class can't do anything that falls outside the HTML standard. For example, it would be nice to have an ellipse and other curved shapes, but that just isn't available. However, you can create...

Defining Profile Properties

Before you can store anything in the aspnet_Profile table, you need to define it specifically. You do this by adding the lt properties gt element inside the lt profile gt section of the web.config file. Inside the lt properties gt element, you place one lt add gt tag for each user-specific piece of information you want to store. At a minimum, the lt add gt element supplies the name for the property, like this lt providers gt lt properties gt lt add name firstl lame gt lt add name Lastl lame gt...

Fundamental ADONET Classes

ADO.NET has two types of objects connection-based and content-based. Connection-based objects These are the data provider objects such as Connection, Command, DataReader, and DataAdapter. They allow you to connect to a database, execute SQL statements, move through a read-only result set, and fill a DataSet. The connection-based objects are specific to the type of data source, and are found in a provider-specific namespace such as System.Data.SqlClient for the SQL Server provider ....

Http Handlers And Session State

By default, HTTP handlers do not have access to client-specific session state. That's because HTTP handlers are generally used for lower-level tasks, and skipping the steps needed to serialize and retrieve session state information achieves a minor increase in performance. However, if you do need access to session state information, you simply need to implement one of the following two interfaces If you require just read-only access to session state, you should implement the...

Configuring Session State

You can configure session state through the lt sessionState gt element in the web.config file for your application. Here's a snapshot of all the available settings you can use lt xml version 1.0 encoding utf-8 gt lt configuration gt lt system.web gt lt -- Other settings omitted. -- gt lt sessionState mode InProc stateNetworkTimeout 10 sqlConnectionString data source 127.0.0.1 Integrated Security SSPI sqlCommandTimeout 30 useHostingIdentity true cookieless UseCookies lt system.web gt lt...

The XAML CodeBehind

XAML allows you to construct a user interface, but in order to make a functioning application, you need a way to connect the event handlers that have your application code. XAML makes this easy using the Class attribute shown here lt UserControl Width 400 Height 100 gt The x namespace prefix places the Class attribute in the XAML namespace, which means the Class attribute is a more general part of the XAML language, not a specific Silverlight ingredient. In fact, the Class attribute tells the...

Exposing the Inner Web Controls

One important detail to remember is that the user control's constituent controls can be accessed only by the user control. That means the web page that hosts the user control cannot receive the events, set the properties, or call the methods of these contained controls. For example, in the TimeDisplay user control, the web page has no ability to access the LinkButton control that it uses. Usually, this behavior is exactly what you want. It means your user control can add public properties to...

The LinqDataSource

The LINQ to SQL examples in this chapter so far have used pure code to retrieve, manipulate, and bind data. However, ASP.NET also includes a LinqDataSource control that you can use to perform many of these tasks automatically. Before taking a look at the LinqDataSource control, it's worth asking when it's appropriate. As with LINQ to SQL in general, LinqDataSource has applications in simple and complex scenarios. However, its most impressive niche is rapid application development when combined...

Starting from a Specific Node

The SiteMapDataSource has two more properties that can help you configure the navigation tree StartingNodeOffset and StartingNodeUrl. StartingNodeUrl is the easiest to understand it takes the URL of the node that should be the first node in the tree. This value must match the url attribute of the node in the Web. sitemap file exactly. For example, if you specify a StartingNodeUrl of home.aspx, then the first node in the tree is the Home node, and you will see only nodes underneath that node....

Custom Profile Providers

The profile model plugs neatly into ASP.NET web pages. However, it isn't very configurable. You might decide you need to create a custom profile provider for a number of reasons You need to store profile information in a data source other than a SQL Server database, such as an Oracle database. You need your profile data to be available to other applications. Parsing the information in the PropertyValuesString and PropertyValuesBinary fields is tedious, error-prone, and inflexible. If you need...

Multiple Connection Points

A web part provider can make multiple connection points available, while a web part consumer can consume multiple provider connection points. In that case, every connection point requires a unique ID on both the consumer side and the provider side. On the provider side, you specify the connection point ID in the ConnectionProvider attribute, as follows. Compared to your previously created provider CustomerNotesPart, you just add a unique ID as a second parameter to the ConnectionProvider...

Creating a Typed DataSet

To create a typed DataSet in Visual Studio, open a project, right-click the project in the Solution Explorer, and choose Add New Item. Then, choose DataSet, and supply the name you want to use for the generated DataSet class like NorthwindDataSet.xsd . If you're adding the typed DataSet directly to a Visual Studio website not a web project or a separate class library , Visual Studio will prompt you to place the code-behind for the typed DataSet in the App_Code folder, and you should accept....

Embedding Dynamic Graphics in a Web Page

The Image.Save approach has one problem that has been used in all the examples so far. When you save an image to the response stream, you overwrite whatever information ASP.NET would otherwise use. If you have a web page that includes other static content and controls, this content won't appear at all in the final web page. Instead, the dynamically rendered graphics will replace it. Fortunately, a simple solution exists. You can link to a dynamically generated image using the HTML lt img gt tag...

The Properties Window

The simplest attributes influence how the properties of your control appear in the Properties window. For example, you've probably noticed that the core set of ASP.NET web controls group their properties into several categories. When you select a property, the Properties window shows a brief description. To add this information to your own control, you need to decorate each property with the Category and Description attributes, as shown here _ lt Description The text to be shown in the control...

Asymmetric Encryption

Asymmetric algorithms try to solve some of the problems of symmetric algorithms. They are based on mathematical methods that require different keys for encryption and decryption. Usually the key used for encryption is called a public key. You can give this key to anyone who wants to send encrypted information to you. On the other hand, the private key is the only key that can be used for decryption. Therefore, if you are the only one with access to the private key, you are the only person who...

Calling Stored Procedures

Parameterized commands are just a short step from commands that call full-fledged stored procedures. As you probably know, a stored procedure is a batch of one or more SQL statements that are stored in the database. Stored procedures are similar to functions in that they are well-encapsulated blocks of logic that can accept data through input parameters and return data through result sets and output parameters . Stored procedures have many benefits They are easier to maintain For example, you...

The globalasax Application File

The global.asax file allows you to write event handlers that react to global events. Users never request the global.asax file directly. Instead, the global.asax file executes its code automatically in response to certain application events. The global.asax file provides a similar service to the global.asa file in classic ASP applications. You write the code in a global.asax file in a similar way to a web form. The difference is that the global.asax doesn't contain any HTML or ASP.NET tags....

Creating the Web Service

Although web services are used in a specialized way in ASP.NET AJAX pages, the way they're defined is the same. Like any ASP.NET web service, the web services you'll use with ASP.NET AJAX consist of two pieces an .asmx file that acts as the web service endpoint, and a .vb file that has the actual VB code. You add these files to the website that contains the ASP.NET AJAX page that will use the web service. The quickest way to create a web service in Visual Studio is to choose Website gt Add New...

Database Scripts for ASPNET Services

The aspnet_regsql.exe tool executes a couple of scripts for creating or dropping the membership-related database and database tables. These scripts ship with the .NET Framework you can find them in the .NET Framework directory, as shown in Figure 21-6. Two types of scripts exist InstallXXX and the corresponding UninstallXXX scripts. When an InstallXXX script installs a set of database tables such as the set needed for the membership API, the corresponding UninstallXXX script drops the same...

ASPNET AJAX on the Server The ScriptManager

Obviously, you wouldn't want to type long URLs that point to script resources on every page that requires ASP.NET AJAX. The solution is to use an ASP.NET control called the ScriptManager. The ScriptManager is the brains of the server-side ASP.NET AJAX model. It's a web control that doesn't have any visual appearance on the page. However, it performs a key task it renders the links to the ASP.NET AJAX JavaScript libraries. To add the ScriptManager to a page, you can drag it from the AJAX...

Web Part Editors

In the previous example, you created a custom web part with a personalizable property called Customer. This property determined whether the content of the GridView in the web part displays information for just one customer or for all customers. You were not able to change this property through the web part page's user interface, so you will now see how you can accomplish this. The ASP.NET Web Parts Framework provides functionality for editing properties of web parts. As you saw when creating...

Handling Hotspot Clicks

The next step is to make the hotspots clickable. A hotspot can trigger one of two actions it can navigate to a new page, or it can post back your page and fire the ImageMap.Click event . To choose which option you prefer, simply set the ImageMap.HotSpotMode property. rip When you set the ImageMap.HotSpotMode property, it applies to all hotspots. You can also override this setting for individual hotspots by setting the HotSpot.HotSpotMode property. This allows you to have some hotspots that post...

Brushes

Brushes are used to fill the space between lines. Brushes are used when drawing text or when using any of the FillXxxO methods of the Graphics class for painting the inside of a shape. You can quickly retrieve a predefined solid brush using a static property from the Brushes class, as shown here Dim myBrush As Brush Brushes.White You can also create a custom brush. You need to decide what type of brush you are creating. Solid brushes are created from the SolidBrush class, and other classes...

Pens

When you use the DrawXxx methods from the Graphics class, the border of the shape or curve is drawn with the Pen object you supply. You can retrieve a standard pen using one of the static properties from the System.Drawing.Pens class. These pens all have a width of 1 pixel. They differ only in their color. You can also create a Pen object on your own and configure all the properties described in Table 29-3. Here's an example Dim myPen As New Pen Color.Red myPen.DashCap DashCap.Triangle...

Rollover Buttons

Rollover buttons are another useful JavaScript trick that has no equivalent in the ASP.NET world. A rollover button displays one image when it first appears and another image when the mouse hovers over it and sometimes a third image when the image is clicked . To provide the rollover effect, a rollover button usually consists of an lt img gt tag that handles the onclick, onmouseover, and onmouseout JavaScript events. These events will call a function that swaps images for the current button,...

Storing Objects in View State

You can store your own objects in view state just as easily as you store numeric and string types. However, to store an item in view state, ASP.NET must be able to convert it into a stream of bytes so that it can be added to the hidden input field in the page. This process is called serialization. If your objects aren't serializable and by default they aren't , you'll receive an error message when you attempt to place them in view state. To make your objects serializable, you need to add the...

Browser Detection

So, how does ASP.NET decide which type of text writer suits a particular client It's all based on the user-agent string that the client supplies when it makes a request. ASP.NET tries to match this string against a large catalog of known browsers. You can find this catalog in c There you'll see a number of .browser files. Each one is an XML file that maps a user-agent string to a set of capabilities and a text writer. Every .browser file has this basic structure lt browsers gt lt browser id...

Using Selection to Create a MasterDetails Form

As demonstrated in the previous chapter, you can bind other data sources to a property in a control using parameters. For example, you could add two GridView controls and use information from the first GridView to perform a query in the second. In the case of the GridView, the property you need to bind is SelectedIndex. However, this has one problem. SelectedIndex returns a zero-based index number representing where the row occurs in the grid. This isn't the information you need to insert into...

The PageRequestManager Class

Another keenly important class is the PageRequestManager. The PageRequestManager is created if the page supports partial rendering, and uses one or more UpdatePanel controls on the server side. The PageRequestManager class fires a series of events that you can respond to with client-side JavaScript code. Table 32-6 lists these events. In previous examples in this chapter, you've used the PageRequestManager to handle asynchronous callback errors with the UpdatePanel control by handing endRequest...

The Custom WebParts Skeleton

First, you have to create a custom class that inherits from WebPart. Also, you need to import the System.Web.UI.WebControls.WebParts namespace so you have easy access to the Web Parts Framework classes. Imports System.Web.UI.WebControls.WebParts Namespace Apress.WebParts.Samples Public Class CustomerNotesPart Inherits WebPart Public Sub New End Sub End Class End Namespace Next, add some properties to your web part. For every property procedure in your class, you can specify whether the property...

Timeout

Another important session state setting in the web.config file is the timeout. This specifies the number of minutes that ASP.NET will wait, without receiving a request, before it abandons the session. lt sessionState timeout 20 gt This setting represents one of the most important compromises of session state. A difference of minutes can have a dramatic effect on the load of your server and the performance of your application. Ideally, you will choose a time frame that is short enough to allow...

Toolbox

The Toolbox works in conjunction with the document window. Its primary use is providing the controls that you can drag onto the design surface of a web form. However, it also allows you to store code and HTML snippets. The content of the Toolbox depends on the current designer you're using as well as the project type. For example, when designing a web page, you'll see the set of tabs described in Table 2-3. Each tab contains a group of buttons. To view a tab, click the heading, and the buttons...

VaryByControl

If your user control contains input controls, it's difficult to use caching. The problem occurs if the content in the input controls affects the cached content that the user control displays. With ordinary caching, you're stuck reusing the same copy of the user control, regardless what the user types into an input control. A similar problem exists with web pages, which is why it seldom makes sense to cache a web page that includes input controls. The VaryByControl property solves this problem....

Disabling Request Validation

Of course, in some situations, the request validation rules are just too restrictive. For example, you might have an application where users have a genuine need to specify HTML tags or a block of XML data. For example, consider a web application that requires that the user submit a block of formatted HTML that represents an auction listing or an advertisement. In these situations, you need to specifically disable script validation using the ValidateRequest property of the Page directive, as...

Application State

Application state allows you to store global objects that can be accessed by any client. Application state is based on the System.Web.HttpApplicationState class, which is provided in all web pages through the built-in Application object. Application state is similar to session state. It supports the same types of objects, retains information on the server, and uses the same dictionary-based syntax. A common example with application state is a global counter that tracks how many times an...

Adding Caching

One issue you might notice with the SqlSiteMapProvider is that it stores the root node for the current site map in memory indefinitely. This means the SqlSiteMapProvider uses the same site map until the application domain is restarted for example, when you rebuild your website or change its configuration settings . If you plan to change your site map regularly, you have several choices to make sure your application notices the change and refreshes the site map. The best option is to use the...

The Item Removed Callback

ASP.NET also allows you to write a callback method that will be triggered when an item is removed from the cache. You can place the method that handles the callback in your webpage class, or you can use a static method in another accessible class. However, you should keep in mind that this code won't be executed as part of a web request. That means you can't interact with web-page objects or notify the user. The following example uses a cache callback to make two items dependent on one another...