June 2006 - Posts

Displaying Formatted Source Code in a Web Page
30 June 06 09:51 AM | Scott Mitchell | with no comments

In my last blog entry you may have noticed that my code snippet looks rather spiffy. Here, let me show off just how spiffy my source code formatting is!

1 private ProductsTableAdapter _productsAdapter = null;

2 protected ProductsTableAdapter Adapter

3 {

4 get {

5 if (_productsAdapter == null)

6 _productsAdapter = new ProductsTableAdapter();

7

8 return _productsAdapter;

9 }

10 }

11

12 [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]

13 public Northwind.ProductsDataTable GetProducts()

14 {

15 return Adapter.GetProducts();

16 }

Whee, that was fun and easy. Easy because of a free Visual Studio plug-in (one for VS.NET, one for VS 2005) I found earlier in the week, Colin Coller's CopySourceAsHtml (CSAH). Just highlight source code in Visual Studio, right-click and choose Copy as Html. Colin's plug-in then converts the highlighted code into HTML that accurately reflects your Visual Studio's appearance settings. A quick and easy way to show your code on your blog or in online articles!

The only downside I see is that it appears that you can't CopyHtmlAsHtml. That is, when I highlight markup in an ASP.NET page, there's no Copy as Html option in the context menu.

Filed under:
Customizing the TableAdapter
27 June 06 11:55 AM | Scott Mitchell | with no comments

In my Working with Data in ASP.NET 2.0 tutorial series, Tutorial #1 begins the series by creating a Data Access Layer (DAL) using a Typed DataSet. A Typed DataSet is composed of a collection of strongly-typed DataTables and TableAdapters. The DataTables serve as business objects for holding the underlying database data, whereas the TableAdapters function as the DAL, synchronizing the contents of the business objects with the underlying data store.

The code for the TableAdapters is automatically generated by Visual Studio based on their properties and how you configured it in the Create TableAdapter Wizard. However, TableAdapters are implemented as partial classes, meaning it's possible to extend the functionality of the auto-generated TableAdapter by adding your own class file. The benefit of the partial class approach is that you can add methods and properties to the auto-generated TableAdapter without fear of having your modifications eaten the next time Visual Studio wants to regenerate the code. Let's look at how to utilize the fact that the TableAdapter is a partial class.

The TableAdapter's data store-specific details - the connection information, the command-level settings, and so on - are buried in its code as internal and private properties and methods. This makes sense, as the point of the DAL (and OOP in general) is to abstract away implementation details. However, there may be times where you need to update the connection string from the Business Logic Layer (BLL), or change the CommandTimeout for particularly long-running queries. By simply creating a new class file in your project, you can add public properties or methods to the TableAdapter than can access and modify those private and internal properties. For example, the following code adds a public ConnectionString property and a public SetCommandTimeout(timeout) method to the ProductsTableAdapter class (one of the TableAdapters created in the Working with Data in ASP.NET 2.0 tutorial series):

1 namespace NorthwindTableAdapters

2 {

3 public partial class ProductsTableAdapter

4 {

5 public string ConnectionString

6 {

7 get

8 {

9 return this.Connection.ConnectionString;

10 }

11 set

12 {

13 Connection.ConnectionString = value;

14 }

15 }

16

17 public void SetCommandTimeout(int timeout)

18 {

19 foreach (IDbCommand command in CommandCollection)

20 command.CommandTimeout = timeout;

21 }

22 }

23 }

This property and method can then be used in the BLL after creating an instance of the TableAdapter and before issuing the call to access data (such as GetProducts()).

One word of warning - exposing implementation details in the DAL may be necessary for certain scenarios, but don't make a habit of it. Ideally, the DAL and BLL and presentation tier should each be self-contained and not need to “leak” implementation details or settings to other tiers...

Filed under:
SoCal CodeCamp Talks
24 June 06 05:12 PM | Scott Mitchell | with no comments

