Skip to content

D2009 Generics and Type Constraints

The .NET type system is rooted at System.Object. The Delphi/Win32 type system isn’t rooted (built-in simple types, records, and classes don’t have a common ancestor), and primitive types can’t/don’t implement interfaces, so someone in the newsgroups asked how to deal with generics which must perform operations on primitive types, without the use of IComparable, et. al. Here’s one way. I’m not sure if it’s the best way, but it works.

unit Unit5;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TAdder<T> = class
  public
    function AddEm(A, B: T): T; virtual; abstract;
  end;

  TIntAdder = class(TAdder<integer>)
  public
    function AddEm(A, B: integer): integer; override;
  end;

  TStringAdder = class(TAdder<string>)
  public
    function AddEm(A, B: string): string; override;
  end;

  TMath<T; A: TAdder<T>, constructor> = class
  public
     function AddTwoDigits(Left, Right: T): T;
  end;

  TForm5 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  end;

var
  Form5: TForm5;

implementation

{$R *.dfm}

procedure TForm5.Button1Click(Sender: TObject);
var
  AddInt: TMath<integer, TIntAdder>;
  AddString: TMath<string, TStringAdder>;
begin
  AddInt := TMath<integer, TIntAdder>.Create;
  try
    ShowMessage(IntToStr(AddInt.AddTwoDigits(2, 2)));
  finally
    AddInt.Free;
  end;
  AddString := TMath<string, TStringAdder>.Create;
  try
    ShowMessage(AddString.AddTwoDigits(’2′, ‘2′));
  finally
    AddString.Free;
  end;
end;

{ TIntAdder }

function TIntAdder.AddEm(A, B: integer): integer;
begin
  Result := A + B;
end;

{ TStringAdder }

function TStringAdder.AddEm(A, B: string): string;
begin
  Result := IntToStr(StrToInt(A) + StrToInt(B));
end;

{ TMath<T, A> }

function TMath<T, A>.AddTwoDigits(Left, Right: T): T;
var
  Add: A;
begin
  Add := A.Create;
  try
    Result := Add.AddEm(Left, Right);
  finally
    Add.Free;
  end;
end;

end.

An Enumeration of Prime Numbers with Anonymous Methods

In this post, I am going to demonstrate a programming technique which cannot be done without anonymous methods (or lambda expressions).  I’ll throw in some generics for fun. First, though, I need to describe the problem I’m solving.

I want to solve problem three of Project Euler. Project Euler is a web site which poses a series of programming problems intended to teach you mathematical concepts.  Here is problem three:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

In order to compute prime factors, it helps to have a method to return a list of primes.  A very simple algorithm to do this is called the Sieve of Eratosthenes. If you don’t already know this algorithm well enough to implement it yourself, then please read the Wikipedia article I just linked before continuing.  The rest of this post will make very little sense unless you understand the Sieve.

I’m going to make a minor change to the algorithm described in the article. In that version, you begin by "writing a list of numbers from 2 to the largest number, say n, you want to test for primality." That won’t work for me, since I don’t know the largest number I need to test for primality.  I could guess, but I might be wrong, and, in any event, it seems inelegant.

So I’m going to take a different approach.  Whenever I have a need for a sequence of something, say, prime numbers, I think of enumerations.  It’s common to see enumerations over a fixed list, like strings in a TStringList, but they work just as well for infinite lists.  So I’m going to write an enumerator which returns prime numbers in ascending order.

The basic outline of the algorithm is this:

  1. Start with the lowest prime number.
  2. Increment the current prime number.
  3. Test it with a function which returns false if any of the previous prime numbers are factors of the number tested, true otherwise.
  4. Repeat steps 2 and 3 until a new prime is found.

Obviously, the heart of the algorithm is the function in step 3. To solve this problem without anonymous methods, I would need to maintain a list of the primes returned previously, and test each one in sequence.  That would work fine, but I am going to demonstrate a different approach.

Since I happen to know that 2 is prime, I’m going to start with a function which returns true.  So in step 1 I’ll begin with 1, not a prime number, but the "uninitialized" start of the enumeration.  Note that the value 1 will never be returned by the enumeration. In step 2, I’ll increment it to 2.  In step 3, I’ll test it with my function, which, at this point, returns the constant true.  So far, so good, since 2 is prime.

Now I need to change the function to one which excludes products of 2, the first returned prime.  That way, when we get to 4, it will be rejected by the function. In order to do this, I’m going to dynamically create a new function and substitute it for the original function which always returned true.

OK, enough chat.  Let’s look at some code.  First, here is the interface for the enumerator:

  TPrimeNumberEnumerator = class
  private
    FCurrent: integer;
    FIsPrime: TPredicate<integer>;
    function MakeFilter(CurrentPredicate: TPredicate<integer>; CurrentPrime: integer): TPredicate<integer>;
  public
    constructor Create;
    function GetCurrent: Integer;
    function MoveNext: boolean;
    procedure Reset;
    property Current: integer read GetCurrent;
  end;

The public portion of the interface is just an implementation of the enumerator pattern in Delphi, plus the constructor, which simply calls Reset.  FCurrent will hold the last prime number returned, or 1 if no primes have been returned yet. FIsPrime is a reference to a function which returns false if any of the previously returned returned primes are even factors of the integer argument passed, and true otherwise.  TPredicate<integer> means a function which returns a Boolean with a single, integer argument. GetCurrent just returns FCurrent. First, let’s look at Reset, which gets everything ready.

procedure TPrimeNumberEnumerator.Reset;
begin
  FCurrent := 1;
  FIsPrime := function(AValue: integer): boolean
  begin
    Result := True;
  end;
end;

FCurrent is initialized to the value below the first value returned, as with many enumerator implementations. FIsPrime, at this point, ignores its argument, and simply returns true.  I used an anonymous function here for consistency with the rest of the code, but a non-anonymous function could have been used in this part. Again, since I know that 3 is prime, this trivial function is good enough for this specific case, although we’ll need something better soon!

The heart of the enumerator is in MoveNext and MakeFilter. Here’s MoveNext:

function TPrimeNumberEnumerator.MoveNext: boolean;
begin
  Inc(FCurrent);
  while not FIsPrime(FCurrent) do Inc(FCurrent);
  FIsPrime := MakeFilter(FIsPrime, FCurrent);
  Result := true;
end;

That’s just the algorithm I described above.  Increment FCurrent, then test this value for primality.  Keep incrementing until we find a new prime. Return True, since there’s always another prime.

Importantly, however, when a prime is found I modify the predicate FIsPrime in such a way that it excludes products of this prime.  That’s the Sieve of Eratosthenes. Let’s look at how this is done:

function TPrimeNumberEnumerator.MakeFilter(
  CurrentPredicate: TPredicate<integer>;
  CurrentPrime: integer): TPredicate<integer>;
begin
  Result := function(AValue: integer): boolean
  begin
    Result := CurrentPredicate(AValue) and ((AValue mod CurrentPrime) <> 0);
  end;
end;

MakeFilter takes the function it was passed plus a new prime number and returns a new function, which returns false if the passed function, CurrentPredicate, returns false or the integer argument, AValue, can be evenly divided by the prime number passed to MakeFilter.  The new function returns true, otherwise. Note that the function is "capturing" both the original function, CurrentPredicate, and CurrentPrime, both of which are arguments to MakeFilter, but not to the function returned.

Since I always pass FIsPrime as the CurrentPredicate argument, each time I call MakeFilter I’m enhancing FIsPrime to exclude more non-prime numbers.

