DevelopMentor is Alive and Well

Amazing the speed at which false rumors can fly across the Internet. One such rumor was that DevelopMentor had ceased to exist. Nothing could be further from the truth. Check out Mark Blomsma’s post: Don’t Believe Everything You Read or Tweet.

Posted in Personal, Technical | Leave a comment

ASP.NET: Internet Explorer Cannot Display the Web Page

After installing a recent Windows Update, I was no longer able to run ASP.NET web apps using localhost. It seems the update removed an entry from my hosts file, located in C:\Windows\System32\drivers\etc, removing the entry that maps localhost to the loop-back IP address. The result was that pressing F5 or Ctrl-F5 to run an ASP.NET web app from Visual Studio 2008 resulted in a page in IE7 that said “Internet explorer cannot display the web page”. Interestingly, Firefox had no problem displaying the web page. To rectify the issue, I just had to open the hosts file and add the following entry:

127.0.0.1 localhost

After that IE7 displayed the web page property for localhost addresses.

Posted in Technical | Leave a comment

T4 POCO Templates for L2S and EF

In my MSDN Magazine article on SOA Data Access I recommend exposing Data Transfer Objects (DTOs) from the Data Access Layer (DAL). These objects should be Plain Old CLR Objects (POCOs) that are Persistent Ignorant (PI), eschewing traces of any particular persistence technology. (How’s that for an alphabet soup of acronyms?!) The point here is that the DAL truly encapsulates the API you’re using to fetch and update data, which makes it possible to swap out one data access stack for another without breaking the client.

Having said all that, what tools are available to automatically generate POCO entities from the database? The answer: None. Well, that’s not entirely accurate. There are plenty of code-generation tools out there, such as Code Smith. However, after searching for a few hours, I could not find any templates to generate POCOs. There were templates galore for various frameworks, such as n-tiers, NHibernate, CSLA, and PLINKO. But none of these simply generate POCOs.

This exercise in futility led me to check out T4, which stands for Text Template Transformation Toolkit. Simply stated, it’s a code-generation tool that’s built into Visual Studio! Scott Hanselman has a nice post on how to use it, and there are templates out there for generating various kinds of text files, especially C# and VB code files. There is also a T4 Editor by Clarion that provides intellisense and the like, as well as a Toolbox by Oleg Sych with some handy templates for common scenarios.

As was the case with Code Smith, I could not find any T4 templates to generate POCOs from a database. However, I did find a template by Damien Guard that serves as a wholesale replacement for LINQ to SQL entities. Using this template as a starting point, I ripped out the L2S-specific attributes for entities in order to generate persistence ignorant POCOs. There are two things that are really cool about this:

1. The T4 template uses as its “data source” the .dbml file created when you add a “LINQ to SQL Classes” item to your Visual Studio project. This means that you can drag specific tables and columns from a data connection in the Server Explorer onto the DBML design surface, and the T4 template will create POCOs matching what you’ve defined in the DBML file.

2. LINQ to SQL has the capability of using POCO’s instead of L2S entities. All you have to do is generate an XML mapping file using the SqlMetal command-line utility and feed it into the constructor when creating a strongly-typed DataContext. This completely eliminates the need for a separate set of DTOs!

A T4 template is just a text file with a .tt file extension that you can add to a Visual Studio project. For an L2S project, first add a new “LINQ to SQL Classes” item (which is a DBML file) and configure it, then add the “L2S-POCO.tt” T4 template and rename it to have the same name as the DBML file. Lastly, set the BuildAction of the DBML file to None, so that your app will use classes generated by the T4 template instead. That’s all there is to it!

After creating the T4 POCO template for LINQ to SQL, I thought I might as well go ahead and do one for the Entity Framework. Thankfully, Danny Simmons had already created a template to generate EF entities, so I used it as a starting point to generate POCOs for use with the Entity Framework. The main difference here is that EF cannot use POCO’s currently, so you will need both the EF-specific entities created by the EDMX file, as well as POCO’s created by the T4 template, which you can use as DTOs. This means that you will not change the BuildAction of the EDMX file.

You can download my T4 POCO templates and sample apps here. Enjoy.