Just got back from giving my two talks at the SoCal CodeCamp here in San Diego [1]. Both talks went well, a couple of minor hiccups during the “writing code by the seat of my pants” portions, but nothing that couldn't be quickly debugged and fixed. Thanks to everyone who attended the talks.

The PowerPoint slides and code demos are available online at http://datawebcontrols.com/classes/SoCalCodeCamp2.zip

Off to the Geek Dinner here in a bit; and there's a whole 'nother day of CodeCamp talks tomorrow.

Filed under:
Supporting HTTP Authentication and Forms Authentication in a Single ASP.NET Web Site
23 June 06 10:24 AM | Scott Mitchell | with no comments

Authenticating users visiting an Internet-based website is usually accomplished in one of two ways:

  • Using Forms authentication - here a user is prompted for their credentials through a standard web page form
  • Using HTTP authentication - RFC 2617 defines two standard HTTP protocol-level authentication schemes - Basic authentication and Digest authentication. When a browser interfaces with a site using this form of authentication, it displays that familiar modal dialog box prompting you for your credentials (see this image).

Many websites use Forms authentication, as it provides more control over the user experience and many platforms (such as ASP.NET) include tools for adding Forms authentication support. (In fact, with ASP.NET 2.0, you can build a complete user account-based website using Membership and Forms authentication without having to write a line of code; see Examining ASP.NET 2.0's Membership, Roles, and Profile for more information.)

However, Forms authentication is not a standard; while it's easy for a human to provide their credentials through Forms authentication, it's much more difficult for a computer program since the HTML inputs for the credentials can differ from site to site. With the standard HTTP protocol-level authentication schemes, however, the workflow for authentication is much more mechanical and can easily be supported by a computer program. In fact, tools like wget, Microsoft's Background Intelligent Transfer Service (BITS), and many RSS readers support built-in HTTP authentication.

Traditionally, Forms authentication is handled at the ASP.NET level, while the HTTP authentication schemes are configured from the web server level. This means that Forms authentication can easily be configured to authenticate users against a credential store located in some XML file, a database table... whatever. With HTTP authentication, the user credential store consulted for authentication is typically the Windows User Store.

Consider the case of a blog or forum site, where we have certain resources that we want to protect. For example, imagine that at a forum site there is a forum that is “private,“ meaning that only a set of users can view the forum's posts. It's easy to establish authorization rules in Web.config and use Forms authentication to identify users. However, imagine that our forum website offers RSS feeds of the forum's most recent posts. How do we share the RSS feeds for the private forums? RSS readers can't authenticate via Forms authentication.

One option, which is what is used by CommunityServer, is to use a unique RSS subscription URL per user. The only issue here is that if that particular URL is leaked somehow, anyone can consume the private forum feeds. Rob Howard and I discuss this feature in CommunityServer in this forum post: Enable RSS on non-public forums. Another option is to support both HTTP and Forms authentication and have it so that they both use the same credential store (such as that database table or XML file or what have you...)

Back in April 2006, Atif Aziz and I published an article on MSDN Online on how to build an ASP.NET web application that can do just this. In particular, the article examines MADAM, a collection of HTTP Modules for handling this sort of functionality. With MADAM you can define in Web.config what conditions would require the authentication scheme to switch from Forms authentication to HTTP authentication. For example, you might instruct MADAM that whenever anyone was attempting to access a particular resource, to switch to HTTP authentication. The MADAM HTTP Modules then detect when such a condition unfolds and intercept the HTTP response to include the necessary headers for the specified HTTP authentication scheme. Similarly, when the user agent responds with the user's credentials, the MADAM HTTP Modules work to validate the credentials against the configured credential store.

If you've ever needed to meld Forms authentication and HTTP authentication in a single web application using a single credential store, check out MADAM. You can learn more about it and download the complete source code at Supporting HTTP Authentication and Forms Authentication in a Single ASP.NET Web Site.

The Namespace and Class Names for Strongly Typed DataSets and TableAdapters
22 June 06 07:34 AM | Scott Mitchell | 1 comment(s)

In my multi-part tutorial series on Working with Data in ASP.NET 2.0, the tutorials are built upon an application architecture that uses a Typed DataSet as the Data Access Layer (DAL) and custom classes for the Business Logic Layer (BLL). In the first tutorial, the DAL is created, resulting in the following business objects:

  • Northwind - the strongly-typed DataSet that has the set of strongly-typed DataTables and the relationships among them
  • Northwind.ProductsDataTable - a strongly-typed DataTable that provides information about a set of products
  • Northwind.ProductsRow - a strongly-typed DataRow that provides information about a particular product instance; has properties like ProductID, ProductName, UnitPrice, and so on.

There are other business object classes that model the other tables in the database - Northwind.CategoriesDataTable, Northwind.CategoriesRow, and so on.

In addition to these business objects, the Typed DataSet includes TableAdapters, which provide the methods for populating these business objects with data from the database (as well as methods for inserting, updating, and deleting data). The TableAdapter classes automatically created by the Typed DataSet include one for each DataTable, and are found in the NorthwindTableAdapters namespace. These classes include:

  • ProductsTableAdapter
  • CategoriesTableAdapter
  • SuppliersTableAdapter
  • EmployeesTableAdapter

A question I've received from a number of folks who've read the tutorials is, “How do I change the names of these classes?” The names for the Typed DataSet, its DataTables and DataRows, and the TableAdpaters and their namespace are all determined by properties for these objects. By default, the name for the DataSet is the name of the DataSet file in your project. For the tutorial, I named the DataSet file Northwind.xsd, hence the Typed DataSet name is Northwind.

If you don't want to use the name of the DataSet file as the Typed DataSet name, you can change it by opening the DataSet in the Designer view, going to the Properties window, and changing the Name setting from Northwind (or whatever) to the name you desire. Imagine that you wanted to change the name to Scott, in an attempt to pump up my already overinflated ego. After doing so (and saving the DataSet file), the class names would change to:

  • Scott
  • Scott.ProductsDataTable
  • Scott.ProductsRow
  • ...

And the TableAdapters would all be in the ScottTableAdapters namespace. Similarly, to change the name of a DataTable or TableAdapter, click on the DataTable or TableAdapter in the DataSet Designer, go to the Properties window, and change the Name property. That's all there is to it!

Happy Programming!

Filed under:
More "Working with Data in ASP.NET 2.0" Tutorials Available!
19 June 06 12:01 PM | Scott Mitchell | with no comments

The next five tutorials in the “Working with Data in ASP.NET 2.0” series is available online. These five new tutorials make up the “Custom Formatting” section of the series, and include:

  • Custom Formatting Based Upon Data - Adjusting the format of the GridView, DetailsView, or FormView based upon the data bound to it can be accomplished in multiple ways. In this tutorial we'll look at how to accomplish data bound formatting through the use of the DataBound and RowDataBound event handlers.
  • Using TemplateFields in the GridView Control - To provide flexibility, the GridView offers the TemplateField, which renders using a template. A template can include a mix of static HTML, Web controls, and databinding syntax. In this tutorial we'll examine how to use the TemplateField to achieve a greater degree of customization with the GridView control.
  • Using TemplateFields in the DetailsView Control - The same TemplateFields capabilities available with the GridView are also available with the DetailsView control. In this tutorial we'll display one product at a time using a DetailsView containing TemplateFields.
  • Using the FormView's Templates - Unlike the DetailsView, the FormView is not composed of fields. Instead, the FormView is rendered using templates. In this tutorial we'll examine using the FormView control to present a less rigid display of data.
  • Displaying Summary Information in the GridView's Footer - Summary information is often displayed at the bottom of the report in a summary row. The GridView control can include a footer row into whose cells we can programmatically inject aggregate data. In this tutorial we'll see how to display aggregate data in this footer row.

As with the first 10 tutorials, the latest five include both C# and VB versions, can be downloaded as PDFs, and include the complete code download as a self-extracting ZIP file. Enjoy!

http://www.asp.net/Learn/DataAccess

Filed under:
SoCal Code Camp (San Diego) - THIS Saturday and Sunday (June 24th and 25th)
18 June 06 11:52 AM | Scott Mitchell | with no comments

For anyone in Southern California who is interested in attending a free, community-driven, two-day conference on .NET and other computing technologies, the SoCal CodeCamp will be coming to town this coming weekend - June 24 and 25. CodeCamps are free, developer-driven, code-rich events that occur over weekends to serve as a place for the local development community to share ideas.

To my knowledge, this is the first CodeCamp in San Diego (although there was one up in Fullerton back in January 2006). This CodeCamp will be held at the UC-San Diego Extension Complex, which is part of the beautiful UCSD Campus, just west of Hwy 5, about a mile north of the 52 Hwy (locations & directions). I'll be giving two talks on Saturday:

  • The Ins and Outs of ASP.NET 2.0 Site Navigation - Any website that is composed of more than one page needs some sort of navigation user interface. A navigation user interface might be as simple as static hyperlinks to the other pages in the site, or might involve the use of menus or trees. Prior to ASP.NET 2.0, developers typically rolled their own site navigation solutions. ASP.NET 2.0, however, makes defining a site's structure and implementing it using common navigation user interface elements a walk in the park. In this talk we'll look at ASP.NET 2.0's site navigation features, the navigation-related Web controls, and how to customize the site map provider piece of site navigation.
  • Let's Build a Weblog Engine Right Now - In this talk you'll see just how quick and easy it is to create a scalable, real-world data-driven application in ASP.NET 2.0. Starting from scratch, during the presentation we'll define our database structure, create a tiered application architecture, and build the ASP.NET web pages needed for a fully functional, working weblog engine that you can start using to host your blog. And all within the time limits of the session!

My talks are but two of dozens of talks canvasing a wide swath of technologies spanning a two-day event. You can check out the entire schedule as well as examine session abstracts. Finally, there's the ever-popular (and free!) Geek Dinner on Saturday night. There will be free food, live music, and (non-free) drinks. Plus it's at the Institute of the Americas buildings at the UCSD Campus, which if I recall correctly, has a stunning sunset view of the Pacific.

Hope to see you there!

Filed under:
Working with Data in ASP.NET 2.0
12 June 06 09:02 AM | Scott Mitchell | with no comments

About once a week I get an email from a reader of ASP.NET Data Web Controls Kick Start wondering if I'm going to be updating the book for ASP.NET 2.0. (For those unfamiliar with the book, Data Web Controls Kick Start is a 350+ page book focusing entirely on working with the DataGrid, DataList, and Repeater controls in ASP.NET 1.x; the An Extensive Examination of the DataGrid Web Control article series was the impetus for the book.)

My answer to them is, “Yes, I'm writing an update to this book, but one that's entirely online.” In particular, I've been working on a series of “Working with Data in ASP.NET 2.0” tutorials for Microsoft and am proud to announce that the first 10 of these tutorials are now available online!

The “Working with Data in ASP.NET 2.0” tutorials are modeled after the tutorial series started by Scott Guthrie and aim to provide step-by-step instructions (with lots of screen shots) on how to perform common data-related patterns. The first three tutorials constructs the architecture used by the other tutorials. The first tutorial, Create a Data Access Layer, shows how to create a DAL using Typed DataSets. The second tutorial looks at building a custom Business Logic Layer on top of that DAL, while the third implements the framework for the presentation layer, crafting the master page and site navigation for the tutorials website. The remaining seven tutorials provided currently show how to perform common data access scenarios using the architecture. The third tutorial looks at using the ObjectDataSource to access data from the BLL, while tutorials four and five look at using parameters with the ObjectDataSource. Tutorials six through ten focus on master/detail reporting scenarios.

There will be a total of 38 (or so) tutorials - I've currently turned in the first 28 to Microsoft and will be starting #30 this week. In addition to displaying data, future tutorials will look at editing, inserting, and deleting data, using optimistic concurrency, paging and sorting through data, and so on, and includes a multitude of examples using the GridView, DetailsView, FormView, DataList, and Repeater controls. All in all, these 38 (or so) tutorials, if printed, would likely consume around 250 pages of printed material.

What I like best about these tutorials is the way they're packaged up and presented, and my hat's off to the editors at Microsoft. My favorite “features” of this tutorial series, which differentiates it from much of the standard content on the MSDN website, are:

  • All tutorials include both a C# and VB version
  • Each tutorial can be downloaded as a printable PDF; also, you can download a single PDF that has the entire content for the first 10 tutorials
  • When downloading the code, it downloads as an extractable ZIP file and not an MSI file; furthermore, you can download the code on a tutorial-by-tutorial basis, or download the entire code for the first 10 tutorials
  • The HTML and source code presented inline in the article is color coded

As more tutorials from the series come online, I'll be sure to blog about them here...
http://www.asp.net/Learn/DataAccess/

Filed under:
July's Toolbox Column in MSDN Magazine
10 June 06 11:15 AM | Scott Mitchell | with no comments

My seventh Toolbox column in the July 2006 issue of MSDN Magazine is now available online. The July issue examines three products:

  • IP*Works! - a .NET framework that includes a bevy of classes for performing network-level operations. Make HTTP, FTP, SMTP, POP3, etc. requests from managed code; work with RSS feeds, make socket connections, and so on.
  • r.a.d. controls - build slick ASP.NET user interfaces using telerik's r.a.d. controls suite. Includes a host of AJAX-enabled controls that are easy to add to your website and can greatly improve the design and usability
  • Advanced Font Viewer - quickly examine what text looks like in a myriad of different fonts. Useful for comparing fonts in a side-by-side manner

I also reviewed Wei-Meng Lee's ASP.NET 2.0: A Developer's Notebook.

As always, if you have any suggestions for products or books to review for the Toolbox column, please send them into toolsmm@microsoft.com

You can keep abreast of the latest Toolbox articles through the column's RSS feed or the Toolbox column category here on my blog.

Filed under:
Login Control + CAPTCHA
06 June 06 03:31 PM | Scott Mitchell | with no comments

My latest installment (Part 5) of the Examining ASP.NET 2.0's Membership, Rols, and Profile article series shows how to extend the Login control to add additional Web controls to the interface and how to customize the authentication logic accordingly. In particular, the article includes a demo (among others) that shows how to add a CAPTCHA to the Login control. For that demo I'm using Jeff Atwood's free (and open-source) ASP.NET CAPTCHA server control.

In short, to accomplish this perform the following tasks:

  • Convert the Login control into a template. This can be done from the Designer by clicking on the “Convert to Template” option in the control's smart tag
  • Augment the Login control's template markup to include Jeff's CAPTCHA control (my example also requires that the user enter their email address on file)
  • Create an event handler for the Login control's Authenticate event. In there, verify the user's username and password via a call to Membership.ValidateUser(username, password). Assuming that that check passes, programmatically access the Email and CAPTCHA controls using LoginControlID.FindControl(“ID“) and verify the validity of those inputs. If the user has supplied valid inputs all around, set e.Authenticate to True; otherwise, if any check fails, set e.Authenticate to False.

That's all there is to it!

[Read the article...]

Filed under:
More Posts

Archives

My Books

  • Teach Yourself ASP.NET 4 in 24 Hours
  • Teach Yourself ASP.NET 3.5 in 24 Hours
  • Teach Yourself ASP.NET 2.0 in 24 Hours
  • ASP.NET Data Web Controls Kick Start
  • ASP.NET: Tips, Tutorials, and Code
  • Designing Active Server Pages
  • Teach Yourself Active Server Pages 3.0 in 21 Days

I am a Microsoft MVP for ASP.NET.

I am an ASPInsider.