Welcome

You have reached the blog of Keith Elder. Thank you for visiting! Feel free to click the twitter icon to the right and follow me on twitter.

How To Not Screw Up Your Application Object Model – Don’t Go All OOP On Me!

Posted by Keith Elder | Posted in .Net, CSLA.Net, Programming | Posted on 02-05-2008

12

I have no idea where this post is going to go but I have several things that have come up in discussion lately with developers that I need to get out.  The conversations I’ve been having are around building applications and using the CSLA.Net business object framework.  This article doesn’t focus on CSLA.Net so even if you aren’t using it, these principals still apply.  This post stems from conversations with developers that are spending a lot of time creating beautiful object models.  I’ve seen developers spend a lot of time on perfecting the object model of an application based on sound OOP practices and techniques.  Once the object model is applied to the application it doesn’t work and the developers are scratching their heads asking themselves why.   I’ll explain a common scenario that I’m running into, how to avoid it, and how I think you should think about your object model for your applications.  Definitely fun bathroom reading, so let’s get going!

Throw Away The Object Model In Your Head

As object oriented programming developers on the .Net and or Java platforms we’ve always been taught and trained to think in object models and object graphs.  For example if I asked experienced object oriented programming developers to create an object model for a Veterinary Clinic they would start immediately thinking in terms of physical objects like, dogs, cats, birds, etc.  The reason is because we have been beat to death with OOP principles.  As an exercise I opened up Visual Studio and threw out the very first object model that came to mind based on a Veterinary Clinic.  Here’s what I came up with thinking about the object model from a pure educational standpoint.  I’d kept going but I wanted it to fit onto one screen.

image

Without knowing anything about the business of a vet clinic and relying only on my experience in owning pets this is the first thing I came up with.  My thought process was vets take care of pets, there are all types of pets, and pets belong to an owner.  Some pets are birds, some are dogs, cats, snakes, lizards, etc.  My college professor would be very proud of my object model I am sure.  He’d feel all warm and fuzzy seeing that I broke down my objects all the way down to dogs then the subclass of spaniels and then cocker spaniels (of which I own three).  On paper this looks great but it is an extremely bad object model.  Don’t do this!  The problem is developers try to apply these perfect object models to their applications.  This is the worst thing a developer can do when building an application.  Well, not the worst, but it sure is a really bad start and a lot of wasted time.

After doing this little exercise I have to admit I felt very dirty.  Seriously.  Why?  Because none of these objects fit into the what the Veterinary Clinic really needs and I honestly just wasted my time proving a point trying to stop you from wasting your time.  Stay with me and I’ll show you. 

A Real Example

I have a friend that is a vet.  After writing this really bad object model down I gave him a call and asked him if he had any software he used to run his clinic.  He said absolutely and he couldn’t run his business without it.  Great, a real world example!

I asked him to tell me about one of the screens they use the most in their application.  He then described what he called the “Account Locator” which after further questioning turned out to be a fancy name for a “Search” screen to lookup clients or accounts in the system.  I took a few mental notes during our conversation and after hanging up made this mock application based on his description. 

image

The scenario is employees running the main desk at the clinic need to get to accounts quickly and this is why this screen  is used so much.  The scenario is if someone calls the clinic to schedule an appointment, the first thing someone has to do is lookup their account.  The grid below displays some useful information to help the employee find the right account.  It also allows the employee to make the client feel like they are well known.  The example my friend gave is once an account is located the employee immediately knows the pet(s) name, the last time they came in and the type of the pet. 

This scenario now brings me back full circle to the object model I initially built.  Here’s the million dollar question: 

What good is a gigantic object model in this scenario?  Answer:  Nothing! 

The elaborate object model I built out based on my first impression of what objects I’d needed to create are basically useless. 

Why?  For starters, look at where the information from the object model (which shouldn’t have been written in the first place) has to come from just to make this screen work. 

image

Data is traveling from all sorts of different objects and I didn’t even account for all of the fields.  Are you starting to see why building elaborate object models for an application first doesn’t work?  If you don’t know how the data is going to be used you can’t build an object model. 

This is the main point.  Focus on the business requirements and don’t get all caught up in OOP principles just because it is fun.  And it is fun to be honest.  I love discussing object models but the point is you should be discussing the business requirements!

Do We Really Need An Object Then?

The question I get after showing someone the above example is, “Do we really need an object then since we are just fetching data?”.  When people ask me this what they mean is if they are just searching data and returning data, why all the emphasis on building objects in the first place?

The answer to that is lengthy but I’ll try to hit the high points.  Let’s start with the act of a user entering data into the three fields to search.  This is technically an object.  It is an AccountSearch object.  It isn’t a very hard object to create, it just has three properties.  Here are the things a developer has to think about though.

  1. Searching by just pet name will return too many results.  The developer must force that users enter the pet name and the owner last name.
  2. If a user enters a phone number only, that is ok.
  3. If they enter all three fields that is ok.
  4. The phone number must be formatted correctly to match how it is stored in the database.
  5. The pet name and the owner last name much match a certain criteria (example % isn’t in anyone’s name).
  6. Who is allowed to use this object?  Can just anyone in the world use it?  Probably not.  Therefore there are security concerns as well. 
  7. How is the object bound to these fields?
  8. Is the object in a broken state (error?).
  9. Was the object modified? (in other words you can’t search on something if there is nothing there)
  10. Is the object in a valid state?

All of this needs to be thought about and leaving any one of these off can cause lots of problems within the application.  Therefore, this is why we’d have an object that handled all of this logic.  And this is why we call them “business objects”.  In this case it is a single object that encapsulates all of these scenarios.  Take the first letter in the CSLA.Net Business Framework.  The first letter stands for “Component”.  This is where the name comes from because as you can see we are dealing with a single component that accounts for all of this.

How Many Objects Are On This Screen?

Now that we’ve established our initial object model was a complete waste of time, let’s look at what we should do with this example.  Looking at my prototype example, how many business objects do you think are on that example screen?  If you said three, you’d be correct! 

image

  1. AccountSearch.cs – This object encompasses the search functionality I elaborated on previously. 
  2. AccountSearchResult.cs – This object is a Read-0nly object that simply holds the data for each row.
  3. AccountSearchResultList.cs – This object is a Read-Only-Collection of AccountSearchResult objects. 

Even though the AccountSearchResult object is just a read only object it still needs to be an object.  For example, what if the business required us to change this screen and add another column that only admins could see?  Maybe the column in this case would be a column that held the Owner’s social security number.  In this scenario, the AccountSearchResult object needs to know how to handle this situation and it should know based on the user viewing it that it is not suppose to show that property.  More times than not a developers first reaction is to put this into the UI because it is easy and they aren’t using something like CSLA.Net that provides this functionality out of the box.  Writing that business logic in the user interface doesn’t do any other developer any good if another UI is built like a web UI for example.  Again, that object needs to know how to handle this.  Think component!

What about reusability?

The next question I get after explaining this is:

Are you telling me that every screen the app has, there is a different object?

My answer is any data that is “touching the glass” of the application is encapsulated in some type of object.  In more complex scenarios that may in fact be a full blown object graph with a parent and child objects, etc.  I’m not saying don’t think of any object model but typically more complex object models are what I call core objects to an application.  In this vet application an Owner object would be a core object that would have children of pets, addresses, invoices, bills, follow ups, appointments, etc.  BUT…. ONLY IF THAT IS HOW IT IS VIEWED IN THE APPLICATION!  The difference is you have to think of the YAGNI principle which is if you ain’t gonna need it, don’t put it in your object model.  Build the object model based on the expected behavior. 

Obviously when we build objects we like to re-use them and in some cases you can.  For example why wouldn’t you be able to reuse something like an Address object?  In most cases an address is just an address.  There are cases where even something as simple as an address needs to be in a separate business object though because of the business concerns around it.  For example imagine you were building objects for a realty company.  The address of the client vs the address of the subject property being sold are COMPLETELY different objects with different business rules around them.  This is exactly what I’m talking about.

When building your application you have to think about how an object is used.  For example, take our search screen example above.  What if we were told to build a search screen with the same search fields that returned a slightly different result set.  This is the crossroads where a developer has to really think and make a decision.  Basically there are two choices.

  1. Re-use the existing result object and modify it to account for both scenarios.
  2. Build a brand new object.

There isn’t a hard and fast answer I can give you as which way you should go.  My default answer is make them different objects since later on you can easily update one without impacting the other as new changes come in.  However you may decide to keep everything in one object based on the amount of time you have.  A general rule of thumb to follow is if 80%-90% of the data and logic in the objects can be re-used, then you may decide to just update the one object.  As you approach a lower percentage of re-use you are just causing yourself problems and need to separate those concerns.

The best way to think about this is let’s say you were building a screen that returned just plain old data (not even thinking objects anymore).  And on that screen you had 5 pieces of data.  Your data query might be something like: 

select col1, col2, col3, col4, col5 from MyTable where col1 like ‘%foo%’

If someone asked you to take out the second column in a certain scenario, would you leave the query alone or rewrite it as:

select col1, col3, col4, col5 from MyTable where col1 like ‘%foo%’

I would HOPE you wouldn’t return the second column if your application didn’t need it!  Building different objects for different purposes is the same thing.  Sometimes you might choose to not modify that query.  But as more columns are changed you’d be crazy not to think about the extra payload you are putting on the database, the network, and latency being built into your application.  It is a fine line to walk but as I said, if I have another screen in my application, I’m going to automatically make another object that encompasses that object for that one given scenario.  Remember, it isn’t just as simple as returning data.  If it were, there wouldn’t be something called business logic!

For further clarification let me say this.  If both objects in my application use the same business logic I am not going to duplicate that logic in each object.  That is silly and doesn’t scale.  That logic should be moved to a common library so it can be referenced from both objects.

Takeaway

The big takeaway from this litany of verbal spillage is when you design applications you have to know how the end-user is going to use the application and what the business requirements are.  Sitting down and building an elaborate object model, while really fun and educational, it is a big waste of time.  Don’t do it.  Sit down and ask questions so the behavior and business requirements can be accounted for.  Whether you are using CSLA.Net or not the same thoughts must go into building the application.  I hope this helps cements these concepts because I know there is a large amount of disconnect with this out there among developers who think everything is a perfect object graph like they learned it in school. 

Technorati tags: , ,

Configuring WCF and IIS 7 With HTTP Bindings and Multiple Host Headers

Posted by Keith Elder | Posted in .Net, WCF | Posted on 28-04-2008

27

If you’ve tried to deploy Windows Communication Foundation (WCF)  in a production environment the odds are you have come across this error at one point or another:

This collection already contains an address with scheme http.  There can be at most one address per scheme in this collection. Parameter name: item

It is one of those lovely errors that should have been gumped down before it made it into production code but for some reason the developer who wrote it thought they’d sound smarter if they obfuscated the problem to confuse everyone.  No fear, I’m hear to clear this up and gump it down to save you endless hours of time. 

The Problem

In multiple shared hosting environments or even in the enterprise where load balancers are used it isn’t uncommon to have a single machine answer to multiple host names.  This is typically the problem that causes the error above since IIS has more than one http binding configured to answer requests for a given web site.  To simulate this I am going to walk you through how to create a fake configuration so your local development machine answers to more than one host name.  Then I’ll walk you through how to configure IIS7 to deploy a WCF service to your local machine using one name, and then break the deployment to simulate the error above.  After that we’ll fix it.

Here is the overall goal of the walk through. 

  1. Configure our machine to answer multiple host names
  2. Setup IIS to support our application
  3. Deploy the sample WCF application
  4. Add the second host name to break the deployment
  5. Apply the fix

Requirements

A few months ago I did a walk through on how to configure WCF with multiple bindings.  We are going to take that example and deploy it into IIS.  I’ll be deploying this solution on Windows Vista SP1 using IIS7.  Even if you are using Windows Server 2008 the same setup should be similar.  If you haven’t read the previous article on multiple bindings please do so.  At the bottom of the article download the sample solution, this is what we’ll be deploying if you want to follow along.

Configuring Extra Host Headers

Edit hosts file to add fake names

More than likely if you are performing this setup on a developer machine for testing you’ll need to create several fake host names for your machine.  To do this, open the following file c:\windows\system32\drivers\etc\hosts and add in a few fake names.  For this example I’m going to add two additional host names for my machine so it answers to the names of “Elderville” and “WordsOfWisdom”.  You can obviously choose what you want.  Here are the two entries I am going to add to my hosts file.

image

Note that you will need to be administrator to add these lines to this file.  The lines added resolve to the localhost IP address which is 127.0.0.1.  After these names are added you should be able to ping these host names and get a response.

image

Locally the computer now responds to two additional host names:  elderville and wordsofwisdom.

Initial IIS7 Configuration

In order to deploy our sample WCF service we need to have a location pre-configured.   Create the following path on your hard drive called C:\WCFTest\wcfservice.  Once created, open Internet Information Services manager as administrator and right click the sites folder to add a new web site.

image

Create a new web site to deploy the WCF service and use the path we just created to deploy the service.  I’m going to configure the service to answer using the host name of elderville.

image

After the site is created, convert the “wcfservice” folder into an application.

image

image

This is as far as we need to go as this moment with IIS.  We’ll come back to IIS7 configuration in a bit so leave it open if you are following along.  Right now we just want to deploy the service and make sure it works.

Deploying Our Sample WCF Service

Unzip the sample solution and open the solution in Visual Studio 2008.  In order to prepare the service for deployment the only change we need to make is to change the address of the endpoints.  There are three endpoints this service exposes: WsPlain, Basic and WsSecured.  The first endpoint of WsPlain doesn’t have an address listed in the endpoint properties.  This means it takes the endpoint address it is deployed within.  Each endpoint must have a different address so to get around this we are going to use relative addresses. 

Open the WCF Configuration Editor by right clicking the web.config file in the project and change the address of the Basic and WsSecured endpoints to the same name.  Here’s what they should look like after you make the change.

image

image

Using relative addresses appends the string in the address field to the end of our service address therefore making a different address location for each endpoint.  For example.  Since we are deploying our service as http://elderville/wcfservice/service.svc, the basic endpoint address will get converted to http://elderville/wcfservice/service.svc/Basic

This is the only change that is needed to deploy this service.  Now right click the WCF project and click “Publish”.  Set the target location to c:\wcftest\wcfservice as seen below and then click publish.

image

Open Internet Explorer and browse to the following URL:  http://elderville/wcfservice/Service.svc.  You should see your service page.

image

Reconfigure Windows Test App

To test the service, remove the existing service location from the Windows test project included in the solution.  Open the app.config file and remove the existing WCF client information (leave just the configuration xml elements).  Right click on the service reference within the project and paste the new address into the address field then press go.  Once it loads the service, press OK to add the reference to the project.

image

Next launch the Windows Application and click on the binding buttons to see the messages going back and forth with your service. 

image

At this point we’ve just setup IIS7 and deployed a WCF service.  Steps 1-3 are now complete.  Now let’s apply a more real world scenario to see what happens.

Breaking The Deployment

Based on our original goals we are now going to break this deployment. This is the real heart of this problem as this simulates a more real world example. 

To break this deployment we are going to add the second host name to the WCFTest site we created.  This is simulating is a shared hosting environment or an enterprise setup where load balancers are used.  Since I created “wordsofwisdom” as my secondary host name I am going to add that as an additional HTTP binding on the application.  This means my application will now answer to two names.

In the IIS7 configuration manager right click the application and edit the bindings.

image

The site’s configured bindings should only have one binding enabled which is the original host name entered when the site was originally configured.

image

Click add and enter the second host name the computer will answer as.  I entered the secondary host name of “wordsofwisdom”.

image

Press OK and both names should appear within the site bindings list. 

image 

To recap what we just configured, we setup IIS7 to answer requests for both of our host names.  Again this isn’t uncommon to have this type of configuration.

Now open the browser and browse to the previous working service.  You should see the error now.

This collection already contains an address with scheme http.  There can be at most one address per scheme in this collection. Parameter name: item

Since there are two names in the HTTP binding section it doesn’t know which one is the correct name to answer and thus the WCF service throws an exception. 

Fixing the Deployment

Depending on the .Net framework you are using the fix is different.  If you are using .Net 3.0 the only thing you can do to fix this is write a WCF custom ServiceHostFactory.   This work around is a little ugly and not something easy to standardize.  My suggestion is to upgrade to .Net 3.5 and take advantage of a new configuration option added in .Net 3.5 to solve this exact problem. 

The fix for .Net 3.5 uses a  new configuration element called <baseAddressPrefixFilters>

Represents a collection of configuration elements that specify pass through filters, which provide a mechanism to pick the appropriate Internet Information Services (IIS) bindings when hosting the Windows Communication Foundation (WCF) application in IIS.  A prefix filter provides a way for shared hosting providers to specify which URIs are to be used by the service. It enables shared hosts to host multiple applications with different base addresses for the same scheme on the same site.

To apply this fix open the web.config file for the service within Visual Studio and within the <system.serviceModel> tags add the following XML:

<serviceHostingEnvironment>
    <baseAddressPrefixFilters>
        <add prefix="http://elderville/wcfservice"/>
    </baseAddressPrefixFilters>
</serviceHostingEnvironment>

Once these lines are added, redeploy the service and refresh the service in the browser.  The error should be gone!

Conclusion

In this walk through we’ve covered a lot!  We walked through how to configure IIS7 and deploy an existing WCF service.  We also looked at the scenario that causes the error that a lot of developers run into when deploying WCF services in various environments.  The moral of this story is be safe and go ahead and plan on adding the baseAddressPrefixFilters tag into your web.config files from now on since you never really know how administrators will configure their servers. 

I hope you enjoyed this walk through.

When Bad UnitTests Don’t Know They Are Good

Posted by Keith Elder | Posted in .Net | Posted on 10-04-2008

3

I was writing a test earlier today  trying to play nice with the red first green later crowd.  When I first wrote my test it showed red.  It didn’t work, this was good.  I went in and wrote what I thought was “green” code.  I ran it and whoops I didn’t mark my dummy class public so the XML serializer blew up.  My test failed again.  I fixed that quicly and ran the test again and it failed again!  I looked at the message and this was staring me in the face.

Assert.AreEqual failed.
Expected: <system.xml.serialization.xmlserializer>
Actual:       <system.xml.serialization.xmlserializer>

Yah.  I’m at a loss too.  Doesn’t this test know that it was suppose to pass?  I feel like Adam Sandler in Happy Gilmore.    “Why won’t you just get in the hole?!!!”. 

Podcasting From MVP Summit Next Week

Posted by Keith Elder | Posted in .Net, Geek Dinner | Posted on 07-04-2008

2

Next week is the MVP Summit.  This is one of the events I have looked forward to the most since I was fortunate enough to go last year. 

MVPs from all across the world descend upon Seattle and Redmond during this week to meet with MVP Leads and product teams from Microsoft.  Someone asked me what it is like and I described it as hanging out in the speakers lounge 24/7 at a gigantic conference. 

image Sunday evening is Party with Palermo.  Jeff’s parties have become a staple event for everyone to gather and have fun. 

Monday we’ll kick off the summit with a registration, a special key note, and some other break out sessions.

Tuesday we’ll be on the Microsoft campus meeting with product teams viewing the new bits and weighing in our thoughts.  Rinse and repeat for Wednesday and Thursday.

image Thursday night is the Geek Lager which is going to be held at Kell’s Irish Pub right off of pike street.  If you aren’t flying out late on Thursday night or will be in the area, stop on by.  You can RSVP for the Geek Lager here as well as get more information.  The Corner Bhoys are playing that night starting around 9:00 PM.  We’ll kick things off around 7:30ish. 

As I mentioned in the title, I am planning on doing some podcasting from the summit.  My goal of the podcast sessions are to capture the real world stories about various technologies.  Thus you won’t hear anything about something that is coming down the road.  If they turn out worthy enough of publication I’ll put them up onto a new domain I have.

.Net War Stories – Tech-Ed 2008 Birds of a Feather Submission

Posted by Keith Elder | Posted in .Net | Posted on 31-03-2008

1

I submitted a Birds of a Feather submission for Tech-Ed 2008.  The title of it is “.Net War Stories”. 

I’ve always wanted to moderate a BOF session at Tech-Ed but just never really came up with anything I was willing to submit.  For the past several days I have been thinking a lot about .Net.  During a conversation after work with a friend last week he said, “I get more out of talking to you in one hour than I would have if I’d spent that time at the computer reading countless blogs and documentation.”  He wasn’t saying that I’m a genius, far from it, his point was that it is the stories I have to tell about this technology or this technology that are the difference.  This is when it hit me, we just need to tell our war stories!  Here’s the session details I submitted.

Within a few years we’ve had a lot of technologies to keep up with on the .Net platform including .Net 3.0, WPF, WFC, WF, .Net 3.5, Visual Studio 2008, Asp.Net MVC Framework, Silverlight, LINQ and soon the Entity Framework. Are you feeling like you are at Information Overload? Don’t worry, we all are! At some point you have to take all these technologies and solve business problems with them. Demos are great but what’s the “real world story” from the trenches? And where do you start? Which ones work, and which ones don’t? This discussion isn’t about marketing and demos it is about the shiny pennies (the good) and the rusty washers (the bad) with these technologies. Bring your .Net war stories to this discussion and help others wade through information overload.

I don’t know if anyone even thinks this would be a great session but I think a lot of people like myself are in information overload.  Maybe this session would help.

At this point I have no idea if the session will get taken by Tech-Ed.  Contact your Senator or Congressman if you think it should be on the list for Tech-Ed 2008.

If you wish to vote for this session you can cast your vote here:

https://www.msteched.com/dEv/voting.aspx