February 2009

Volume 24 Number 02

Toolbox - The Active Record Pattern, Aspect-Oriented Programming

By Scott Mitchell | February 2009

All prices confirmed on December 29, 2008, and are subject to change. The opinions expressed in this column are solely those of the author and do not necessarily reflect the opinions at Microsoft.

Contents

Implement the Active Record Pattern in Your .NET Application
Aspect-Oriented Programming in the .NET Framework

Implement the Active Record Pattern in Your .NET Application

The active record pattern is commonly used in data-driven applications to model a database table or view in terms of a class, where a row of the database table is modeled by an instance of the class. In this pattern, the class's properties map to the corresponding database table's columns.

The class's instance methods perform operations on a database record, whereas its static methods work with the whole table. For example, if the database contained a table named Employee with columns EmployeeId as a uniqueidentifier, Name as an nvarchar(50), and Salary as a money, to implement the active record pattern you'd create a class named Employee with properties named EmployeeId, Name, and Salary. The Employee class would include instance methods such as Create, Save, and Delete, and might include static methods such as DeleteAll, Find, and FindAll.

Figure 1shows the active record pattern. It offers a simple, intuitive syntax for working with data and is the pattern used by many object-relational mappers (O/RM).

Figure 1 Active Record Pattern in Action

// Add Andrew Fuller as a new employee Employee emp = new Employee(); emp.Name = "Andrew Fuller"; emp.Salary = 50000.00M; emp.Create(); // Give a 10% raise to all employees Employee[] allEmployees = Employee.FindAll(); foreach (Employee current in allEmployees) { current.Salary *= 1.10M; current.Save(); }

The Castle ActiveRecord(version 1.0, RC3) project offers a quick and easy way to implement the active record pattern for Microsoft .NET Framework-based apps. It's built on top of NHibernate, which is a free, open-source O/RM tool and was reviewed in the October 2006 Toolbox column.

One of the drawbacks of NHibernate is that it has a bit of a steep learning curve and requires the developer to create and maintain the XML mapping files that tie together the database tables, columns, and relationships with the classes and properties in the app. The ActiveRecord project API encapsulates much of this complexity by using .NET attributes and makes implementing the active record pattern easy.

To get started, download the installation package from the project's home page. This installs the ActiveRecord and NHibernate assemblies and makes them visible to Visual Studio; add these assemblies to your project. Next, create the classes in your app that will use the active record pattern to model a database table.

This is the code for the Employee class referenced in Figure 1:

[ActiveRecord] public class Employee : ActiveRecordBase<Employee> { [PrimaryKey] public Guid EmployeeId { get; set; } [Property] public string Name { get; set; } [Property] public decimal Salary { get; set; } }

Note that the Employee class extends the ActiveRecordBase class and uses attributes to flag which properties map to columns in the database table and which column serves as the primary key. The ActiveRecordBase class defines instance methods such as Create and Save and static methods including Find, FindAll, and DeleteAll.

You can provide more detail about each member in the Employee class by passing in parameters through the PrimaryKey and Property attributes, including the length of the string columns, whether the column requires unique values, if the column can be assigned a database NULL value, and whether to ignore the column when inserting or updating a class instance.

Along with creating the Employee class, you also need to define a few configuration settings, such as the database connection string and a handful of NHibernate-specific options. But there's no need to write any data-access code. That's handled for you automatically by the ActiveRecord project and NHibernate. In fact, you don't even need to have created the database tables at this point, as the ActiveRecord project can auto generate the tables for you based on the classes you've created.

The attribute syntax of the ActiveRecord project is also used to establish relationships among classes. For example, the HasMany and BelongsTo attributes can be used in a parent and child class, respectively, to indicate a one-to-many relationship. Imagine that the data model was expanded to include a Department table with columns DepartmentId and Name, and a DepartmentId column in the Employee table establishing a one-to-many relationship between departments and employees. This relationship would be modeled in the application by adding a Department class and updating the Employee class to include a new property (see Figure 2).