In effect, I’m creating a new function which has only one argument, AValue, but incorporates two additional arguments, CurrentPredicate and CurrentPrime.  The difference is that CurrentPredicate and CurrentPrime are captured from the creating method and hence fixed at the time the function is created, whereas AValue will be specified at the time the function is executed.  This is a technique called currying, and it’s quite common in functional programming.  You cannot do currying in the general sense without anonymous methods or lambda expressions.  So this is a new programming technique available in Delphi 2009.

Having done all this, I need to be able to get an instance of my enumerator:

  TPrimes = class
  public
    function GetEnumerator: TPrimeNumberEnumerator;
  end;

And now I can solve the original problem:

procedure TForm4.btnGoClick(Sender: TObject);
var
  Current: integer;
  Primes: TPrimes;
  Composite: Int64;
begin
  Composite := 600851475143;
  lboResults.Items.Clear;
  Primes := TPrimes.Create;
  try
    for Current in Primes do begin
      if Composite mod Current = 0 then begin
        Composite := Composite div Current;
        lboResults.Items.Add(IntToStr(Current));
        if Composite = 1 then break;
      end;
    end;
  finally
    Primes.Free;
  end;
end;

FullTrust on the LocalIntranet

I had missed this before, but with .NET Framework 3.5 SP 1, Microsoft has changed the default permission for LocalInternet to FullTrust. It can do this because .NET 3.5 SP1 also installs .NET 2.0 SP2 and .NET 3.0 SP2. This should effectively end the headache that many Delphi for.NET developers experienced when referencing (instead of statically linking) the VCL for .NET assemblies, where users could run an application locally, but would see a permission here if they copied the same application, with the VCL for .NET assemblies, to a network share.  So if your users are experiencing this problem, getting the 3.5 SP 1 Framework, available from Windows Update, should fix it.

Generics: Not Just for Lists

It appears that the next version of Delphi, code-named Tiburón, will include support for generic types in the Win32 compiler.  Developers without .NET experience may not be familiar with use cases for generics.  Of course, generics work really well for typed containers, and this is often the first example that people give as a use case.  But they have many other uses as well.  I’ll give a few examples; I hope this will help Delphi developers think about how they might want to use the feature in their own code.

Nullable<T>

It’s common to have a reference in code to a value read in from a database.  Of course, most databases allow NULL, whereas many scalar types, like integer, do not. So a programmer can either choose to designate a certain scalar value as a "NULL flag," which can cause problems when that value is actually stored in the database, or to have a separate, Boolean reference indicating whether the other variable should, in fact, be treated as NULL.  Neither solution is great. A better way is to build a single structure which stores both the NULL flag and the scalar value.  This is a more elegant way of storing the value retrieved from the database, but it gets tedious and hard to maintain when you have to create such a structure for many different types.  Using a generic Nullable<T>, however, you can use a single type which can store a reference to any value, whether scalar or not.

Mocks

Generics work really well for mock classes used in unit testing.  Briefly, a mock is an object which appears to be of a certain type, but is, in fact, just an imitation of that type.  You use a mock in a unit test when including the actual object would make the unit test dependent on things which are not practical or advisable to include in a unit test, like a web service.  The mock can pretend to be the web service and return data without actually making an Internet connection.

Mocking is one of those things which is really simple to implement for one specific case, and fairly hard to implement for a general case.  You can fairly easily create a mock for one specific type.  It’s quite a bit harder to create a mocking framework which can imitate any type. But generics help a lot.

In my unit tests for my ASP.NET MVC web applications, I need to mock the HttpContext, since the version included with the .NET framework polls and a whole bunch of stuff related to web applications which I don’t need for the unit test.  So I use the Moq framework and a mocked context which I posted earlier.  In general, to create a mock of a certain type using Moq, you write:

var mockobject = new Mock<TypeToMock>();

After some additional code to specify what values the methods and properties of the "fake" TypeToMock should return, I can then supply the mocked object to some other instance which expects a "real" instance of TypeToMock, and it will be none the wiser:

testInstance.TypeToMockProperty = mockobject.Object;

Now, a full explanation of how to use the Moq framework is outside of the scope of this post; you can read a brief tutorial at the Moq site if you’re interested.  But the important point is that mockobject.Object appears to the outside world to be an instance of TypeToMock, even though it isn’t, and doesn’t carry any of the baggage that the "real" TypeToMock might have.

MVC

Another area where I’ve found generics to be really helpful is when passing a model to a view in an ASP.NET MVC web application.  MVC View pages have a property called ViewData.Model which returns a model instance that was passed by the controller.  By default, this is of type System.Object, which means that you have to cast it to do anything useful with it.  But by using generics, you can get rid of the casts.  Let’s say that the model I want to supply to the view is of type MyModel.  I changed the view declaration from this:

public partial class MyView : ViewPage

…to this:

public partial class MyView : ViewPage<MyModel>

ViewPage<MyModel> is a different type than ViewPage (without the generic type parameter).  MyView is now subclassing a different parent type. In particular, the property ViewData.Model of ViewPage<MyModel> will be of type MyModel instead of type System.Object.  This means that in the code for my View, I can access properties of my model type directly, without any casts, like this:

editLink.HRef = ViewData.Model.EditUrl;

Note that this is not some kind of disguised cast. With a cast, you either sacrifice performance (with a safe/soft cast) or type safety (with an unsafe/hard cast).  With a generic, you don’t make either sacrifice.  Type checking is performed at compile time, just like with a property of a non-generic type.

So When Should I Use Generics?

There are some "code smells" which indicate that you should consider using a generic type.  Whenever you find yourself writing similar code over and over again just to change one or two types (e.g., the type-safe lists that most of us have built in Delphi), or whenever you find yourself casting a reference regularly to the same type, you might want to consider using a generic type instead.

Understanding Anonymous Methods

It appears that the next version of Delphi will support a feature called anonymous methods.  The circumstances in which one might use an anonymous method do not seem to be obvious to everyone in the Delphi community, so I’m going to attempt to answer that.

There is, at the moment, no shipping version of Delphi which includes anonymous methods, so I’m basing my discussion on my experiences using them in other environments.  The final, released version may include a different feature set and what I describe below.

First, let’s answer the obvious question, with the obvious answer: What can I do with an anonymous method which I can’t do without an anonymous method?  Nothing.  In fact, there’s nothing which you can do with Delphi which you cannot do with ASM.  Anonymous methods are a convenience suited to certain styles of programming, like strong, static typing, and object orientation.  They will probably seem useless to people who do not adopt those styles of programming, just as virtual methods will seem useless or dangerous to a non-OO programmer.

I suspect that most "Pascal programmers" view procedures as being a fundamentally different type than other data structures.  In the static typing the world, we typically define the shape of a data structure at compile time, and the contents at runtime.  By contrast, even when passing a procedure as an argument to another procedure, in older versions of Delphi we have had to define both the shape and the contents of the procedure at compile time.  Only the arguments can be set at runtime.

With one exception: Nested procedures.  Let’s talk about that, for a moment.

Nested procedures, scope, and variable capture

Nested procedures are procedures declared inside of another procedure.  This essentially reduces the scope of the nested procedure to being callable within the nesting procedure only: Here is a simple example.

procedure MyClass.Foo;
var
  i: integer;
  procedure Bar;
  begin
    Inc(i);
  end;
begin
  i := 1;
  Bar;
  WriteLn(IntToStr(i));
  Bar;
  WriteLn(IntToStr(i));
end;

procedure MyClass.Other;
begin
  Bar; // compiler error
end;

The output of calling Foo will be the following lines, written to the console:

2
3

There are two things to note here. First, note that Bar can "see" the variable i, which is declared as a member of Foo.  Outside of the Delphi community, this feature is often called variable capture, although for some reason that term doesn’t seem to be common within the Delphi community.  But that’s what it is.  Second, note that the scope of Bar is limited to the Foo procedure.  That’s nice, from a modularity point of view, but it’s absolutely critical when combined with variable capture.  Outside of the scope of Foo, the variable i has no context/value.

Even the inside of the Foo procedure, however, you cannot assign Bar to an event property or any other procedure reference.  The way that variable capture is handled internally makes this impossible, without some hacking.

Now, one might reasonably ask what the value of that variable capture feature is.  After all, in the example above, I could just as easily have passed i to Bar as a var argument, and the result would have been the same, albeit at the expense of a bit more typing.  Indeed, in the case of nested procs, variable capture is really little more than a labor saving device.

Anonymous methods

Returning to anonymous methods, let’s start with the definition.  An anonymous method, as the phrase implies, is a method without a name.  In addition to being nameless, anonymous methods, in most environments, include some form of variable capture.

According to the Delphi roadmap, anonymous methods will be assignable to procedure references.  You can see an example of this on Andreano Lanusse’s blog.

The combination of assignability and variable capture is quite powerful, because it effectively means that I can change the signature of the procedure reference type in the definition of the anonymous method.  That is, I can pass values which are not included in the arguments declared in the procedure reference declaration.  That’s unnecessary and perhaps even confusing if I’ve written the "reference to procedure" declaration myself.  In this case, I should just include the necessary arguments.  If, however, the declaration was written by someone else — say, the author of a framework — it’s incredibly convenient, as I can now pass values which the framework author hasn’t included on my behalf.

In the past, I’ve had to use some fairly ugly kludges to get around this limitation, such as declaring a new class field to hold some value which I only wanted to use inside of an event handler whose signature I did not control.  With variable capture, these kludges are unnecessary.

This returns us to the issue of "programming worldview" to which I alluded at the beginning of this post.  To a programmer unaccustomed to thinking of functions as values, with functions living in one little container, and data structures living in another little container, this may all seem a bit odd.  But if you consider a function as a bit of data, defining both behaviors and passed values, it’s not so strange.  Of course we can define data at runtime, just like we’ve always done.

Alternate View Folders in ASP.NET MVC

Stephen Walther recently posted a tip on how to load an ASP.NET MVC View from a folder other than Views\{controller}\ or Shared. He notes that it’s possible to hardcode the path to a View in your Controller action.  He also states that you should not do this:

Now, I want to be the first to warn you that you should never, never, never use this tip (Please delete this entry from your news aggregator immediately). There is a good reason for following the conventions inherent in an MVC application. Placing your files in known locations makes it easier for everyone to understand your application.

Now, if the only types of Views that you have an application are views which directly correspond to a single controller or widely shared items like master pages, he’s right.  With more complicated architectures, you may need other choices, and the MVC framework has an extensibility point built-in for this. To the extent that Stephen’s point was that it’s never appropriate to hardcode a path inside a controller, however, I completely agree with that. But there may be legitimate reasons to probe other paths, and it’s also interesting to look at why the framework looks in these specific places in the first place.

I have, I think, a fairly good reason for wanting the MVC framework to probe other folders when looking for a View.  I’ll explain that at the bottom of the post, but first, here’s the technique. I want to thank Jens Hofmann for pointing this out.  His needs are slightly different than mine — he wants the framework to always probe different folders, rather than adding one more folder to the list of folders probed — but his post (in German) pointed me in the right direction to solve the problem. In contrast to Jens’s tip, I’m going to subclass the default controller and extend its list of paths, rather than replacing it altogether.

The ASP.NET MVC framework uses a class called a ViewLocator to find view files.  The default ViewLocator is a subclass called WebFormViewLocator. This by itself suggests one reason why you might want to replace the ViewLocator; if you’re developing an alternate markup language, your views will probably have different template file extensions than a WebForm view, so an alternate ViewLocator will be needed.

What I did was to subclass WebFormViewLocator and add my custom path to the list of paths probed, like this:

public class EntityViewLocator : WebFormViewLocator
{
    public EntityViewLocator()
    {
        ViewLocationFormats = ViewLocationFormats.Union(EntityViewFormats).ToArray();
    }
    private static string[] EntityViewFormats = new[] { "~/Views/Entities/{0}.aspx",
                                                        "~/Views/Entities/{0}.ascx" };
}

The class is public for unit testing convenience. Update: Cleaned up code 1 August 2008.

Now you need to assign the ViewLocator to the Controller.  One way to do this is in the Controller itself.  But I already had a ControllerFactory, so I did it there.

So why do I bother with this?  Why not just use the standard folders?

In one of the applications I’m developing now, the great majority of Controllers and Views are dynamically generated to correspond to a type from an Entity Framework model.  I have a very large number of "controllers," but most of them don’t actually exist as types or source files.  Instead, a single, generic controller can "pretend" to be a specific controller for a specific entity type. Most entity types share completely dynamic views, with no special knowledge of specific controller/entity types, but a few have entirely custom views, which are tightly bound to certain controllers.  Structurally, it makes sense to group these "entity views," as well as their field templates, together, rather than dumping them in with master pages, or creating a folder to correspond to a "controller name" which doesn’t actually exist, since a single controller is used for most entity types.

InterBase 2009 Partner DVD

I am once again organizing vendor participation for the InterBase Partner DVD.  If your company produces a tool, application, component set, etc. which explicitly supports InterBase, the Partner DVD is one of the best ways to ensure that your software is available to anyone who purchases InterBase.  You can include a full version, a trial, or just information about your product; whatever is appropriate for your needs.

As always, participation in the Partner DVD program is free.  The only real requirement is that your software has to explicitly support InterBase. If you would like to have your product on the Partner DVD and are not already participating, please send an e-mail to craig underscore stuntz at acm org

The ADO.NET Entity Framework vs. NHibernate and Other ORMs

In the past couple of weeks, I’ve had occasion to look fairly closely at the ADO.NET Entity Framework, and compare it to NHibernate.  Of course, before I even started, I went out and read what other people had to say on the subject.  Many people point to this post by Danny Simmons as approximating the "official" Microsoft position on the subject, and commenters around the web seem to focus specifically on what Danny calls "a [not yet delivered, but] much larger vision of an entity-aware data platform."  That’s interesting, but there are differences which exist today which are perhaps even more interesting. As Danny points out, "The EF was specifically structured to separate the process of mapping queries/shaping results from building objects and tracking changes. "

The Entity Framework goes to fairly extreme measures to ensure that the bidirectional mappings between the store (database, usually) and the client entity model are correct, provably, when possible. You can read about that in great detail in this paper, but one very visible implication of it to the developer is that in the Entity Framework, you supply separate metadata descriptions for the store and the object model, plus a third description to bridge the two.  Contrast that with a Hibernate mapping, which rolls all three together into one description. Erik Meijer and José Blakely elaborate on this point in an interview with ACM Queue’s Terry Coatta:

 TC:  You mentioned object-relational mappers.  A certain portion of our audience has worked with products such as Hibernate or NHibernate and other commercial ORM systems.  One of the existing characteristics of LINQ and the Entity Framework is that they divide traditional ORM into two pieces: one part handling mapping and one part handling querying.  Is that a correct view and why is this separation reasonable?

JB:  Several OR mappers bundle these two concerns together, and that actually makes sense when the only problem you’re trying to solve is how to bridge the gap between the application and the database.

But we should also look at another very broad class of mapping scenarios.  We are building database management systems and data services around SQL Server— data services such as replication, reporting services, and OLAP.  These all provide services at higher semantic levels of abstraction than does the relational model.

[…]

Thus, when we look at the impedance mismatch both of applications and data services, we realized that for the data-services case, you don’t want objects with methods and behaviors.  What you want is a value-based, richer structural data model.

