July 29, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Create Quick Database Interfaces with ASP.NET Dynamic Data

  • June 8, 2009
  • By Jani Järvinen
  • Send Email »
  • More Articles »

Validating database values

While creating simple database editing user interfaces with ASP.NET Dynamic Data is a snap, creating business rules to regulate data entry is nonetheless part of almost any application. If possible, the best practice is to start this process from the database level: you should enforce required fields in SQL Server, for instance. Similarly, if you know that a field can only have values from 0 to 100, you might add a constraint directly to the field using the CHECK keyword or the Check Constraints dialog box in SQL Server Management Studio.

In ASP.NET Dynamic Data applications, certain database level constraints are automatically enforced. For example, required fields (NOT NULL) automatically generate a validation error at runtime if left blank. However, more complex constraints not reflected by the model (such as CHECK constraints) will generate a generic error saying that the update wasn't successful. To give the user of the application a clearer indication of what's missing, you can again use attributes.

For instance, the Range attribute (defined in the System.ComponentModel.DataAnnotations namespace) can be used to specify minimum and maximum values for either an integer or floating point field. This attribute is applied similarly to the ScaffoldColumn and UIHint attributes.

Other attributes that you can use to check values include the Required and RegularExpression attributes. It is also possible to limit string lengths using the StringLength attribute. If you instead prefer to write custom validation code yourself, then you can write a method to extend the data model you have. For instance, if you are using ADO.NET Entities, then the NorthwindModel.Designer.cs file will have partial method declarations for validating fields.

For example, if you had a business rule saying that employee hire date must be a Monday, then you could write code to implement the OnHireDateChanging method of the Employees class. You could do this with code similar to the following:

  public partial class Employees
  {
    partial void OnHireDateChanging(System.DateTime? value)
    {
      if (value.HasValue)
      {
        if (value.Value.DayOfWeek != DayOfWeek.Monday)
        {
          throw new Exception(
            "The hire date must be a Monday");
        }
      }
    }
  }

However, the problem with this approach is that the OnChanging event is executed many times: when viewing records, when editing them, and finally when saving them. This means that the actual database values must match the rules - if they don't, then the data cannot be shown.

If you instead would like to validate values only when changes are saved back to the database, then you would need to write a bit more code. The entity data model class (NorthwindEntities in the example application) contains an event called SavingChanges which you can handle. You should write your validation rule(s) into this event handler.

  using System.Data;
  using System.Data.Objects;
  ...
  public partial class NorthwindEntities
  {
    partial void OnContextCreated()
    {
      this.SavingChanges
        += new EventHandler(MyHandlerForSavingChanges);
    }
  
    internal void MyHandlerForSavingChanges(
    object sender, EventArgs e)
    {
      IEnumerable<ObjectStateEntry> changedEntities =
        this.ObjectStateManager.
        GetObjectStateEntries(EntityState.Added |
        EntityState.Modified);
      foreach (ObjectStateEntry entry in changedEntities)
      {
        if (entry.Entity is Employees)
        {
          Employees emp = (Employees)entry.Entity;
          if (emp.HireDate.HasValue)
          {
            if (!(emp.HireDate.Value.DayOfWeek ==
              DayOfWeek.Monday))
            {
              throw new Exception(
                "The hire date must be a Monday");
            }
          }
        }
      }
    }
  }

Here, the code first implements the OnContextCreated partial method and then adds an event handler for the SavingChanges event. The event handler itself (in MyHandlerForSavingChanges) collects all the added or modified records from the data model, and then loops thru them to see which are related to the Employees table. Once a match is found, the value of the HireDate field is checked, and if not a Monday, an exception is raised.

Writing custom validation code is not difficult, but often you can avoid this as the attributes provided by ASP.NET Dynamic Data already are quite versatile. If they don't meet your needs however, you can write custom rules using the two techniques shown previously.

Conclusion

In this article, you have seen how ASP.NET Dynamic Data can be used to write functional web front-ends to databases in no time. Without doing almost any customizations, ASP.NET Dynamic Data allows you to create web interfaces that are suitable at least for administrative purposes. With some additional development, you can create effective applications that appeal to a wide range of users. However, ASP.NET Dynamic Data applications might not directly suit all your needs. In these cases, it is helpful to know that you can easily integrate an ASP.NET Dynamic Data application into (an existing) regular ASP.NET WebForms application. You can even enable in-place editing of data using the grids if you comment and uncomment about ten lines of code in Global.asax.cs file. Follow the instructions inside the file itself.

Because ASP.NET Dynamic Data applications are user- interface-wise based on a master page and CSS styles, the applications you write can also be quickly modified to have the necessary look and feel. In the future, these customizations will be even easier. CodePlex already contains a public preview of a forthcoming version, and ASP.NET Dynamic Data will also be a native part of .NET Framework 4.0. Given this, ASP.NET Dynamic Data has a bright future. The technology is already useful, and especially so if you need to write quick interfaces for your databases. And many of us do.

Links

Official ASP.NET Dynamic Data page
Microsoft Visual Studio 2008 Service Pack 1 download page
Using ASP.NET Dynamic Data on MSDN
ASP.NET Dynamic Data 4.0 Preview 4

About the Author

Jani Järvinen is a software development trainer and consultant in Finland. He is a Microsoft C# MVP and a frequent author and has published three books about software development. He is the group leader of a Finnish software development expert group at ITpro.fi and a board member of the Finnish Visual Studio Team System User Group. His blog can be found at http://www.saunalahti.fi/janij/. You can send him mail by clicking on his name at the top of the article.





Page 4 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel