October 2006 - Posts

More Tutorials on Working with the DataList... and More Tutorials in the Pipeline!
31 October 06 12:53 PM | Scott Mitchell

Eight new tutorials have been added to my Working with Data in ASP.NET 2.0 series. This latest batch of tutorials examines how to edit and delete data from the DataList control. These tutorials follow, in scope, the concepts discussed in the earlier edit/insert/delete-related tutorials that focused on the GridView, DetailsView, and FormView controls. These DataList-specific tutorials, however, do include a look at performing batch updates (a topic lacking from the GridView/DetailsView/FormView-specific ones). As always, each tutorial is available in both VB and C#, includes the full working code as a downloadable ZIP, and can be downloaded as a PDF for offline access.

When I started writing these tutorials I was slated to write 46 in total, and, to date, 43 of the 46 are up at http://www.asp.net/Learn/DataAccess/. (They are also being added to MSDN's website, but at a much more glacial pace.) Anywho, the good news is that I've signed on to author another 29 tutorials over the coming months, which will continue the series and be available at http://www.asp.net/Learn/DataAccess/ as they come online.

Here is the planned outline. The content to be covered is pretty much solidified, but there may be some slight modifications, reordering of sections/tutorials, and so forth. I've actually completed the “set” of tutorials on the SqlDataSource (the first four), and will start hammering out the next set this week, time permitting.

  1. Accessing Database Data Directly from an ASP.NET Page
    1. Querying Data with the SqlDataSource Control
    2. Using Parameterized Queries with the SqlDataSource
    3. Inserting, Updating, and Deleting Data with the SqlDataSource Control
    4. Implementing Optimistic Concurrency with the SqlDataSource
  2. Enhancing the GridView
    1. Adding a GridView Column of Radio Buttons
    2. Adding a GridView Column of CheckBoxes
    3. Inserting a New Record from the GridView’s Footer
  3. Working with Batched Data
    1. Batch Updating
    2. Batch Deleting
    3. Generating Multiple Details Records Which Copy Multiple Columns of Data From a Common Master
  4. Working With Binary Files
    1. Uploading Files
    2. Including a File Upload Option When Adding a New Record
    3. Displaying File Information in the Data Web Controls
    4. Changing the Uploaded File for an Existing Record
  5. Caching
    1. Caching Data with the ObjectDataSource
    2. Caching Data at the Business Logic Layer
    3. Using SQL Cache Dependencies
    4. Caching Data at Application Startup
  6. Data and the Site Map Provider
    1. Building a Custom Database-Driven Site Map Provider
  7. Advanced Data Access Layer Scenarios
    1. Having the Typed DataSet Create Your Stored Procedures
    2. Integrating Existing Stored Procedures with the TableAdapter
    3. Techniques for Performing JOINs
    4. Adding Additional DataTable Columns
    5. Working with Computed Columns
    6. Configuring Connection- and Command-Level Settings in the DAL
    7. Wrapping Database Modifications in a Transaction
    8. Debugging Stored Procedures
    9. Protecting connection strings
    10. Creating SQL Functions and Stored Procedures with Managed Code
Filed under:
Three New Data Tutorials on Using Master/Detail Filtering with the DataList and Repeater Controls!
17 October 06 11:11 AM | Scott Mitchell

Three new tutorials have just been added to the Working with Data in ASP.NET 2.0 series. These three focus on master/detail filtering with the DatList and Repeater controls. As always, the tutorials are available in both C# and VB, can be downloaded as PDFs, and whose source code is packaged up into a simple ZIP file (rather than an MSI).

Enjoy!

Filed under:
Novermber's Toolbox Online - and Now in Multiple Languages!
13 October 06 08:50 AM | Scott Mitchell

My eleventh Toolbox column in the November 2006 issue of MSDN Magazine is now avaiable online. The November issue examines three products:

  • BeyondCompare - a top-notch product for comparing and syncing text files, locally or remotely (through FTP, for example).
  • Camtasia - many software vendors' websites these days include interactive, Flash-based demos showing their product in action. This can be used both as a selling point and for technical help (a more interactive knowledgebase). Camtasia is a program designed to capture screen interactions, optionally lay over voice or various video edits, and export the resulting creation to any of a variety of formats.
  • FCKEditor - a free, open-source rich textbox for ASP.NET.