By value-based, I mean the ability to have a high-level constructs such as entities and relationships but without the behaviors.  Just as the relational model is a value-based model, we felt that we needed to provide a layer of abstraction that is richer in terms of entities and relationships.  Therefore, the Entity Data Model and the Entity Framework became a natural layer of abstraction that we felt had to be built, and it’s at that level of abstraction where the mapping between richer-level entities and semantic concepts such as inheritance is abstracted.

Now the Entity Data Model, which is the formalism that defines the Entity Framework value-based layer, is very close to the object data model of .NET, modulo the behaviors.  We decided to let the Entity Framework take care of all the mapping concerns and then just build than programming-language veneers, or wrappers, over entities to expose a variety of programming-language bindings over this infrastructure.

EM:  I would like to point out that there’s a deep analogy with how I explained LINQ in the beginning.  We are trying to extract not one particular case where you go from tables to objects, but rather a wide variety of different things for different uses.  So instead of having a one-often thing, we are trying to generalize this concept so that there are many other situations in which is applicable.

Ironically, one of the places where this distinction is most visible is when attempting to use the Entity Framework designer in the current .NET 3.5 / Visual Studio 2008 Service Pack 1 Beta.  I say "attempting" because, at this point, if you do any serious work with the Entity Framework, you’re almost certain to be editing the EDMX file (which is XML) by hand.  It’s very easy, at the moment, to make the designer create EDMX which is either not a valid or not parsable by the designer. Part of this is, no doubt, because the Entity Framework is quite a bit more mature than its designer.  The Entity Framework has its roots in WinFS and Microsoft Research, while the Visual Studio designer appears to be a more recent addition to "productize" the Entity Framework.  Presumably, the more glaring bugs in the designer will be fixed before release.

But part of me wonders if the instability in the designer is due not only to its relative immaturity, but also to the fact that it tries to present a single face for a mapping which is fundamentally a three-part system.  Indeed, there seems to have been a drive from the "Entity Framework tools team" to roll these three parts into one. The designer shows (graphically) you only the conceptual model, for the most part.  Some parts of the storage model filter through here and there, and the mapping can be seen when you click on an individual element. The paper I referenced earlier shows you the three parts in a graphical form, but the Entity Framework designer shows you only a piece of this, mostly the OO side of things.

One of the mental barriers that you have to get over when designing a good object relational mapping is the tendency to think primarily in object oriented terms, or relational terms, whichever suits your personality.  A good object relational mapping, though, incorporates both a good object model and a good relational model. For example, let’s say you have a database with a table for People, and related tables for Employees and Customers.  A single person might have a record in all three tables.  Now, from a strictly relational point of view, you could construct a database VIEW for employees and another one for customers, both of which incorporate information from the People table.  When using a one VIEW or the other, you can temporarily think of an individual person as "just" an Employee or "just" a Customer, even though you know that they are both. So someone coming from this worldview might be tempted to do an OO mapping where Employee and Customer are both (direct) subclasses of Person.  But this doesn’t work with the data we have; since a single person has both employee and customer records (and since no Person instance can be of the concrete subtype Employee and Customer simultaneously), the OO relationship between Person and Employee needs to be composition rather than inheritance, and similarly for Person and Customer.

So would be Entity Framework designer be better if it graphically showed you all three facets of your mapping? It’s hard to say.  Our model appears complicated enough in just the OO view, even though it represents less than 100 database tables, which is significantly smaller than the schema for our production applications.  Attempting to add the storage metadata and the mapping to that diagram would be putting more lines on a drawing which already threatens to make the term "spaghetti code" literal.

At the same time, though, certain operations really beg for an explicit representation of the storage metadata, the OO model, and the mapping between them, especially when configuring relationships and inheritance.  The latter, in particular, we have found difficult to do in the visual designer without corrupting the EDMX.

Perhaps more importantly, though, it may be true that the "simplification" of the designer is part of the reason that people have to ask what the differences between the Entity Framework and NHibernate in the first place.  If you just look at the XML files for both systems, the difference stands out a lot more.