Posted in Technical | 2 Comments

2008 Year in Review

sneeds_xmas_08

2008 was a great year for the Sneed family. We successfully transitioned back to America from an 18 month sabbatical in Slovakia and settled down in a suburb of Dallas, Texas, where we purchased a 5 bedroom house. Tony had a rewarding year professionally, in which he authored two courses for DevelopMentor, presented a session at the Microsoft TechEd conference, and published an article in MSDN Magazine. However, the biggest blessing by far was the arrival in late October of our daughter, Karisma.  We’ve recently posted our latest family photos.

In the early part of the year we enrolled in a parenting program, through which we met some friends here in the North Dallas area. In February Zuzana became pregnant, and we started making preparations for a larger family. In June we look at two week family vacation in Cancun, Mexico. Then in August, we attended a natural birth class.  Tony also started a weight-loss program and has since dropped about 20 pounds.

Later in the summer we started attending a church in a nearby town, where we made a few more friends. After Karisma’s birth we also became better acquainted with some of our neighbors. We’ve found the folks around here live up to the reputation of Texas as the Friendship State.

As rich as this past year has been, we are looking forward to even more blessings in the coming year. May you have a cheerful Christmas with friends and family, and may your 2009 be filled with joy.

Posted in Personal | Leave a comment

Bug in EF v.1 Limits N-Tier Scenarios

About a month ago I wrote a blog post on an extension method for the Entity Framework called AttachAsModified, which was offered by Danny Simmons shortly after PDC as a way to perform disconnected updates from an n-tier service. Unfortunately, I discovered what I consider to be a bug in EF v.1 that limits your ability to use the AttachAsModified extension method. The problem surfaces when the entity you’re trying to update has reference properties to related entities. For example, say you have an Order entity with a Customer navigation property that relates it to the Customer entity. If Order contained a CustomerID property representing the foreign key, you could simply set its value. But the EF models this as an association between Order and Customer and does not include CustomerID as a foreign key in the Order entity. (The EF team, nevertheless, is considering allowing foreign keys into the model.)

The way to set reference properties in EF is to set the EntityKey of the reference property to a new key based on the foreign key value you want to set it to. For example, if you want to change the Customer that an Order is associated with, you need to do the following:

updatedOrder.CustomerReference.EntityKey =
    new EntityKey("NorthwindEntities.CustomerSet",
    "CustomerID", newCustomerID);

The problem is that, when you call SaveChanges on the ObjectContext, EF includes the non-reference Customer property in the WHERE clause of the UPDATE statement.

exec sp_executesql
N'update [dbo].[Orders]
set [CustomerID] = @0,
[OrderDate] = @1,
-- other fields set to null
where (([CustomerID] is null and ([OrderID] = @2))
    and ([RowVersion] = @3))
N'@0 nchar(5),@1 datetime,@2 int,@3 binary(8)',
@0=N'ANATR',@1='1996-09-29 00:00:00:000',@2=10308,@3=0x000000000004BF3D

If you leave it null, or set it to anything other than the original value, this will result in an OptimisticConcurrencyException. This means you are required to pass in the Order’s original CustomerID value, which doesn’t make sense if you are using a timestamp column to manage concurrency (which is the purpose of the [RowVersion] in the above WHERE clause.

For this reason, I can’t bring myself to require the client app to retain original foreign key values, and I’m left having to re-query the database for the original entity, then set the timestamp property to that passed in with the updated entity. After detaching the entity to commit this change and mark it as ‘unmodified’, you can then modify the original entity properties to the values of the updated entity and call SaveChanges. While re-querying the database for the original entity isn’t pretty (and quite inefficient), I think it’s a better alternative to passing in the original values from the client (an approach advocated by MS architect Cesar de la Torre), because it won’t require code changes in the client when the EF team fixes the bug (hopefully before the release of v. 2!).

Here is a sample app that demonstrates the bug and also how to avoid it by re-querying the database. Cheers.

Posted in Technical | Leave a comment

Spend Baby, Spend

I just read a fascinating and illuminating article on the current financial crisis, as compared with the Great Depression: What Would Keynes Do? by Bruce Bartlett for Forbes Magazine. In the article the author asserts that the main problem with our economy is deflation, that is, falling prices. While most of us delight in lower gas and housing prices, after the recent run-up in these items, it’s deflation that can inflict the most damage to our economy, when the cost to the produce goods exceeds the sale price, leading to job layoffs.

The credit crunch has led to less money in the system, money people need to buy cars and houses, and to get student loans. The problem now is not simply the credit crisis, but fighting deflation. We have to catch it early, and the solution, according to the British economist John Maynard Keynes, is massive government spending on tangible items, resulting in decreased supply and higher prices, and giving a lot of people jobs, so they have the money to go out and buy stuff, which also helps prop up prices.

With the Federal Reserve doing all in its power to pump money into the system and be the lender of last resort, and with the swearing in of Barack Obama as the next president and a majority democratic congress to support him, I believe there is hope we can stave off another Great Depression. While this is difficult for me to admit, coming from a fiscally conservative background, I’m afraid it’s the only medicine that will cure the patient and prevent the economy from dying. I still belief in capitalism over socialism, but capitalism must be tempered to prevent unchecked greed from damaging it. The speculative bubbles in tech, housing and oil have all burst, bringing us to this point. We may now have to err on the side of socialism for a while to correct it, which is unfortunate, but I think it’s the only way to restore our capitalist system to its proper balance.

Posted in Personal | Leave a comment

Hot Off the Presses: SOA Data Access!

I wrote an article for the December issue of MSDN Magazine, which has just hit the streets:

image
The title is: Flexible Data Access With LINQ To SQL And The Entity Framework, and you can download the accompanying code here.

The purpose of the article is to provide a practical approach for developing real-world data-driven applications with either LINQ to SQL or the Entity Framework that use a layered, n-tier architecture. Developers currently face daunting challenges when it comes to developing these types of applications, even though it is these types of apps are the bread and butter of what most developers do on a day-to-day basis. The main challenge seems to be making the client application completely persistent ignorant by shielding it from any traces of persistence technology and using POCO objects that are not required to derive from a base class or implement a particular interface. My approach compromises on this principle somewhat by having DTO’s that implement an interface called ITrackable that has a single property containing change state. Nevertheless, this represents just a small bit of metadata attached to each DTO as it travels from the client to the service, where it is interpreted by a Data Access Layer and persisted to a data store.

The one requirement for my approach to work is that both client and service must agree on the data contract, which includes change state information, but this is par for the course for most service-oriented applications and plays well with non-Microsoft platforms. Another approach would be for a standards body of some sort to issue a universally accepted wire format for passing change-tracking data. Microsoft implemented diffgrams for this purpose some years ago using ADO.NET Datasets, but the standard never gained industry acceptance. What we really need is a new standard, then the problem of tracking changes on the client and persisting them on the service become manageable. This is the direction where I think the Entity Framework, which is considering n-tier design options, team need to be headed.

Posted in Technical | 15 Comments

VS 2010: It’s Time to Play

Are you ready to ride the next generation platform wave? Here are two links to get you started with Visual Studio 2010, .NET 4.0, C# 4, F#, the Parallel Computing Platform, and many other new technologies revealed at the Microsoft PDC conference last month. There are just three easy steps:

1. Go here to download a VPC with VS 2010 (be sure to use a tool like Free Download Manager):

Microsoft Pre-release Software Visual Studio 2010 and .NET Framework 4.0 Community Technology Preview (CTP)

2. Then go here to get the training kit, which includes presentations, demos and hands-on labs:

Visual Studio 2010 and .NET Framework 4.0 Training Kit – November Preview

3. Have fun!

Posted in Technical | Leave a comment

Better N-Tier Concurrency Management for the Entity Framework

I just wrote an article for MSDN Magazine (due out in December) about developing n-tier applications for both LINQ to SQL and the Entity Framework. While researching the topic, I noticed a certain awkwardness with the Entity Framework API when it came to managing concurrency with a timestamp fields, as compared with LINQ to SQL. L2S has an overloaded Attach method that accepts a bool asModified parameter indicating the presence of a timestamp field used for concurrency. The Entity Framework, on the other hand, requires attaching the original unmodified entity, then calling ApplyAllChanges, passing in the modified entity. This doesn’t make a whole lot of sense when using a timestamp for concurrency checking, because the only original value you care about is the timestamp, which is passed in unchanged as part of the modified entity. Using timestamps is a great idea because it relieves the client from needing to cache the object’s original values and reduces the amount of data sent over the wire when you’re sending entities to a service for persistence. In the article, I got around this by querying the database from the service using the key value of the modified entity. Yuck!

Before you throw up your hands in despair, I have good news for you. Danny Simmons, a developer and program manager on the EF team, just came up with a couple extension methods to obviate the need for original entity values. Rather than taking the original entity and applying property changes from a detached object that has been modified, you can simply take the detached object and set the state of each property to modified. What you’re essentially saying is, “Look, I already have a modified entity, just change the state of each property from ‘Unchanged’ to ‘Modified’ so that when I call SaveChanges the updates are persisted.”

There’s one more wrinkle to this scenario: using Data Transfer Objects (DTOs) instead of EF entities in the Data Access Layer (DAL). Although v.2 of the Entity Framework will allow you to use DTOs directly as EF entities, this is not yet fully supported in v.1, meaning that an UpdateOrder method would accept a DTO.Order object, which you would use to create an L2E.Order object. To accomplish this, I created an extension method for ObjectContext called CreateEntityFromObject which accepts a DTO and uses reflection to copy properties from the DTO to the Entity and create an EntityKey. The code to persist changes to an Order entity now looks like this:

static DTO.Order UpdateOrder(DTO.Order order)
{
    using (NorthwindEntities db = new NorthwindEntities())
    {
        // Create new order entity from DTO.Order
        Order updatedOrder = db.CreateEntityFromObject
            <Order>("OrderSet", order);

        // Attach modified order (with original timestamp)
        db.AttachAsModified(updatedOrder);

        try
        {
            db.SaveChanges();
        }
        catch (OptimisticConcurrencyException conflictEx)
        {
            Console.WriteLine(conflictEx.Message);
            return null;
        }
        return GetOrder(order.OrderID);
    }
}

Here is the CreateEntityFromObject extension method:

public static TEntity CreateEntityFromObject<TEntity>
    (this ObjectContext context,
    string entitySetName, object dto)
    where TEntity : IEntityWithKey, new()
{
    // Create a new entity
    TEntity entity = new TEntity();

    // Copy properties
    foreach (PropertyInfo dtoProp in dto.GetType().GetProperties())
    {
        PropertyInfo entityProp = typeof(TEntity).GetProperty(dtoProp.Name);
        object propValue = dtoProp.GetValue(dto, null);
        entityProp.SetValue(entity, propValue, null);
    }

    // Set the entity key
    entity.EntityKey = context.CreateEntityKey(entitySetName, entity);

    // Return the entity
    return entity;
}

To see all of this in action, you can download the code for my sample concurrency application. Enjoy!

Posted in Technical | 3 Comments

The Future of LINQ to SQL Looks Bleak

We now have a fairly clear message from Microsoft that LINQ to SQL will be deprecated in favor of the Entity Framework:

http://blogs.msdn.com/adonet/archive/2008/10/31/clarifying-the-message-on-l2s-futures.aspx

This is basically an admission that coming out with two competing relational data access technologies was not the best possible story, and that unifying data access on the Entity Framework will be better for everyone in the long run.

I like LINQ to SQL and am somewhat disappointed to see it go by the wayside, but Entity Framework has the advantage of being compatible with just about any back-end data store. And, although L2S offers a better developer experience in several areas (POCO support, concurrency management, disconnected scenarios, etc), it won’t be long before Entity Framework catches up.

Does this mean they’re going to rip out L2S from the .Net Framework? Of course not. There are many apps for which L2S is a great choice, but for apps that are going to be around for a while, EF is clearly the way to go. But these apps should also decouple themselves from the data access layer using a plug-in architecture, seeing that Microsoft is in the habit of changing their data access API’s from time to time. J

Posted in Technical | Leave a comment