November 2003 - Posts

Templating options for a Content Management System

As I noted in a previous post I'm writing a simple content management system (CMS) to test out my Entity Framework, as well as to fill the need of one of my clients.  One of the concepts which I've been putting some thought into recently is the best way to provide a templating system for the CMS. 

I've seen a couple of different approaches that all use a very similar approach.  dasBlog, nGallery, and a couple other applications define templates using html files with some kind of global variable tags defined within them. 

dasBlog - {itemTitle}
nGallery - [$itemTitle$]

My initial implementation will likely be very similar.  I have some thoughts regarding an advanced templating system that could be used by “power“ users.  I was thinking of having the templating system be based on the in-line script syntax of ASP.NET.  After the users entered a new script into the admin a page parser would be used to validate the template.  Assuming the template “compiled“ the template would then be available for use.  Essentially the template would be a dynamic assembly that a templated page would hand itself off to.  I haven't done any of the ground work to see how feasible this is, but it *seems* doable.  We shall see....

UPDATE: The templating and macro code in dasBlog looks pretty sweet.  I think I'm going to have to dig through this code a little more...

Pretty darn legendary "non-legend"!

Last week I wrote a post about some problems I was having entering a license for an unnamed product.  In the comments for the post Eric Sink fessed up and admitted that the product was his very own Vault.  I intentionally didn't say the name of the product because I didn't want my experiences to scare anyone away from buying Vault.  Its a kick ass product (well it is just source control but none-the-less it rocks), if you haven't checked it out yet, do so

Today I read Finance for Geeks, written by Eric.  The article provides a “geek-oriented” overview of accounting, finance, and company funding.  All I can say is Eric is awesome.  He continually provides excellent articles on the “non-technical topics” that any geek with dreams of starting up his own ISV needs to know.  He's got me ready to go tell my boss I'm taking off to start up my own ISV....hmmm...maybe I should figure out what software I'm going to develop first :-)

What source control structure is "right" for a class libraries?

Last week we had an internal meeting to discuss the future for a class library that we've been using on all of our .NET projects.  The class library is actually what spurred the creation of my personal Entity Framework.  The library has a bunch of common utilities and functions as well as a set of base classes for business objects.  We currently have about 5 sites/applications using the library.

Let me start by saying our current setup sucks. 

  • Within VSS we have a single source code tree that is organized like so:
    • OurCompany
      • *.Core
        • all the source files here

When we start a new project we copy the latest version of the Core dll into a “ReferencedAssemblies“ folder within the new projects “project folder“ on the network (\\mynetwork\projects\NewProject\ReferencedAssemblies).  Within VS.NET we add the core dll to the referenced assemblies by browsing to the ReferencedAssemblies project folder on the network.  I'm sure your thinking, WHY?!?!  Well I am too.

One of the first things we identified in our meeting was the need to redo our source control structure to better support new versions of the library as well as better sharing of release versions between projects.  We currently don't have any problems with our setup because all our clients are using the same version of our class library (v1.0).  When we begin working on the new version we'll need to have our source control tree better able to support it.  We are planning on branching the current code base into a separate trunk.  Any bugs identified in any of the current applications will be fixed in the v1.0 branch.  All new development will occur within the main tree that will be moved into a v2.0 tree. 

To start we're thinking of creating a set of version folders with VSS that looks something like this: (expanded out beyond what we currently need as an example)

  • OurCompany
    • v2.0
      • src
        • v2.0.0.32983
          • bin
            • Release
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
            • Debug
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
          • (All Source Code Here)
        • v2.0.0.67384
          • bin
            • Release
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
            • Debug
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
          • (All Source Code Here)
    • v1.0
      • src
        • v1.0.0.2993
          • bin
            • Release
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
            • Debug
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
          • (All Source Code Here)
        • v1.0.0.3245
          • bin
            • Release
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
            • Debug
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
          • (All Source Code Here)

So if ProjectA uses v1.0.0.3245 we will share the $/OurCompany/Core/v1.0/src/v1.0.0.3245/bin/Release/Core.dll file to the $ProjectA/v1.0/lib folder.  Then if a bug is identified in the v1.0.0.3245 version of the library we can update it once and have all projects dependent on that release automatically be updated when a new build (and thus get latest) is done for the project.

