July 2010 Entries

I recently had to introduce a DTO pattern on a project. The application was split between a server side and a desktop side using http based WCF to handle the communication.

The project had been working well passing NHibernate entities back and forth, but there was too much data being transferred.

So we introduced the DTO pattern. I added a GetDto method to the base class for the Entities. I added a GetEntity to the base class for the DTOs. We created DTO objects for the entities that we wanted to switch over.

We spent a little bit of time debugging and working out the nuances in the GetDto and GetEntity methods. Everything was working fine. We modified the service classes and proxies to expect the DTO instead of the Entity. Everything is looking fine.

Now we try to pass data back and forth …

"The connection was closed unexpectedly"

 

We start debugging. We can step into the code on the desktop side. Everything looks fine. We step into the code on the server side. Everything looks fine. We finish the method on the server side, and we are slapped in the face with "The connection was closed unexpectedly".

I search all over the place for possible causes. I blame WCF configuration. I blame the alignment of the stars. I blame the weather. I blame the driver who cut me off in traffic.

Stubbornly, I refuse to blame the DTOs. This is a simple pattern. I have used it before to solve this very problem. Surely they cannot be the problem.

I switch back to passing Entities. The closing connection problem goes away. This lets everyone off the hook. Except for that driver. I will find a way to blame him yet.

So it has to be a problem with the DTO. I am stumped…

I go back to looking at the Entity and comparing it to the DTO. Both have the DataContract attribute. Both have DataMember attributes for every property. They do not appear to be any meaningful differences I explicitly call serialize on the DTO. It serializes without a problem.

I am still stumped. On a lark, we decide to try changing the base class of the DTO to match the base class of the Entity.

This is when we discover that EntityBase has a DataContract attribute, and DTOBase does not. We make the change.

The clouds part. The angels sing! Amazingly problem solved!

This should not have caused the problem. The error message should have been much better and definitely point us in a good direction, but what a relief that we figured it out.

Hopefully this will save someone else some trouble shooting time.

Now what can I blame on that driver …

 

 

I have spoken in the past about the burden that keeping documentation up to date. This can be quiet a cumbersome burden.

At the same time, we clearly need some documentation and are often required to provide more documentation than is absolutely needed.

With all this in mind, I have been thinking about ways to design code to lessen the amount of documentation that has to be written and maintained.

 

Turns out, there are many cases where such design changes improves the quality of code, lowers the maintenance costs, and allows us to potentially generate more documentation.

On several projects that I am working on, we end up following a DTO pattern for transferring data from the app side to the presentation side. One of the annoyances is keeping track of the relationship between Entity, DTO, and Repository. The names will vary across implementations, but you will often have a one to one relationship between an Entity and a Data Transfer Object. Both of these may be served from a Repository responsible for interacting with the database.

I have started relying on Generic parameter to explicitly state this relationship in code. We can then use reflection to pull out these relationships and help build out the documentation.

Consider the following class declaration for an Entity:

 

public abstract class EntityBase<TDto, TRepository, TEntity>: IEntity<TDto>

where TRepository : RepositoryBase<TEntity >, new()

where TDto : DtoRootBase

where TEntity : class, IRotEntity

 

 

The IEntity interface needs to know the DTO to require strongly typed methods for GetDto, etc. The Repository needs to know the Entity to be able to provide strongly typed signatures for methods such as Get and Save. By specifying the Repository, we now have all the details needed to implement a Save method in the base class as well as wire up constructors that will retrieve object details from the database.

 

The method signature for declaring classes is complicated somewhat but not overly. Consider the following class declaration:

 

 

public class MemberEntity : BaseEntity<MemberDto , MemberRepository , MemberEntity > , IRootEntity

 

 

Granted it looks a little odd specifying the class as a generic parameter to the base class, but it is not a difficult pattern to follow.

 

But we know have enough details to drive producing a report linking these pivotal objects together. This framework will verify that these details are accurate and update.

 

We also get some value added in the implementation in that key methods that would not normally be strongly typed are strongly typed and the usage of the Entity is more streamlined by allowing us to get a fully initialized entity through the constructor.

 

 

MemberEntity member = new MemberEntity(12);

 

 

Following a Data Transfer Pattern, you are often faced with having to convert a list of Entities to a list of Data Transfer Objects (DTO).

A common strategy is to provide a GetDto() method in the base class for the Entities. This leads to a conversion process similar to:

 

foreach (var entity in ListOfEntities)

{

ListOfDTOs.Add(entity.GetDto());

}

 

 

While this works it is a little clutzy and cumbersome, especially considering the alternative.

 

This can be converted to a LINQ expression as

 

 

var ListOfDTOs = ListOfEntities.Select(entity => entity.GetDto()).ToList();

 

 

But what about going the other way around? We don't really want to define a GetEntity method in the DTO. This can potentially lead to cyclic dependencies, and we don't want to have any logic in the DTO itself.

 

This is actually a great place for an extension method even though we are dealing with a class that we wrote. Consider an Extension method like this:

 

 

public static TEntity GetEntity<TEntity, TDto>(this TDto data)

where TEntity : EntityBase<TDto >, new()

{

TEntity returnValue = new TEntity();

MapProperties(data, returnValue);

return returnValue;

}

 

 

The MapProperties method handles a reflective property mapper.

 

With such an extension method, we can now write logic similar to this:

 

 