Moq and MvcMockHelpers

I’m working on some unit tests for an ASP.NET MVC application I’m developing.  One of the tests ensures that if I construct a URL using Html.ActionLink that the URL which is returned, when fed into the routing system, becomes a correct representation of the route data used to build the URL originally.  I’ll discuss this further in a future post, but today I’m going to talk about Moq. Unfortunately, this type of testing requires more mocking than you’d really prefer, despite the significant improvements in unit-testability in recent previews of the ASP.NET MVC framework.

I started with the MvcMockHelpers library released by Scott Haselman.  It does quite a bit of what I need, so that saved me a lot of work.  Scott’s library supports three different mocking frameworks; of these, I chose Moq.

My tests hit some areas of the HttpContext which Scott’s mock didn’t implement, so I set out to extend it.  One bit, HttpContextBase.ApplyAppPathModifier, was a bit more challenging to mock, despite the fact that the result I needed was quite simple: The mocked function should simply return its only argument.  The Moq demos don’t cover this case, although it is a supported feature in the 2.0 version. After a little digging around through the forums and the change logs, I figured out how to do it:

response.Expect(res => res.ApplyAppPathModifier(It.IsAny<string>()))
    .Returns((string virtualPath) => virtualPath);

There are two parts to this.  First, you specify that this mock will match a call to ApplyAppPathModifier with any string argument.  That is the It.IsAny bit.  Inside the Returns call is a lambda expression which specifies how to turn a string argument into a result.  In this case, the expression is very simple.

So, for anyone who wants it, here is my current implementation of the FakeHttpContext() method.  It returns a mocked HttpContext which is good enough for the unit testing I’m doing at the moment.

        public static HttpContextBase FakeHttpContext()
        {
            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();
            var user = new Mock<IPrincipal>();
            var identity = new Mock<IIdentity>();

            request.Expect(req => req.ApplicationPath).Returns("~/");
            request.Expect(req => req.AppRelativeCurrentExecutionFilePath).Returns("~/");
            request.Expect(req => req.PathInfo).Returns(string.Empty);
            response.Expect(res => res.ApplyAppPathModifier(It.IsAny<string>()))
                .Returns((string virtualPath) => virtualPath);
            user.Expect(usr => usr.Identity).Returns(identity.Object);
            identity.ExpectGet(ident => ident.IsAuthenticated).Returns(true);

            context.Expect(ctx => ctx.Request).Returns(request.Object);
            context.Expect(ctx => ctx.Response).Returns(response.Object);
            context.Expect(ctx => ctx.Session).Returns(session.Object);
            context.Expect(ctx => ctx.Server).Returns(server.Object);
            context.Expect(ctx => ctx.User).Returns(user.Object);

            return context.Object;
        }

JAWS, XP Themes, and Accessibility

It seems that the popular screen reader (software which translates text on the computer screen into spoken audio for the blind) JAWS has problems with applications produced in Delphi when they are manifested for Windows XP.  I don’t know if the problem is limited only to Delphi applications, though.  What I do know is that we tested the latest version of JAWS with a do-nothing application which simply displays a single, standard, text edit control, and a standard label which specifies the text editor as its FocusControl.  When we produce the application without an XP manifest, JAWS reads the caption correctly when the editor is focused.  When we add an XP manifest, JAWS no longer reads the caption.

So if accessibility for the blind is important for your software, it would probably be a good idea to download the free demo version of JAWS and test your software.  If it doesn’t work, try making the manifest optional.

One would think that the makers of JAWS would want software producers to test their products with JAWS.  But according to a salesperson for Freedom Scientific, there is no developer program for the tool.  JAWS is moderately expensive — about $900 — but this is not a barrier for us.  What we would really like is to have access to a defect reporting system for JAWS and early access to future versions of the software.

Update:  Darrell Shandrow, from the Blind Access Journal, comments on this post.

Close