We still have the potential problem of project code relying on a bug within the component.  So if ProjectA is written in a way to account for a bug in v1.0.0.3245 of the component, we may actually break the application by fixing the code.  To handle this problem we'll probably have to have all kinds of other fun and exciting branches.

After thinking about all this I'm curious how others are handling it.  What does your source control tree look like?  What works for you?  What doesn't? Please share your experiences in the comments for this post!

What source control structure is "right" for a class libraries?

Last week we had an internal meeting to discuss the future for a class library that we've been using on all of our .NET projects.  The class library is actually what spurred the creation of my personal Entity Framework.  The library has a bunch of common utilities and functions as well as a set of base classes for business objects.  We currently have about 5 sites/applications using the library.

Let me start by saying our current setup sucks. 

  • Within VSS we have a single source code tree that is organized like so:
    • OurCompany
      • *.Core
        • all the source files here

When we start a new project we copy the latest version of the Core dll into a “ReferencedAssemblies“ folder within the new projects “project folder“ on the network (\\mynetwork\projects\NewProject\ReferencedAssemblies).  Within VS.NET we add the core dll to the referenced assemblies by browsing to the ReferencedAssemblies project folder on the network.  I'm sure your thinking, WHY?!?!  Well I am too.

One of the first things we identified in our meeting was the need to redo our source control structure to better support new versions of the library as well as better sharing of release versions between projects.  We currently don't have any problems with our setup because all our clients are using the same version of our class library (v1.0).  When we begin working on the new version we'll need to have our source control tree better able to support it.  We are planning on branching the current code base into a separate trunk.  Any bugs identified in any of the current applications will be fixed in the v1.0 branch.  All new development will occur within the main tree that will be moved into a v2.0 tree. 

To start we're thinking of creating a set of version folders with VSS that looks something like this: (expanded out beyond what we currently need as an example)

  • OurCompany
    • v2.0
      • src
        • v2.0.0.32983
          • bin
            • Release
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
            • Debug
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
          • (All Source Code Here)
        • v2.0.0.67384
          • bin
            • Release
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
            • Debug
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
          • (All Source Code Here)
    • v1.0
      • src
        • v1.0.0.2993
          • bin
            • Release
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
            • Debug
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
          • (All Source Code Here)
        • v1.0.0.3245
          • bin
            • Release
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
            • Debug
              • *.Core.dll (shared to other projects)
              • *.Core.xml (shared ?)
          • (All Source Code Here)

So if ProjectA uses v1.0.0.3245 we will share the $/OurCompany/Core/v1.0/src/v1.0.0.3245/bin/Release/Core.dll file to the $ProjectA/v1.0/lib folder.  Then if a bug is identified in the v1.0.0.3245 version of the library we can update it once and have all projects dependent on that release automatically be updated when a new build (and thus get latest) is done for the project.

We still have the potential problem of project code relying on a bug within the component.  So if ProjectA is written in a way to account for a bug in v1.0.0.3245 of the component, we may actually break the application by fixing the code.  To handle this problem we'll probably have to have all kinds of other fun and exciting branches.

After thinking about all this I'm curious how others are handling it.  What does your source control tree look like?  What works for you?  What doesn't? Please share your experiences in the comments for this post!

Does an OR Mapper need to use dynamic sql?

What a glorious dynamic SQL vs. stored procedure debate we have going on!  

I've always been a bit of a stored procedure bigot.  In my early days I got bitten numerous times by dynamic sql.  As Frans has pointed out dynamic sql, which is generated for you behind the scenes, removes a lot of the “potential for pain.”  By encapsulating the SQL generation in a single component you can ensure the SQL code doesn't get interspersed with all the other code within your application.

The entity framework I've been developing (which technically is a OR mapper) uses stored procedures.  The main reason for this is that like Frans, I had some misconceptions about dynamic sql.  Over the last year or so I've read a lot of posts by Thomas, as well as Frans, which have corrected a lot of my misconceptions.  They've done an awesome job educating stored procedure bigots like me, on the fact that dynamic sql, when done right, can be a very viable alternative to stored procedures.

The biggest problem with using stored procedures within an OR Mapper is the fact that it introduces another element into the equation.  When you update your business object, you then need to update your table, as well as your stored procedures.  When you want to add another filter to a select you need to update your stored procedure.  When you want to do pretty much anything, you need to update your stored procedures.

Although my OR Mapper currently uses stored procedures to perform all its data access, it would not be a huge task to make it use dynamic sql.  As I've noted before the framework uses a provider model.  My current entity provider happens to use stored procedures to persist, retrieve, and delete entity objects from the data store.  There is nothing stopping me from creating another provider that uses dynamic sql. 

Lately I've been thinking about what the REAL problem is with using stored procedures with an OR Mapper.  Why do I have to go into each stored procedure myself and add the additional parameter.  If dynamic SQL can be generated “on the fly” to persist my entity objects, why couldn't a stored procedure be generated “on the fly” as well. 

By relying on myself to update the stored procedures when I update an entity object I'm not keeping with the DRY principle.  The information necessary for the generation of that stored procedure is already available within the metadata for that entity object.  Why can't the entity object's metadata be the driving force?

What is an entity object?

One of my colleagues recently asked me to define an “entity object.”  Before I came up with a definition he sent me this link: What is an entity object?

The article does a good job of describing what an entity object is as well as many of the things one has to think about when they are designing a system or framework to work with entity objects. 

Should entering your license key be this hard?

Last night I purchased a license for an application from the company's website.  After purchasing the license I received an email that contained my license key.  After installing the program on my machine I went into the license “area“ of the application.  I opened up the email with the license, highlighted the key, and pasted it into the dialog box in the application.  After clicking OK I received a message saying the license I entered was not valid.  “Say what?!?!”...I proceeded to copy and paste the license several other times, each time trying something slightly different.  I finally realized that I had to manually add line breaks after each 40 characters of the license key.  Why doesn’t the license key in the email have line breaks after each 40 characters?  Why does the application care?  Shouldn’t it be able to figure out what the key is, even if I don’t explicitly add the line breaks myself?

 

Maybe we should JUST focus on our user interface's usability!  I was ready to call up and ask for my money back when I finally realized what I had to do to make the application accept the key I was entering.  Things should not be this hard.

 

 

?>

Is Your API usable? Why not?

During the design of a website, intranet, or custom built application I often put a lot of consideration into the usability of the user interface.  Having a nice clean interface that is easy to navigate and that makes it obvious how to carry out important tasks is considered by many to be the most important aspect of an application.

Recently I've been doing a lot of work on base class libraries as well as my entity framework.  Although I've always thought an API should be usable, I haven't done anything to back it up.  Part of the reason I don't think I really considered it a part of my design and review process was that I was too busy trying to figure out other things.  Once it worked I didn't care if it was usable, what did that matter....it worked!

Needless to say I'm trying to change my ways.  A usable API is extremely important.  The likelihood of a class library being used is directly tied to how usable it is.  It needs to make sense to developers.  It needs to make it obvious how to perform certain tasks using the API.  It needs to make the code feel simple, clean, and super cool. 

Do the developers using your API's a favor and consider usability ALWAYS.  Make it a part of the design and review process.  Make it a high priority.  Don't be happy with “it works, it works,” make it work the way the developers using it would expect.

Is Your API usable? Why not?

During the design of a website, intranet, or custom built application I often put a lot of consideration into the usability of the user interface.  Having a nice clean interface that is easy to navigate and that makes it obvious how to carry out important tasks is considered by many to be the most important aspect of an application.

Recently I've been doing a lot of work on base class libraries as well as my entity framework.  Although I've always thought an API should be usable, I haven't done anything to back it up.  Part of the reason I don't think I really considered it a part of my design and review process was that I was too busy trying to figure out other things.  Once it worked I didn't care if it was usable, what did that matter....it worked!

Needless to say I'm trying to change my ways.  A usable API is extremely important.  The likelihood of a class library being used is directly tied to how usable it is.  It needs to make sense to developers.  It needs to make it obvious how to perform certain tasks using the API.  It needs to make the code feel simple, clean, and super cool. 

Do the developers using your API's a favor and consider usability ALWAYS.  Make it a part of the design and review process.  Make it a high priority.  Don't be happy with “it works, it works,” make it work the way the developers using it would expect.

Versioning of class libraries with source control

Versioning

Sharing across projects

How to update the library without breaking things that rely on whats broken

Branching/merging

  • v1.1
    • src
      • v1.1.0.32983
        • bin
          • Release
            • *.Core.dll (shared to other projects)
            • *.Core.xml (shared ?)
          • Debug
            • *.Core.dll (shared to other projects)
            • *.Core.xml (shared ?)
      • v1.1.0.67384
        • ...
  • v1.0
    • src
      • v1.0.0.2993
        • ...
      • v1.0.0.3245
        • ...

Getting on the Provider bandwagon

After reading Rob Howard's ASP.NET "Whidbey" Provider Model blog entry I realized I had jumped on the Provider bandwagon without even knowing it. 

I've written a number of posts related to the design of my Entity Framework since I started this blog. 

In several of my entries I've written about Entity Managers.  The managers are responsible for saving, deleting, and retrieving business objects from a data store.  But wait, these aren't really managers.  EntityBroker uses managers.  What I have are entity “providers.”  They provide persistence services to the entity objects.  Different providers provide persistence to different data stores.  Calling the entity providers managers leads one to believe they handle more then they actually do.  They don't handle transactions, they don't handle object construction (manager.Create(typeof(Customer))), they are just providers. 

Entity objects use the configured provider to save, remove, retrieve, and find themselves.  Changing the configured provider changes how this is done as well as what type of data store the objects are stored within.  Providers give users of the entity framework a lot of flexibility. 

While me entity framework is still not my ideal, it is getting closer.  My recent work with creating a “Mock Entity Manager Provider”, has proven that the architecture does allow new entity providers to be plugged into the framework.  The ability to switch a flag within a configuration file and all the sudden have all my business objects use a different data store is something I really like.  I haven't yet had the need (or time) to write the other entity providers that I want for the framework, however, through the development of my mock entity provider I have definitely seen the benefits that a provider model brings!

Getting on the Provider bandwagon

After reading Rob Howard's ASP.NET "Whidbey" Provider Model blog entry I realized I had jumped on the Provider bandwagon without even knowing it. 

I've written a number of posts related to the design of my Entity Framework since I started this blog. 

In several of my entries I've written about Entity Managers.  The managers are responsible for saving, deleting, and retrieving business objects from a data store.  But wait, these aren't really managers.  EntityBroker uses managers.  What I have are entity “providers.”  They provide persistence services to the entity objects.  Different providers provide persistence to different data stores.  Calling the entity providers managers leads one to believe they handle more then they actually do.  They don't handle transactions, they don't handle object construction (manager.Create(typeof(Customer))), they are just providers. 

Entity objects use the configured provider to save, remove, retrieve, and find themselves.  Changing the configured provider changes how this is done as well as what type of data store the objects are stored within.  Providers give users of the entity framework a lot of flexibility. 

While me entity framework is still not my ideal, it is getting closer.  My recent work with creating a “Mock Entity Manager Provider”, has proven that the architecture does allow new entity providers to be plugged into the framework.  The ability to switch a flag within a configuration file and all the sudden have all my business objects use a different data store is something I really like.  I haven't yet had the need (or time) to write the other entity providers that I want for the framework, however, through the development of my mock entity provider I have definitely seen the benefits that a provider model brings!

Should a business object == a database table?

A common approach used in developing an application that utilizes a database is to create one business object for each table in the database.  I have taken this approach on many occasions.  The biggest advantage of using this approach is that it simplifies the process of mapping business objects to database tables.

Last week I began developing my first application against my “new” Entity Framework.  The application is a lightweight content management system.  The CMS will have many of the features we have come to expect from a CMS, as well as some support for Rss and *possibly* some blog related features.

While developing the object model for the CMS I've found that the data model (that doesn't yet exist) has been attempting to influence the design of my objects. 

Last night I made changes to the object model that will make a 1:1 mapping between my objects and my database tables unlikely.  It feels nice to have rid myself of the influence of the data model.  As I continue developing the CMS I'm sure the data model will show his ugly face again in attempts to bring me back to the 1:1 mapping he expects....I wonder if I'll be able to fight him off?

TDD with a database is no fun

Last week I posted about how using MockObjects allowed me to remove the overhead of working with the database during the coding of my business objects.  The last two nights I have switched over to using the database again to test out my stored procedures and other database related logic.  Unfortunately I'm quickly being reminded of why I liked using MockObjects so much.  Writing test classes that hit the database require a bit of extra work that only adds pain to the TDD process.  The most painful extra step is ensuring that the database is left in the same state that it starts in.  This involves writing a Cleanup method for removing any records inserted into the database.  Currently my Cleanup methods look something like this:

[TearDown]

public void Cleanup() {
   Globals.DeleteData("Table1", “Table2“, “Table3“);
}

The Globals.DeleteData() method deletes all records in each of the tables passed in.  I've been thinking about using transactions to “rollback” all the changes made by my classes but that will involve a little coding within my base framework.  Additionally something that I haven't fully embraced within my test classes is the use of Mock Objects for “dependent objects”.  Ideally my test classes should only be testing one type of object, however, when I incorporate the database into the equation this isn't really possible since in order for my inserts to work I need records in all referenced tables (Foreign Keys).

In summary, I don't like doing TDD with a database.  It interrupts the coding process too much and introduces a bunch of extra variables that make the process cumbersome.  I'd love to just write my unit tests against my Mock Entity Provider but then I can't validate my stored procedures and other database related logic with my unit tests.  Any recommendations?

MockObjects help me get in the "TDD Zone"

One of the things I've struggled with in the past when doing Test Driven Development was the need to work with the database.  Recently I started a new project and decided to try and do things the “right way.”  Rather then have my test classes hit the database I decided to write a MockEntityManager class to use during testing.  Tonight I put the final touches on the mock object and started writing some code for my objects.  What a difference! 

By removing the database from the equation I'm able to focus on my objects.  I no longer have to worry about updating stored procedures or table schema's when the functionality of my objects change.  I can update my test, see red, update my class, see green. 

The other nice thing about my setup is that by flipping one flag in my config file for my tests I can have all my tests run against the database.  So I get the best of both worlds.  I get into a nice “coding flow” with the mock object, but, also get the security of knowing my database and stored procedures are functioning as expected with a quick config file change.

MockObjects help me get in the "TDD Zone"

One of the things I've struggled with in the past when doing Test Driven Development was the need to work with the database.  Recently I started a new project and decided to try and do things the “right way.”  Rather then have my test classes hit the database I decided to write a MockEntityManager class to use during testing.  Tonight I put the final touches on the mock object and started writing some code for my objects.  What a difference! 

By removing the database from the equation I'm able to focus on my objects.  I no longer have to worry about updating stored procedures or table schema's when the functionality of my objects change.  I can update my test, see red, update my class, see green. 

The other nice thing about my setup is that by flipping one flag in my config file for my tests I can have all my tests run against the database.  So I get the best of both worlds.  I get into a nice “coding flow” with the mock object, but, also get the security of knowing my database and stored procedures are functioning as expected with a quick config file change.

A base class for testing Entity objects

Late last week one of my colleagues approached me about the “need” to create a test class that would handle testing all the “base functions” on our entity objects.  He was in the middle of writing a lot of repetitive code and getting pretty sick of it.  The idea had run through my mind before but I never really thought about how to implement such a “fantastically snazzy base class.”

Well tonight I had the need.  Rather then really thinking about how to do it, I just started coding.  The first thing I did was add a couple of stub routines to test the Save(), Delete(), and GetAll() methods of the entity objects.  Although there are a couple more that are “test worthy“ I figured these three would provide me with a good starting point. 

I decided to start with the Save() method since it seemed to be the most important, and potentially most difficult.  I needed to figure out a way to populate the entity object with random values.  Sounds easy enough...I opened up groups.google.com and did a search within the .net newsgroups for “generate a random string.“  I found a nice little code snippet that gave me just the bit of information I needed to get started.

private string GetRandomString(int maxLength) {
   string randomString = null;
   Random rNumber =
new Random(Environment.TickCount);
   for(int i = 0; i < maxLength; i++) {
      randomString = randomString + Convert.ToChar(rNumber.Next(65,90));
   }
   return randomString;
}

Ok, so I had the first piece of the puzzle.  I could now generate a random string.  Next a little thought into what I actually needed to do to the object before I could try and save it.  I would need to loop through all the properties and assign appropriate values...ahh, I love Reflection!

public void LoadProperties(EntityObject entity) {
   System.Reflection.PropertyInfo[] properties = entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
  
foreach(PropertyInfo property in properties) {
     
object[] attributes = property.GetCustomAttributes(typeof(PersistAttribute), false);
     
if(attributes.Length > 0 && property.CanWrite)
         SetDynamicPropertyValue(entity, property);
   }
}

The above code loops through all the public properties that are declared on the passed in entity object and then sets the property using the SetDynamicPropertyValue() method.

private void SetDynamicPropertyValue(EntityObject entity, PropertyInfo property) {
   Random random;
   switch(property.PropertyType.ToString()) {
      case "System.String":
         property.SetValue(entity, GetRandomString(),
null);
         break;
      case "System.Int32":
      case "System.Decimal":
      case "System.Double":
        random =
new Random(Environment.TickCount);
        property.SetValue(entity, random.Next(1, 9999),
null);
        break;
      case "System.DateTime":
        Random dayRandom =
new Random(Environment.TickCount);
        Random monthRandom =
new Random(Environment.TickCount);
        property.SetValue(entity, DateTime.Parse(monthRandom.Next(1, 12) + "/" + dayRandom.Next(1, 2 + "/" + DateTime.Now.Year),
null);
        break;
      case "System.Boolean":
        random =
new Random(Environment.TickCount);
        property.SetValue(entity, Convert.ToBoolean(random.Next(0, 1)),
null);
        break;
      default:
        if(property.PropertyType.BaseType.ToString() == "System.Enum") {
          Array values = Enum.GetValues(property.PropertyType);
          random =
new Random(Environment.TickCount);
          property.SetValue(entity, values.GetValue(random.Next(values.Length)),
null);
        }
        break;
     }
}

By utilizing the SetValue() method on the PropertyInfo class as well as the handy dandy Random class I'm able to set the properties of my object dynamically. 

Now that my objects could be loaded I filled in the stub methods for Save(), Delete(), and GetAll().  

[Test]

public void Save() {
   Save(Entity)
}

private void Save(EntityObject entity) {
   LoadProperties(entity);
   Assert.IsTrue(Entity.Save(), "The object could not be saved.");
}

[Test]
public void Delete() {
   Save();
   Assert.IsTrue(Entity.Delete(), "The object could not be deleted.");
}

[Test]
public void GetAll() {
   Random random =
new Random(Environment.TickCount);
  
int recordsToAdd = random.Next(1, 10);
  
for(int i = 0; i < recordsToAdd; i++) {
      EntityObject e = (EntityObject)Activator.CreateInstance(Entity.GetType());
      Save(e);
   }
   MockEntityManager.NumberOfMatchesForGetAll = recordsToAdd;
   Assert.AreEqual(recordsToAdd, Entity.GetAll().Count, "The number of records returned is different then expected.");
}

Obviously the code I'm presenting here isn't far enough along to use in a “real” test environment but I'm pleased with the progress I made thus far.  With a couple more tweaks I think I'll have the base class where it needs to be.

What methods are you using to automate the test classes for the common methods on your entity objects? 

Sample Code Files

A base class for testing Entity objects

Late last week one of my colleagues approached me about the “need” to create a test class that would handle testing all the “base functions” on our entity objects.  He was in the middle of writing a lot of repetitive code and getting pretty sick of it.  The idea had run through my mind before but I never really thought about how to implement such a “fantastically snazzy base class.”

Well tonight I had the need.  Rather then really thinking about how to do it, I just started coding.  The first thing I did was add a couple of stub routines to test the Save(), Delete(), and GetAll() methods of the entity objects.  Although there are a couple more that are “test worthy“ I figured these three would provide me with a good starting point. 

I decided to start with the Save() method since it seemed to be the most important, and potentially most difficult.  I needed to figure out a way to populate the entity object with random values.  Sounds easy enough...I opened up groups.google.com and did a search within the .net newsgroups for “generate a random string.“  I found a nice little code snippet that gave me just the bit of information I needed to get started.

private string GetRandomString(int maxLength) {
   string randomString = null;
   Random rNumber =
new Random(Environment.TickCount);
   for(int i = 0; i < maxLength; i++) {
      randomString = randomString + Convert.ToChar(rNumber.Next(65,90));
   }
   return randomString;
}

Ok, so I had the first piece of the puzzle.  I could now generate a random string.  Next a little thought into what I actually needed to do to the object before I could try and save it.  I would need to loop through all the properties and assign appropriate values...ahh, I love Reflection!

public void LoadProperties(EntityObject entity) {
   System.Reflection.PropertyInfo[] properties = entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
  
foreach(PropertyInfo property in properties) {
     
object[] attributes = property.GetCustomAttributes(typeof(PersistAttribute), false);
     
if(attributes.Length > 0 && property.CanWrite)
         SetDynamicPropertyValue(entity, property);
   }
}

The above code loops through all the public properties that are declared on the passed in entity object and then sets the property using the SetDynamicPropertyValue() method.

private void SetDynamicPropertyValue(EntityObject entity, PropertyInfo property) {
   Random random;
   switch(property.PropertyType.ToString()) {
      case "System.String":
         property.SetValue(entity, GetRandomString(),
null);
         break;
      case "System.Int32":
      case "System.Decimal":
      case "System.Double":
        random =
new Random(Environment.TickCount);
        property.SetValue(entity, random.Next(1, 9999),
null);
        break;
      case "System.DateTime":
        Random dayRandom =
new Random(Environment.TickCount);
        Random monthRandom =
new Random(Environment.TickCount);
        property.SetValue(entity, DateTime.Parse(monthRandom.Next(1, 12) + "/" + dayRandom.Next(1, 2 + "/" + DateTime.Now.Year),
null);
        break;
      case "System.Boolean":
        random =
new Random(Environment.TickCount);
        property.SetValue(entity, Convert.ToBoolean(random.Next(0, 1)),
null);
        break;
      default:
        if(property.PropertyType.BaseType.ToString() == "System.Enum") {
          Array values = Enum.GetValues(property.PropertyType);
          random =
new Random(Environment.TickCount);
          property.SetValue(entity, values.GetValue(random.Next(values.Length)),
null);
        }
        break;
     }
}

By utilizing the SetValue() method on the PropertyInfo class as well as the handy dandy Random class I'm able to set the properties of my object dynamically. 

Now that my objects could be loaded I filled in the stub methods for Save(), Delete(), and GetAll().  

[Test]

public void Save() {
   Save(Entity)
}

private void Save(EntityObject entity) {
   LoadProperties(entity);
   Assert.IsTrue(Entity.Save(), "The object could not be saved.");
}

[Test]
public void Delete() {
   Save();
   Assert.IsTrue(Entity.Delete(), "The object could not be deleted.");
}

[Test]
public void GetAll() {
   Random random =
new Random(Environment.TickCount);
  
int recordsToAdd = random.Next(1, 10);
  
for(int i = 0; i < recordsToAdd; i++) {
      EntityObject e = (EntityObject)Activator.CreateInstance(Entity.GetType());
      Save(e);
   }
   MockEntityManager.NumberOfMatchesForGetAll = recordsToAdd;
   Assert.AreEqual(recordsToAdd, Entity.GetAll().Count, "The number of records returned is different then expected.");
}

Obviously the code I'm presenting here isn't far enough along to use in a “real” test environment but I'm pleased with the progress I made thus far.  With a couple more tweaks I think I'll have the base class where it needs to be.

What methods are you using to automate the test classes for the common methods on your entity objects? 

Sample Code Files

On Error GoTo DOT_NET

I've been thrown back into the unmanaged world once again.  Man does it suck in this deep dark land of On Error Resume's, no curly braces, and no semi-colons.....well unless you're using the semi-colon prefix character that Don Box taught all us “newbies” about!

Call ReWriteInDotNet() ';

 

Ideal Coding Environment

This morning as I was going through the Digest emails I recieve from the DevelopMentor mailing lists I stumbled upon a couple posts from individuals looking for the “ideal coding“ font.  I decided to try out the two fonts mentioned and as I was at it I updated my font-colors to the dark background/light foreground setup that some of my co-workers use.  It made me start to think about what my “ideal coding environment“ is...

IDE
VS.NET 2003 - I'm more productive with this IDE then any others I've used.  I've heard a lot of really good things about SlickEdit though, so I might have to download the demo and give it a test run.  I'm looking forward to the refactoring support in Whidbey since I think its something which is lacking in VS.NET 03.

IDE Font / Color Setup
I've always used the default settings of my editor, except for the font size which I usually bump down to 9pt. for the extra screen real-estate. 

Courier New 9 pt.

Source Control
By default this is VSS.  It comes free with whatever MSDN/Partner “thingy” we have, and works relatively well for what we need.  SourceGear's Vault would most likely be our replacement but I haven't really used it much as of yet.

As an experiment I'm trying a different setup.  A new font (Andale Mono) and a new color scheme which you can checkout below... 


click here for full size

What is your ideal coding environment? 

Design of objects with CreatedBy, UpdatedBy, OwnedBy

Tonight I started development of a lightweight content management system (CMS) for a client.  The CMS is going to be using my Entity Framework so it should be fun to see how it goes since this will be the first new project I've worked on since doing a lot of re-architecting.

A couple of weeks ago I sketched out the object model in my notebook and last night I mapped the object model to a data model.  One of the things that I've run across on many projects is how to deal with objects that have CreatedBy, and UpdatedBy properties.  Within the database each of these fields are int's that store the ID of a User within the User table.  On my objects I'll need a property available to retrieve the ID of the user, but will also need a User object that represents the user.  I've seen this done a couple of different ways:

  • Declare a CreatedByID property that holds the ID of the user that created the object.  Declare a CreatedBy property that returns a User object that represents the user that created the object.  When the object is loaded set the CreatedByID property to the ID from the database.  When a user accesses the CreatedBy property use the CreatedByID property to load a full User object representing the User who created the object.

public int CreatedByID {
   get { return _createdByID;}
   set { _createdByID = value;}
}

public User CreatedBy {
   get {
        if(_createdBy == null)
             _createdBy = new User(_createdByID);
        return _createdBy;
   }
   set  { .... }
}

// Load code
_createdByID = Convert.ToInt32(dr[“CreatedBy“]);

  • Declare only a CreatedBy property that returns a User object.  When loading the object set the ID field of the User object to the CreatedBy field of the object.  If a user accesses a property other then the Id property perform a lazy load of the complete User object.

public User CreatedBy {
   get {
        if(_createdBy == null)
             _createdBy = new User();
        return _createdBy;
   }
   set  { .... }
}

// Load code
this.CreatedBy.ID = Convert.ToInt32(dr[“CreatedBy“]);

I prefer having a single property for gaining access about the user that created the object rather then having one property for the ID and a seperate property for the User object, however, having seperate properties often is easier to code.  As a user of a component what would you prefer?  If you were coding the app which way would you go? Why?

Unofficial blogs.gotdotnet.com feed updated

The Blogs.GotDotNet.Com feed is using the new feedgregator engine that I've been playing around with lately.  The main benefit of the new feedgregator engine is that I have complete control over how things are being done (aka no third party components).  The latest blogs.gotdotnet.com feed now includes the full post body so you don't have to double click to view entries for those bloggers who don't put the full post in the description field of their feed.

http://www.emxtechnologies.com/gotdotnet-blogs/mainfeed.xml

If there is anything missing from this feed please let me know.  I'll be more then happy to add it.  Sometime soon I'll probably open up the Feedgregator workspace to the public.  Before doing so I hope to:

  • Add Pre/Post aggregation tasks
    • FTP
    • XSL Transform
  • More extensibility points
  • ...

Making the customer matter

I believe the success or failure of a company can be tied directly to whether or not they truly put their customers first.  There are certain methodologies that lend themselves more towards pleasing the customer then others.  For most of my career I've worked with clients using a fixed bid waterfall process.  The engagement has been broken down into discrete phases that allowed us, the service provider, to ensure we stayed within budget and delivered what the client paid for.  Over the years I've worked with some clients that have been extremely pleased with the work we've done and then others that have been some where in between.  They liked us, our skills, and our ability to solve their problem but seemed to have some reservations about future projects.  I often marvel at how well we've done using the waterfall methodology.  I think much of this can be attributed to the overall skill and talent of the individuals I’ve worked with.

Over the last several months I've thought a lot about our clients.  What is it that they want?  What will make them happy?  What can we do to ensure they get the most out of any engagement with us?

As I sit and think about each of these questions I always come back to one thing.  If we put them first, above all else, above budgets, timelines, formal processes, and everything else we can ensure their happiness.

Now the problem.

It's hard to keep the client first using a fixed bid waterfall methodology.  The fixed bid portion forces you to always think about how close you are to the estimates, forces you to (sometimes) sacrifice quality to ensure everything is finished within budget.  It sucks.  We need to do better.  We need to kick butt for our clients.  We need to delight them.  We need them to love us.  We need something else.

Although there is no silver bullet I think the philosophies behind Agile methodologies allows the client to get much more out of us.  We can focus on them.  We can focus on their needs, wants, and desires.  We can come closer to the ideal world that allows us to kick butt and take names for them.