ListOfEntities = (from dto in ListOfDTOs

select dto.GetEntity<SampleEntity, SampleDto>()).ToList();

It is common for every table to have a common set of audit tracking fields such as DateLastModified, UserIdLastModified, etc.

In our entities, this is easily supported by having these properties defined in a base class that every entity derives from.

This has always been somewhat cumbersome from a mapping perspective. Using classic hbm mapping files there is no way to inherit such details and they had to be repeated for each mapping.

One of the many benefits that Fluent NHibernate brings to the table is a much better solution to this.

We can define an AuditMapping base class and derive our mapping classes from it and not have to duplicate the mapping of common fields.

 

 

public class AuditMap<T> : ClassMap<T> where T : IEntity

{

public AuditMap()

{

Map(p => p.DateEffective);

Map(p => p.DateExpiry);

Map(p => p.DateLastModified);

Map(p => p.TypeIdModifierOrigin);

Map(p => p.UserIdLastModifier);

}

}

 

 

You just need to constrain T to require that it implements an interface common to all Entities or be derived from the base class for all entities.

 

This proves to be a nice way to standardize mapping and simplify the process of actually mapping the classes.

 

Is anyone else using any similar techniques?

My day started out very rough. Hit a few rough patches early on, but then turned around to end as one of the best days of the year!

I spent the night in the hospital last night. My wife had surgery yesterday and I stayed with her. No one wants to stay in the hospital, right?

Bright and early at 6 AM, I went to the car and discovered a flat tire. I am a software guy. Changing a tire is too much like hardware. I have changed 3 flat tires career total. In the course of changing the tire, I learned a lot about the Jeep Commander. One thing that I learned, the trusty jack that came with it will not in fact lift the car high enough to get the front tires off.

Funny story, it took me and 3 hospital security guards with 2 different jacks to actually change the tire. In the end, we had to resort to placing 2x4's on top of the jack to get the lift we needed.

Armed with a freshly changed tire, I proceed to take my daughter to day camp. It is now 8:30.

We packed a lunch for her, a lunch for me, and walked the dog. I am trying to put the tire changing adventures behind me. We rush out of the house hoping to make up some lost time.

I swear that I confirmed before we left that she had her lunch with her...

Amazingly the lunch was missing when we got to day camp. My lunch was in the car, but it was all alone!

So after getting more than a little upset about the whole missing lunch, I drop her off with my lunch and proceed on to work. Wondering how the day could get any worse.

Turns out just the exact opposite!

I get to work and discover that the current sprint is going very well. QA has accepted all of our user stories for the sprint nearly a day ahead of schedule. We may go home early unless one last round of testing finds anything.

That never happens! One of the rules of software development surely is that QA will find something at the last minute. The fact that this is a holiday weekend all but guarantees it, but we will keep our fingers crossed.

I am setting at my desk hoping for an early day, dreaming of the mythical gods of software development smiling down on me, whimsically imaging a day when QA signs off on a sprint at the beginning of the last day instead of at the last minute. Caught up in these dreams, I get a call from my wife.

The doctors have decided that she needs to move to a different floor. My initial reaction was shock and disappointment. I was afraid that we were returning to a day of everything going wrong. Moving hospital rooms is a pain, especially when the patient is alone. You have to pack up all your stuff. You have to unpack all your stuff. You have to break in new nursing staff. This new nursing staff has to wait on your orders to be transferred. If you are confined to a hospital bed with limited mobility, this cannot be good. If you desperately need sleep, this is most definitely bad. I am worried.

Turns out this new room will be twice the size of the old room. My wife loves it. The old room felt like a dungeon. This new room is wonderful. The move went smoothly. The gods of hospital room moves smiles on us.

But back at the office, I fear the good news. Surely these good fortunes and blessing won't last forever. Where is that other shoe?

Wonder of wonders, the sprint ends successfully. I do in fact get to leave the office at 1. A most excellent way to end a sprint.

Now off to the hospital. The new room seems like a luxury hotel room compared to the old room. There actually is a couch in the room. You can walk around without banging into polls or knocking over tables. It is amazing. It is unbelievable.

My day has taken a dramatic turn, several dramatic turns. Having started off so badly, I am very shocked at where I am now. Shocked and not entirely believing the transformation.

Surely there must be something wrong. Am I dreaming? Is there some hidden catch? There must be something that I am not seeing!

And then I get an email that would turn any day around all by itself no matter how bad it is.

For the first time ever, I was awarded an MVP award!!!!!!

Most readers on this blog site will know what a big deal this. For anyone not familiar with development in the Microsoft world, it is hard to explain, but trust me it is a big deal.

In summary, Sprint ended well and early on a holiday weekend. We are still in the hospital, but now in a room that most hotels would envy, and I was awarded an MVP award! Bad stuff happened this morning? Yea, I seem to vaguely remember something about that.

Here's hoping that everyone enjoys a wonderful holiday weekend.

I have been playing around with lambda syntax and some of its implications.

 

I came across a rather clever way to launch a simple thread.

 

 

(new System.Threading.Thread(() =>

{

Function(param);

}

)).Start();

 

 

Of course if all you have is a single line, you can replace it with:

 

(new System.Threading.Thread(() => Function(param))).Start();

 

This makes it real simple to call a method in a separate thread. This can be very useful and make it very easy to build more responsive logic.

Sadly it also makes it very easy to abuse threads and more likely to code yourself in a corner.