This month's issue reviewed Len Fenster's book Effective Use of Microsoft Enterprise Library. The Enterprise Library is a set of free, open-source application blocks released by Microsoft that perform a variety of standard tasks - data access, configuration, caching, exception handling, and so on. Len's book looks at the utility of the Enterprise Library, how it can fit into your organization's applications, and how to create your own custom application blocks that fir the same pattern. From the review:

The book is composed of nine content-packed chapters and three appendices, with each application block thoroughly explored in its own chapter. Each chapter begins with an examination of the application block's purpose, followed by a look at its class structure. The author then walks through how to configure an application to use the application block; numerous source code samples illustrate how to work with the application block from code. The book is a must read for those who are using the Enterprise Library or are in the midst of evaluating it.

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

ALSO! Brand new!! You can now read MSDN Magazine online in one of (currently) seven languages: English, German, Spanish, French, Portuguese, Russian, or Chinese! From the homepage you'll find a drop-down list in the upper right corner from where you can select your language preference.

So you can now read Toolbox in Spanish (or French, or Russian, or...)!!

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:
Specifying Authorization Rules for the Business Logic or Data Access Layers (BLL/DAL)
04 October 06 04:43 PM | Scott Mitchell

In my Limiting Data Modification Functionality Based on the User (C# version) tutorial, I show how to adjust the functionality at the presentation layer based on the “currently logged on user.” (The demo doesn't actually setup the membership and roles systems, and rather allows the visitor to pick who they are logged on as from a drop-down list. See my Examining ASP.NET 2.0's Membership, Roles, and Profile article series for more information.)

One question I have received more than a couple of times is how to extend the permission-based business rules down into the Business Logic Layer and/or Data Access Layer. That is, how can I configure my BLL so that if my presentation layer has a bug or whatever, a person who is not authorized to, say, delete a record, is forbidden from doing so.

There are a couple of ways. One way is to add the logic programmatically to your BLL or DAL. You can access information about the currently logged in user in these layers using the Membership or Roles classes in the .NET Framework, like so:

1 public bool AddProduct(...)

2 {

3 if (!Roles.IsUserInRole("Administrator"))

4 throw new System.Security.SecurityException("You do not have permission to add a new product to the system.");

5

6 ...

Alternatively, you can specify authorization rules using PrinciplePermissionAttributes, as discussed by Scott Guthrie in his blog entry Adding Authorization Rules to Business and Data Layers using PrincipalPermissionAttributes.

With Scott Guthrie's approach, your BLL or DAL's code would include attributes defining the permissions required.

using System;
using System.Security.Permissions
;

[PrincipalPermission(SecurityAction.Demand, Authenticated = true
)]
public class
EmployeeManager
{
[PrincipalPermission(SecurityAction.Demand, Role
= "Manager"
)]
public Employee LookupEmployee(int
employeeID)
{
// todo
}

[PrincipalPermission(SecurityAction.Demand, Role
= "HR"
)]
public void
AddEmployee(Employee e)
{
// todo
}
}

The benefits of PrincipalPermissionAttribute, as noted by Scott, are:

“The PrincipalPermissionAttribute isn't tied to any specific authentication mode. It will work with Forms Authentication, Windows Authentication, Passport Authentication, or any custom authentication mode you want to invent. It will also work with any Role implementation I might use (so if you build or plug-in your own Role Provider in ASP.NET it will just work).

“The PrincipalPermissionAttribute type is implemented in the standard CLR mscorlib assembly that all .NET projects compile against. So it isn't ASP.NET specific, and can be used within any application type (including Windows and Console applications). In addition to making it more generically useful, this makes it easier to unit-test business/data libraries built with it.”

Filed under:
WARNING: Concurrency Issue with ASP.NET 2.0 GridViews/DetailsView/FormViews that Support Editing and/or Deleting and Whose View State is Disabled
03 October 06 12:56 PM | Scott Mitchell

WARNING: There is a potentially severe concurrency issue with ASP.NET 2.0 GridViews, DetailsView, or FormViews that support editing and/or deleting and whose view state is disabled....

In the Editing, Inserting, and Deleting Data tutorials of my Working with Data in ASP.NET 2.0 tutorial series, I demonstrate how the GridView, DetailsView, and FormView can all support the built-in editing, deleting, and inserting capabilities with view state disabled. The reason is because the key data Web control properties (such as the DataKeys collection), are stored in control state, which is always persisted to view state regardless of the control's EnableViewState property value.

In my tutorials I don't mention the view state issue, I just silently set the EnableViewState property to false. And this works wonderfully when testing the page. Deletes and edits work exactly as expected, with or without view state enabled. However, a rather insidious behavior can rear its head when there are multiple users visiting the same page. This potential trap was pointed out to me by alert reader Jamie Crutchley, whose observed and shared information about this problem on the ASP.NET Forums in the past. I'll explain the problem (and a potential workaround) in my own words, but you can read Jamie's posts here and here, if you'd rather.

PROBLEM: Two users - Alice and Bob - visit a page (Products.aspx) that uses a GridView whose to list products; the GridView's view state has been disabled. The GridView uses its DataKeys collection to store the primary key values of the three products. Imagine that the products listed are Pens, Books, and Paper, and their respective primary key values are 1, 2, and 3.

  1. Alice clicks on the Delete button for the first product in the grid (Pens).
  2. A postback occurs. Because the GridView's view state has been disabled, on postback the data is re-read from the GridView's data source. This has the side effect of repopulating the DataKeys collection with the newly read data!
  3. Since the first row index was clicked, the GridView grabs the DataKeys value indexed at 0 and issues a delete based on that primary key value (1).
  4. Bob still sees all three products on the page (since he loaded the page before Alice deleted Pens). Sometime after Alice has made her deletion, Bob, too, decides that Pens must be deleted. He clicks on the Delete button for Pens.
  5. A postback occurs. Because the GridView's view state has been disabled, on postback the data is re-read from the GridView's data source. This has the side effect of repopulating the DataKeys collection with the newly read data!
  6. Since the first row index was clicked, the GridView grabs the DataKeys value indexed at 0. However, since the DataKeys collection has been reloaded in Step 5, the first DataKeys value is the primary key of Books (since Pens has since been deleted). The consequence is that Books is deleted, even though Bob wanted to delete Pens!!

More generally, if Alice deletes any product whose index preceeds the index of the record Bob deletes, Bob's delete will actually delete a different record. Similarly, if Alice deletes a preceeding record of the one Bob is editing, the edits will be applied to a preceeding row. Eep.

SHORT AND SIMPLE SOLUTION: Unless you are absolutely, 100%, certifiably, unconditionally certain that there will never, ever, not in a million years be two users concurrently editing/deleting records, then be sure to leave the GridView / DetailsView / FormView's EnableViewState property to True (the default).

MORE INVOLVED SOLUTION: If you really would like to reduce the page size by disabling view state, you can use the following “hack”... When a Delete (or Edit) button is clicked in the GridView the RowCommand event fires before the DataKeys collection is internally repopulated. Therefore, you can create an event handler that includes code that “saves” the DataKeys value(s) for the record being deleted. Then, in the ObjectDataSource's Deleting event handler you can reassign this value back to the primary key parameter(s).

Here's some code to implement this approach. First, in the RowCommand event handler the primary key (ProductID) is saved in a page-level variable:

1 int recordToDelete = -1;

2 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

3 {

4 recordToDelete = Convert.ToInt32(GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);

5 }

Then, in the ObjectDataSource's Deleting event, assign the page-level variable to the appropriate parameter:

1 protected void ObjectDataSource1_Deleting(object sender, ObjectDataSourceMethodEventArgs e)

2 {

3 if (recordToDelete > 0)

4 e.InputParameters["ProductID"] = recordToDelete;

5 }

The tutorials and code at Working with Data in ASP.NET 2.0 will be updated so that they no longer disable view state and will include a similar warning as to this blog entry, although due to the breadth of material online, it may take several days or weeks to get all the changes made and propagated...

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.