A classic !
We now have an idea of what the front end is doing to build our dataset. So let’s look at what our Webservice and Business Layer will do to accomplish their work. First off let’s start by looking at the Webservice method:
/// <summary> /// Write the truck to a file span> /// for now( database futuristically ) /// </summary> /// <param name="truck">truck dataset.</param> [WebMethod] public void InsertTruck(DataSet truck) { ObjectBuilder ob = new ObjectBuilder(truck); Truck tr = ob.Build<Truck>(); //-- VALIDATE TRUCK -- if (tr.ValidateTruck() == string.Empty) tr.InsertTruck(); }
The first thing we do here is declare a new instance of the OjbectBuilder class. We pass the DataSet truck, into the constructor. We then ask the object builder to build our truck object by letting it know that it has to Build . This method takes in a generic type and returns that same specified type after it is hydrated. We will have a look at the build method in just a second.
So now that we have our object created and hydrated, we check its validity. This method will check datatypes, business rules and so on. If that check passes we invoke the InsertTruck() method, and “Insert” the truck. In a normal application this method would tap the database and insert our new Truck. In our case it just writes the info to a .dat file in C:\Temp.
With all that out of the way we can now check out the ObjectBuilder class. The code can be found by following the link below.
===============================================
CODE: ObjectBuilder.cs
===============================================
Not too complex. The class has a DataSet property, which is set when the constructor is called. This is the dataset that will be used to rebuild our object and then hydrate it. The Build() method is by far the most complex. However, if we examine this method, it too will be simple to understand, and then you can say you used reflection. Before we do all that lets give a shout out to the DNN project, codeproject.com, and adargel who wrote the article.
So let’s get to it and check out what the code does…. line by line.
public T Build<T>()
{
This line tells us that we will be using generics. The method will return a Generic type T, not yet known, and we will specify this generic type when we call the method.
Truck tr = ob.Build<Truck>();
This method call tells us that we want a Truck object built, hydrated and returned. So, with that out of the way let’s look at the first line that does some work.
T entity = Activator.CreateInstance<T>();
This line creates a new instance called entity of generic type T. In our case that type will be Truck. The next half of this line asks for a new instance of this class. This will call the default constructor. So, we now have a new object of type Truck that is ready to be hydrated. The next line:
DataRow row = _dsObjectToBuild.Tables[0].Rows[0];
just grabs the first datarow out of the details table in our dataset.
So, onto the loop(s). The first loop will just itterate through all the properties in our new object. It does so by using reflection.
//-- ROLL THROUGH ALL THE PROPERTIES IN THE OBJECT -- foreach (PropertyInfo property in entity.GetType().GetProperties())
We want to roll through all of the PropertyInfo ( properties ) objects that our new object has. You have to include System.Reflection for this to work. Moving on… the next line:
if(property.CanWrite && property.CanRead)
We want to make sure that we can read and write from and to the property. Small step but a rather important one. At any rate, the next line puts us in another loop! Whats going on!?
foreach (object ca in property.GetCustomAttributes(false))
This line will itterate through all the custom attributes of the particular property. But what is a Custom Attribure? http://www.devx.com/dotnet/Article/11579 . All together now: “Thank you DevX.com!”
Think of custom attributes as properties( attributes ) that can be specified for methods, properties and so on. One common Custom Attribute that you may be familiar with is [Webmethod] . This declares a method in a webservice as one that needs to be exposed. In much the same way we can create our own attributes by inheriting from System.Attribute .
The custom attribute that we are insterested in for this simple example is DatabaseParameter. This will indicate that the current property is one that will ultimately get dumped to the DB. The following line performs that check:
if (ca is DatabaseParameter)
Some may not care that the properties passed from the client app are not columns in the table you will dump the data to. In that case you do not need to check whether or not the values coming back are DatabaseParameters, if that is the case you can exclude the inner for loop and the check. And now… last but not least the most important line:
property.SetValue(entity, row[property.Name], null);
This line actually sets the value of the property based on the value of the particular column in the DataRow ( ie: row[property.Name] ).
So once this is all done executing we have a nice hydrated object ready to return. Once that happens control is sent back to the Webservice and the InsertTruck() method is called. Which in turn drops the object to a text file. Again, in a real world application that data would be dumped to a database. The code for the Webservice and Business Layer can be found below.
================================================
CODE DOWNLOAD: WS_BUILDER.zip
================================================
So, where do we go from here? For anyone following along I would recommend giving the code a shot, so you can see it working for yourself. I plan on posting 2 followups one on CustomAttributes and an explanation of how this particular endeavour is leveraging them, and the second will be on a different setup for you folks that do not like Reflection. I won’t reveal too much but will say this, we will use interfaces and a custom business hydrator for each class.
At any rate that is all for now. Feel free to comment with any questions, or let me know if I missed anything.
So now that we have the basic idea down, we should be ready for some code. We will start by looking at the front end application.
The front end app will have to maintain( or build ) a dataset with the properties of our object. To do this we will need a builder object. This builder object will have to maintain the dataset, allow us to extract it, and add “properties”. The class below should provide a clearer picture.

So what does this mean? The class will have a main method which will add properties to the dataset being maintained. When the Builder object is instantiated it calls the BuildDataSet() method which creates the dataset and so on. So… on with it ! You want to see some code.
==============================================
CODE:: Builder.cs
==============================================
Pardon the link to another file but WordPress was hating on embeded code. At any rate, the first part of the builder is fairly simple. The AddProperty may confuse some. It first creates a string array with as many columns ( properties ) as the column count in the datatable. We then see a rather long if statement. If we are adding the first property ( column ) then we want to just add it, otherwise we recreate the row with the new column. This means that the property set grows lateraly, as such:
————————————————————————
Property 1 | Property 2 | Property 3 | ……….>
————————————————————————
Value 1 | Value 2 | Value 3 | ……….>
————————————————————————
So we will always have 1 DataSet, containing 1 DataTable with one growing DataRow. Now I know that some will complain about having to maintain this set, however I urge you to take the following into consideration 1) The client side code and 2) the fact that looping through columns and moving some values around is relatively inexpensive. So let’s start with #1:
1. The client side code.
( in this instance we want to add a new truck to our database, the truck has four
attributes: Name, Make, MaxSpeed, and MaxTowing)
private void btnSave_Click(object sender, EventArgs e) { Builder b = new Builder(); b.AddProperty("Name", this.txtName.Text); b.AddProperty("Make", this.txtMake.Text); b.AddProperty("MaxSpeed", this.txtMaxSpeed.Text); b.AddProperty("MaxTowing", this.txtMaxTowing.Text); //-- TAP WEBSERVICE AND INSERT -- s.InsertTruck(b.pDataSet); }
( s being the webservice refference )
So what are the benefits? First off you know exactly what value is assigned to what property. Second, you don’t have to deal with passing 10+ parameters to one method. Third, you can run your DataSet against a dynamic business rule engine before making the call( that may be another series ). Last but not least the code is just cleaner. Click the link below to download the Windows Application containing the above code:
============================
CODE DOWNLOAD: FrontEnd_Builder.zip
============================
So now that you have some idea of what the front end is doing we can concentrate on the backend. That will be our Part 3. We will pass the DataSet to the backend, hydrate a new Truck business object and invoke the InsertTruck() business method. Stay tuned…
So my latest posting adventure has required me to post some code and I found myself searching for a utility that would convert C# code to well formatted CSS-ish HTML. That way it can remain all pretty and formatted. I tried search terms such as: sample code generator, sample code designer, sample code to html, sample code editor… etc. The final try “code to html” did the trick. I found the following site:
http://www.manoli.net/csharpformat/
The converter uses a simple CSS stylesheet and injects span elements in the right spots to highlight and color the code. Pretty cool tool. I highly recommend it. Now I just have to figure out why WordPress is hating on me…. or rather the WYSIWYG editor they use.
Everyone always talks about building “Smart Clients”! Well what about building a “Stupid Client”? In today’s day and age it seems that buzzwords rule the market place, so I kind of want to create my own. I am constantly faced with the same question: How do we deploy a Windows Application that can be easily updated even when business logic changes? The answer is kind of simple, and I don’t know if someone has already thought of it. I have a lot of “good ideas” and find that someone else has already implemented them…
At any rate, the point is that as a Manager/Architect/Developer/End-User/Consumer etc. you do not want to have to “update” software often. Deploying new versions of any client software is costly, both in terms of bandwidth (kind of cheap now) and in terms of time, testing, and potential failure upon update. This is the reason that you do not want to let a front end application have any knowledge of the complex types that may be dealt with on the server side. What do I mean? In an N-Tiered distributed application we may find the following scenario:

In most instances the front end client will communicate with our application server through a webservice. Some environments split the webserver and application server, however for simplicity’s sake we will just say that they both reside on the same machine. The client needs to be as dumb as possible. If you build business logic into the client application, even as much as checking a simple value, you will find yourself updating the client to accommodate business rules. In my span as a software developer I find that business moves at blinding speed! Marketing initiatives, competitive strategies and business plans all change so fast that they will make your head spin. So building a “Stupid Client” may help you slow down your software deployment cycles. So how is this achieved? Well one thing that I like about the MVC (Model-View-Controller) model is that it promotes a “Stupid Client”(View). Following link offers a quick explanation:
http://en.wikipedia.org/wiki/Model-view-controller
So with that model in mind we find ourselves looking for a good way to pass data back and forth between our client and the back end server(s). If your client is a Web application you can communicate with the business layer rather easily since that resides on your webserver(depending on your infrastructure architecture). Windows applications are a different beast; they reside on the user’s box. So how do we send mass amounts of information back and forth without letting the client know about our complex business objects? Datasets, reflection and a simple design pattern.
So, to start we will examine the design pattern. The BUILDER pattern moves construction logic outside of the class being instantiated.
http://www.dofactory.com/Patterns/PatternBuilder.aspx
We will use some of the concepts that Builder introduces, although not a true builder.
As I said the builder pattern removes the build logic from the specific class that we need to build. In our case what we will need to do is allow our builder to provide us with a new instance of our business object. Generally the builder pattern provides more specific functionality. We will build a generic builder…
The idea behind our Builder class is that it will rebuild a Dataset into an object, hydrate it, and then allow it to do its work. So how do we go about doing this? The diagram below explains the concept.

With that in mind we should be ready for some code. I am still working on that piece. It is almost done, but it will require a writeup that is equally lengthy. So stay tuned, that will be out in the next couple of days.
I’ve been trying to do battle with the mentality that the more developers the better for a long time. Or the cheaper the better. No other field presents the fact that you get what you paid for better than the software industry. If you hire a high-school kid to develop your website, it will show. If you refuse to hire a web-designer to skin your site it will show. Last but not least, if you offshore your support and software development it will show.
Why do I say this? Many folks are in the mindset that software is like bricklaying, you have a 1000 hour project, so if you hire 1000 people you will get it done in an hour right? WRONG! Software development is more like an art. I know I am not the first to point this out, but think of it this way. Could you hire 100 college aged art studends and produce a masterpiece such as another Mona Lisa? Answer is… No. There are two reasons there 1) None of us are as dumb as all of us and 2) Quantity does not equal quality.
The first point relates to communication issues, group think, and satisficing that group environments tend to produce. If you have ever been stuck in a meeting where you’ve thought “I’d rather set myself on fire than be here!”, you know what I am talking about. Ask yourself this: How productive would my responses be when I am in that mindset? I can only speak for myself, but I know that my answers would be complete crap. This is why a smaller dedicated team will always work better than pulling 40 people into one small claustrophobia inducing room.
So, with that in mind say that you are offshoring a project to a large team or one that has fallen into that trap. Those folks do not work for your company, they do not care about the health of your business or it’s success. The only reason they may try at all is so that they do not lose the contract. At this point we are looking at a bored and disconnected team that we are depending on for IT needs. One great example of such a disaster is Dell. If you think back to waaaay before the “Dude! You’re getting a Dell” stoner commercials, you will recall( I hope ) that they used to advertise their award winning tech support. This stopped. Why ? Because their award winning service and support was handed over to an offshore team that was not interested in Dell’s wellbeing. They were interested in nothing more than the contract.
This becomes bluntly obvious when you start hearing terms like “Dell Hell” when reffering to their tech support. Often times immesuareable quality is lost due to offshoring. In Dell’s instance we see a very distinct impact, however software is very complex. No one can ever measure the complete lost quality due to offshoring a project. Bugs,time, money, maintenance costs can be measured, but what about that dedicated developer that decides to go above and beyond? Being that the piece of code that is being written offshore is something that the original developer may never see again, I can guarantee you that guy does not exist.( Keep in mind that I am reffering to larger firms only, I’m NOT saying there’s no talent in India )
So whats the point? The point is that when you disconnect your team from the project that much, technology only solves the physical problems. Technology cannot create dedication, talent or loyalty. Lately this problem has become even larger as countries that have been getting these offshore contracts are starting to raise rates. ( you know… that whole supply v demand thing… ) I remember reading a figure somewhere which stated that if an organization executed an offshoring venture correctly, they could save roughly 35% of the cost. (Two questions: 1. Is that just the initial effort? 2. If so, what about maintenance costs?) So if those countries are starting to raise wages and demand more, what is the cost savings estimate at now? Also, what is the percentage of organizations that have managed to get that 35% cost savings, or have executed their plan correctly?
The more of these issues you look at the more risk you start seeing. I am not a gambling man, but I wonder what a professional gambler would say about the odds…
1. Group think.
2. A general disconnect.
3. Immeasureable loss of quality.
4. Rising rates and fewer resources.
5. Inaccurate return estimates.
6. Low margin of return… 35% or less.
Starting with just those six cons… does offshoring seem worth it? In my humble and possibly misguided opinion … No. There is a much greater chance of failure or dissatisfaction to all parties involved than there is a chance of benefit. I have taken a few management courses and even elementary management practices will advise against ventures with this much risk. ( That’s not even mentioning the fact that for most executive types software and it’s development process is a complete mistery )
I know some of you may think: “Well I was promised $ 4 million in savings from this venture.” That may seem like a considerable amount, but take another look at Dell’s situation. How many clients did they lose due to their offshoring venture? No one can answer that with a hard factual figure. The only assumption that one could make based on their quality of service is that the losses are staggering… “Dell Hell”… So they may have saved an initial $20 million but lost hundreds. I can tell you of at least one client they lost … me. I loved my Dell laptop when I bought it. It was a high quality machine and the support was excelent. However, within the timeframe that I owned this piece of technology they managed to offshore support, sales and many other departments. What happened when I tried to buy another Dell laptop ? I called them first, got mad & hung up, went to Best Buy( yea yea yea I know ) bought myself an HP Laptop and bought the 3 year extended warranty. Why? Because when I am trying to finish a project and my computer blows up… I WANT HELP AND I’M WILLING TO PAY FOR IT!
Anyway the point to this giant rant is that the risks to offshoring are greater than any benefit.