Figure 2 Adding Employee Class

[ActiveRecord] public class Department : ActiveRecordBase<Department> { [PrimaryKey] public int DepartmentId { get; set; } [Property] public string Name { get; set; } [HasMany(typeof(Employee))] public IList Employees { get; set; } } [ActiveRecord] public class Employee : ActiveRecordBase<Employee> { ... [BelongsTo("DepartmentId")] public Department Department { get; set; } }

Notice that the Department class has an Employees property, which returns the set of Employee objects for a specific Department instance. Similarly, the Employee object has a Department property that returns information about the department to which the employee belongs.

The ActiveRecord project makes it easy to get started building your application's architecture on top of a proven framework, NHibernate. Within a few minutes you can craft classes that use the active record pattern without having to master NHibernate's XML configuration syntax.

**Price:**Free, open-source.

castleproject.org/activerecord

Aspect-Oriented Programming in the .NET Framework

Separation of concerns is a central tenet of software engineering that encourages separating an application's features and functionality into non-overlapping modules. Each programming paradigm has its own techniques for encouraging this. Procedural programming languages allow developers to encapsulate functionality in subroutines; object-oriented programming languages use classes.

Security, logging, and caching are all examples of concerns that typically apply to multiple modules and, when implemented, result in code scattered across those modules to which the rules apply. These types of concerns are said to be cross cutting and are referred to as aspects.

Aspect-oriented programming (AOP) is a programming paradigm that focuses on handling the separation of cross-cutting concerns. AOP allows developers to create aspects in a single module and then specify when these run—prior to the execution of a method, when a method completes with success, and so on.

For example, with AOP a developer could build an aspect that runs prior to a method's execution and verifies that the user belongs to a particular role and then specifies to what methods the aspect applies. As a result, whenever one of these specified methods is about to be executed during run time, the corresponding aspect code executes first. AOP is typically implemented through code weaving, which involves injecting the aspect code into the appropriate spots in the application code—either at the end of compile time or during run time.

Check out PostSharp(version 1.5), a free, open-source library created by Gael Fraiteur that you can use to implement AOP techniques in the .NET Framework. At its core, PostSharp analyzes and transforms .NET assemblies, allowing for the code weaving necessary to implement AOP.

Built atop this core is PostSharp Laos, a lightweight aspect-oriented system that enables developers to create and use aspects in terms of custom attributes. The aspects can then be applied to classes or methods by decorating them with the custom attribute. Alternatively, aspects can be applied to all classes or methods that have a certain naming pattern through syntax in the project's AssemblyInfo file.

Figure 3shows an example of a PostSharp aspect for error notification. This aspect extends the OnExceptionAspect, which means that the aspect can execute in response to an unhandled exception, perhaps e-mailing an administrator details of the exception. This aspect can be applied to a particular method by decorating it with the OnException attribute, as shown here:

[OnException("admin@contoso.com")] private void MyMethod() { // ... }

Figure 3 A PostSharp Aspect for Error Notification

public class OnExceptionAttribute : OnExceptionAspect { public string ToAddress { get; set; } public OnExceptionAttribute(string to) { ToAddress = to; } public override void OnException(MethodExecutionEventArgs e) { // TODO: Send ToAddress an e-mail detailing the exception details. // Exception details available in the MethodExecutionEventArgs object } }

Immediately after the code has been compiled, PostSharp modifies the IL code of MyMethod, surrounding the existing code with a try...catch with a call to the OnException method within the catch block. As a result, the OnException aspect is invoked whenever there is an unhandled exception in MyMethod.

You'll find extensive documentation at the PostSharp Web site, along with a helpful message board. There are also community-created plug-ins, libraries, and other tools that use or extend PostSharp.

**Price:**Free, open-source.

postsharp.net/

Send your questions and comments to toolsmm@microsoft.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. Scott is an independent consultant, trainer, and writer. Reach him at Mitchell@4guysfromrolla.comor via his blog at ScottOnWriting.NET.