November 2009

Volume 24 Number 11

Toolbox - Database Documentation, API for Pre- and Post-Conditions, Blogs and More

By Scott Mitchell | November 2009

One-Click Database Documentation

Over the course of my career I have seen a variety of techniques used for documenting the structure and purpose of a database. Most developers use Microsoft SQL Server’s Database Diagram tool to generate a pictorial representation, and then call it a day. While this is a good first step, it is rarely sufficient. For starters, sharing database diagrams with other stakeholders can be difficult at best. (I had one client e-mail me dozens of screenshots that, stitched together, comprised one large database diagram.) And such diagrams are often less than ideal for large databases; a diagram displaying hundreds of tables is difficult to read and understand.

While a database diagram is certainly useful, there are much better tools for documenting your database. One such tool is BI Documenter (version 3.0), a user-friendly application for auto-generating documentation for Microsoft SQL Server databases. To get started, launch BI Documenter and create a Solution file. The Solution file specifies the databases to document and maintains a history of snapshots. A snapshot is a description of the database’s structure at a particular point in time and is generated for you by BI Documenter. Over the lifespan of a project, a database’s schema usually changes, sometimes significantly—new tables get added, existing columns get modified or removed, indexes may be added or dropped. These snapshots ensure that the documentation you create today can be faithfully reproduced in the future. When generating the documentation, you can either create a new snapshot of the current database schema or you can regenerate the documentation from a previous snapshot.


BI Documenter

After selecting the database to document and creating the snapshot, all that remains is to configure the documentation options. BI Documenter can create a Compiled HTML Help file (.chm) or a series of HTML pages. There are settings to customize the colors used in the documentation as well as the ability to add a logo to each page. You can optionally select what database object types to document and which ones to omit. What’s more, BI Documenter includes a built-in database diagramming tool you can use to create and add database diagrams to the documentation. Plus, you can import your own Microsoft Word and image files.

The generated documentation includes a detailed list of the specified database objects, which includes users, roles, indexes, triggers, tables, and more. Viewing information about a particular table lists that table’s columns, triggers, indexes, constraints, dependencies, extended properties, and the SQL statements needed to create the table. The table’s columns, triggers, and other information are displayed as links that, when clicked, load a page with further details.

BI Documenter is available in three editions: Database, Enterprise, and Workgroup. The Database Edition can only document Microsoft SQL Server databases, while the Enterprise and Workgroup Editions can also document Analysis Services databases, Integration Services packages, and Reporting Services servers. The Database and Enterprise Editions enable a single user to create the documentation, while the Workgroup Edition allows multiple users to collaborate.

Price: $195 for the Database Edition, $395 for the Enterprise Edition, $495 for the Workgroup Edition
bidocumenter.com

Blogs of Note

I recently worked on a project that involved adding new functionality to an existing line-of-business Windows Presentation Foundation (WPF) application. During my time on that project I found Beth Massi’s blog to be an indispensible resource. Beth is a Program Manager for the Visual Studio Community Team at Microsoft. She has created numerous tips, tricks, videos, articles and tutorials on her blog and on Microsoft’s Channel 9 Web site (channel9.msdn.com) that explore topics like LINQ, Entity Framework, WPF, ADO.NET Data Services, and Microsoft Office development.

Most of Beth’s blog entries describe a specific programming scenario and then show how to solve it with lucid step-by-step instructions, numerous screen shots and code snippets, and links to blog posts and articles with more information. For example, the blog entry titled “Master-Detail Data Binding in WPF with Entity Framework” starts by walking the reader through creating the Entity Data Model. Beth then shows different ways to use LINQ to pull back the appropriate detail records. Other blog entries written in a similar style include “Using TableAdapters To Insert Related Data Into An MS Access Database” and “Tally Rows In A DataSet That Match A Condition,” among many others.

What makes Beth’s blog stand out is her passion for Visual Basic. All of Beth’s code examples are in VB and she frequently posts about upcoming language features, such as support for collection initializers in Visual Basic 10. She’s also interviewed several Microsoft MVPs who are using VB, asking them about the applications they’re building, their favorite language features, and so on. These interviews (and others like them) can be seen at Channel 9 (channel9.msdn.com/tags/MVP) and at the “I’m a VB” Web site, imavb.net.

blogs.msdn.com/bethmassi


Beth Massi's blog

A Fluent API for Pre- and Post-Conditions

When a method is called, it expects its environment to be in a certain state prior to its execution; it may also assume certain conditions hold once execution completes. These assumptions are called pre-conditions and post-conditions. Pre-conditions commonly apply to a method’s input parameters. For example, in the .NET Framework the File class’s ReadAllText method accepts the path of a file as input and returns the contents of the file as a string. The inputted file path cannot be a zero-length string, contain only white space characters, or include any invalid file-path characters; it cannot be null; and its length cannot exceed the system-defined maximum file-path length. If any of these preconditions are not met, the ReadAllText method throws an exception.

Pre- and post-conditions are typically implemented using a series of conditional statements as shown in Figure 1. CuttingEdge.Conditions (version 1.0), an open source project started by Steven van Deursen, provides a fluent interface for specifying pre- and post-conditions. (A fluent interface is an API design style that maximizes readability through the use of descriptive names and method chaining.)

Figure 1 Pre- and Post-Conditions Implemented Using Conditionals

public string ReadAllText(string path)
{
      // Pre-conditions...
      if (path == null)
            throw new ArgumentNullException(...);
      if (path.Length == 0)
            throw new ArgumentException(...);
      if (IsOnlyWhitespace(path) ||
            ContainsInvalidCharacters(path))
            throw new ArgumentException(...);
      if (path.Length >
            GetMaximumFilePathLength())
            throw new PathTooLongException(...);

      // Open file and read and return contents
            as string...
      object contents = GetFileContents(path);

      // Post-conditions
      if (!contents is string)
            throw
                  new InvalidFileTypeException(...);
      if (string.IsNullOrEmpty(
            (string) contents))
            throw new EmptyFileException(...);
}

To apply a pre-condition on an input parameter, property, or variable, use the Requires extension method; for post-conditions, use the Ensures extension method. Both methods return a Validator object, which has a host of methods available for applying rule checks, such as IsNotNull, IsNotEmpty, and IsEqualTo, among many others. Figure 2 shows the same method as Figure 1, but uses the CuttingEdge.Conditions API to implement the pre- and post-conditions.

Figure 2 Pre- and Post-Conditions Implemented Using CuttingEdge.Conditions

public string ReadAllText(string path)
{
      // Pre-conditions...
      path.Requires()
            .IsNotNull()
            .IsNotEmpty()
            .Evaluate(!IsOnlyWhitespace(path)) &&
                  !ContainsInvalidCharacters(path),
                  "path contains whitespace only or
      invalid characters")
            .Evaluate(p => p.Length <=
                  GetMaximumFilePathLength());

      // Open file and read and return contents
      // as string...
      object contents = GetFileContents(path);

      // Post-conditions
      contents.Ensures()
            .IsOfType(typeof(string))
            .IsNotNull()
            .IsNotEmpty();
}

Each Validator method call—IsNotNull, IsNotEmpty, and so on—throws an exception if the condition is not met. For example, if path is null, the IsNotNull method call will throw an ArgumentNullException.  And you can optionally provide a string to use as the exception’s message.

Sometimes a pre- or post-condition cannot be expressed using one of the Validator class’s built-in methods. In such cases you have two options. You can either create an extension method on the Validator class or you can use the Evaluate method, which lets you specify a Boolean or lambda expression to evaluate. If the expression returns true,  processing continues; if it returns false, an exception is thrown. Figure 2 illustrates using both forms of the Evaluate method in the pre-conditions section.

Price: Free, open source
conditions.codeplex.com

The Bookshelf

ASP.NET MVC is a relatively new framework added to the ASP.NET stack that enables developers to create Web applications using a Model-View-Controller (MVC) pattern. It differs from the traditional Web Forms development model in many ways. For starters, ASP.NET MVC affords much more control over the rendered markup and provides a more distinct separation of concerns. Web pages are accessed using terse, SEO-friendly URLs. And the MVC architecture allows for better testability. For a more in-depth look at the differences between ASP.NET MVC and Web Forms, refer to Dino Esposito’s article in the July 2009 issue (msdn.microsoft.com/magazine/dd942833.aspx).

Getting started with ASP.NET MVC involves a bit of a learning curve, even for experienced ASP.NET developers, because of the numerous differences between the two frameworks. For example, when creating an ASP.NET MVC application in Visual Studio, you are prompted to create a unit test project. With ASP.NET MVC, you design your Web pages using HTML along with a few helper classes—there are no Web controls to drag and drop onto the page. And unlike Web Forms, there are no baked-in postback or Web control event models. In short, there are a lot of new techniques to learn when moving from Web Forms to ASP.NET MVC.

If you are an intermediate to experienced ASP.NET developer who wants to learn ASP.NET MVC, check out Stephen Walther’s latest book, “ASP.NET MVC Framework Unleashed” (Sams, 2009). Walther does an excellent job introducing new concepts and showing how they’re used—without overwhelming the reader with an avalanche of information.


ASP.NET MVC Framework Unleashed

The book starts with a short overview of ASP.NET MVC—the motivation behind the new framework, its design goals, and benefits. The next 500 pages walk the reader through the key aspects of ASP.NET MVC, one at a time. First, the reader learns how to create a new ASP.NET MVC application in Visual Studio, how to add a database, how models, views and controllers are added to the project, and so forth. The next 100 pages explore models, views and controllers in detail. Each concept is clearly described and is accompanied by screenshots and code samples in both C# and Visual Basic. Later chapters look at the HTML helpers available; explore techniques for validating form data; and dissect ASP.NET MVC’s URL routing feature. There are also chapters on authentication, AJAX, jQuery and deployment.

After examining the core pieces of ASP.NET MVC, in separate chapters, in detail, and with the aid of several simple exercises, the book finishes with an end-to-end example of building a real-world ASP.NET MVC Web application. This final project, spread over 150 pages, cements the concepts explored in the earlier chapters and highlights many of the benefits of the ASP.NET MVC framework.

Price: $49.99
samspublishing.com


Scott Mitchell*,* author of numerous books and founder of 4GuysFromRolla.com, is an MVP who has been working with Microsoft Web technologies since 1998. Mitchell is an independent consultant, trainer and writer. Reach him at Mitchell@4guysfromrolla.com or via his blog at ScottOnWriting.net.