Thursday, May 7, 2009

The Provider Factory Pattern

At our weekly tech lunch we watched Jean-Paul Boodhoo on Demystifying Design Patterns Part 1 on dnrtv.com and he showed us how to use the "The Provider Factory Pattern" which is basically using a factory to give a data provider that is completely abstracted away from the database request methods that use it.

This is some very cool stuff basically you have a factory that provides a methods for getting a connection
public IDbConnection GetConnection()
{
IDbConnection connection = _frameworkDBProviderFactory.CreateConnection();
connection.ConnectionString = _authenticationSettings.ConnectionString;
return connection;
}

though an interface so you can call any type of Database who's connection object implements the IDbConnection interface (SQLServer, MySQL, Oracle, etc.) (see full source)

To use this you create a request method
public bool AuthenticateUser(string userName, string password)
{
bool success = false;
DataTable requestTable = new DataTable();
using (IDbConnection conn = UserDataProvider.GetConnection())
{
conn.Open();
IDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "select UserName, Password from users where UserName = @Username and Password = @Password";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(UserDataProvider.AddParameterWithValue("@UserName",userName));
cmd.Parameters.Add(UserDataProvider.AddParameterWithValue("@Password", password));
IDataReader reader = cmd.ExecuteReader();

using (reader)
{
requestTable.Load(reader);
}
}
if (requestTable.Rows.Count==1 )
{
success = true;
}
requestTable.Dispose();
return success;
}

The request method can open this connection, pass in your ANSI SQL query, parameters, etc. then execute it. (see full source)

The Method doesn't know or care what kind of data base it's talking to, additionally starting in the 2.0 framework you can pull the type of Database from the connection string configuration so all you have to do is have the database client lib included in your project and your good to go.

Friday, April 17, 2009

Continues Integration with Team City

At Netdug last night the subject was continues integration with Team City, so I finally got the opportunity to see a continues integration server in action. As a demonstration the presenter had RoboDojo (created by David Star of Elegant Code) David committed a change to his project to on codeplex and with in a few minutes the project built, ran his tests, etc.

Inspired by this my project tonight was to set up Team City. The Installation was fairly simple, I set up my Sample Project, using the sln2008 builder output to a virtual directory in IIS so I can check the output for both the webforum and webservices. Everything just worked until I tried to get the mstest to run the unit tests. It kept failing to run the unit tests, but didn't tell me.

This bothered be a little, after searching online for a while I couldn't find anything but how to do it with msbuild, or with one of the other builders. Finally after playing around with the setting I found that I could get the mstests to run if I used an older nunit test runner that supported both nunit and msunit, and honestly I really like doing that way I only have one place to add test projects.

So what I was expecting to be a 30-60min project tuned into a 3 hour project, but in the end, it really wasn't that bad, the only major complaint I have now is that Team city is kind of a memory hog (it's written in java, go figure) so I don't think I can really run it on the same box I do development on, but it wasn't designed to.

My eventual goal is to do continues integration at work, but I think that's going to be a hard sell right now, so I'm starting off with built deployments, this way I can show the benefits of doing this, then work on getting continues integration. Now that I have the proof of concept done, I can give a realistic time line on how long it would take to set this up at work.

Monday, April 13, 2009

Rolling your own Mock Objects

One of the problems I have with doing unit testing is the mock objects. the principal is simple enough, I create an object that implements the interface I'm trying to mock, the only problem is I end up creating a least 2+ mocks for every class I'm trying to test. I could use something like Rino mocks but there may be some company policy against using open source, or you just don't want to keep it as simple as passable.

Talking to another developer about this he pointed all I needed to do was to give my mock objects some state to handle what passes or fails; BRILLIANT!! why didn't I think of that. So I took the base class

I added 2 collections:
  1. A Collection of string to handle messages added by the various mocked methods to tell the unit test what has occurred
  2. A second collection of strings to to tell the mock to fail and on what methods based on messages passed to the mock object
public class BaseTestRequest
{
public Collection Messages { get; set; }
public Collection FailOn { get; set; }
private string _currentMessage = string.Empty;

public string CurrentMessage
{
get { return _currentMessage; }
set
{
_currentMessage = value;
Messages.Add(value);
}
}

public BaseTestRequest()
{
Messages = new Collection();
FailOn = new Collection();
}

public bool WasSuccessful()
{
return (!FailOn.Contains(_currentMessage));
}
}
Then I can mock an object like this
public class TestAuthenticationRequests : BaseTestRequest, IAuthenticationRequests
{
public bool AuthenticateUser(string userName, string password)
{
CurrentMessage ="AuthenticateUser";
return WasSuccessful();
}
}

to see the full code with comments check out this Sample Code from the sample project.

Sunday, March 29, 2009

Sample Code Project

At code camp I was asked about N-Tier Design, so I referred the individual to my blog post about it and they left a comment asking if I had a sample project to show off how to do it. This got me thinking about the best way to show the what and how of the stuff I'm doing.

The solution, A sample code repository, so if you look on the menu under "Subscribe" you will see a link to the Sample Code Repository. This will be an evolving project showing off new things I've learned and some best practices. It is not intended to be a production application, just a collection of sample code in the form of a project to show what I'm blogging about.

Please feel free to comment (good or bad) on what I'm doing, I feel I'm going to be doing a lot of refactoring on it.

Saturday, March 28, 2009

Boise Code Camp

Attending the Boise Code camp today and thought I would blog about it

Please keep in mind that a lot of this was notes taken during the sessions so they may be a little disjointed, I tried to clean them up as much as I could.

Keynote: Bob Lokken
Bob talked about the global economy and the local economy and how it affects the software industry in the treasure Vally. The short version we need to further education, basically if you have software developers the jobs will come, or the software developers will create the jobs themselves.

Session one: Test Driven development using ICO and Mocks Part 1
Basically we Covered the importance of unit testing, why to use interfaces, and starting to cover Mocks, this was a really simple entry level explanation of TDD and why to use it.

Session two: Test Driven development using ICO and Mocks Part 2
We started with covering context specification, so basically creating test to verify your objects are following the specification requested by the customer using nunit.

So basically you have an E-Commerce site with the following requirements
  1. Returns a success or fail for each request
  2. Order status should be submitted
  3. credit card should be billed the total amount of the order
  4. Customer should be notified when they place an order

So for doing these test all we really care about is if the requirement is fulfilled, not if the logic is correct

  • For requirement 1 we are testing then when we make a request we are returned a pass or a fail
  • For requirement 2 we are testing that when we submit an order the status gets submitted as well.
  • For requirement 3 we Mock the credit card interface so we can tell if the credit card interface was called without billing the card.
  • For requirement 4 we Mock the Notify interface that the code calls the notify interface, just like we did for Requirement 3.

With all of these we are using a naming convention that describe what it is we are testing for, an example for requirement 1 is "When_request_return_pass_or_fail" this tests for exactly that and only that.

Next we talked about the "no time for testing Death spiral" so basically you don't have time to test, the less you testing you do the more bugs you have so the less time you have for testing.

Lunch:
Hung out with the guy's from The Network Group

Session 3: Introduction to Inversion of control
The first thing to do is follow the solid principals, basically the same stuff that Uncle Bob talks about like "Single responsibility Principal", "Dependency inversion Principal" etc.

We covered the IOC concepts using the Unity IOC. The IOC frameworks let you specify the type of lifespan, so you can create a Singleton or multiple instance, etc. with out having to alter your code to make it a Singleton.

Some points of interest where that constructors should not take domain objects, they should only take interfaces that allow them to talk to other layers. When using IOC for the most part you should really only have one constructor, if you have more then you need to set up hints in the code to specify what constructor to use.

An interesting thing we covered was that you can create an IOC in 15 min or 6 months depending on what features you want it to have.

Constructor injection vs configuration injection
Using Constructor inversion tightly couplings your code with an IOC container, in configuration inversion you can make this hot swappable.

An interesting comparison is that an IOC is basically like a super class factory, look into logging injection with castle Windsor

Session 4: Microsoft Extensibility Framework (MEF)
Extensibility allows your application to extend from the base functionality, like allowing 3rd party plug-ins, MEF allows you to add additional functionality after compilation in a standard way.

An example would be to add additional functionality like new features to a web service with out having to compile the web service. You simply add a plug-in dll and you get a new request option . MEF came about because there was no common plug-in framework in dot net, or Microsoft in general, MEF was created to solve this problem.

MEF plug-ins have imports and exports, this allows plug-ins to look for what they need and what this plug-in provides this is all done with the Catalog. The catalog manages what plug-ins are available, and what there requirements are.

You can set the default to handle passable conflicts, for example if there are multiple plug-ins that implement the same interface, and your code requests only one, it will explode because it doesn't know which one to use, unless you specify a default, in this case instead of blowing up it will use the default.

You can cache the meta data so you don't have to reload the assembly every time you want to look at the avalable plug-ins so you can lazy load the assembly only when it's requested.


Session 5: ASP.NET MVC in the real world
Started with a basic tutorial on how to create a MVC web app (a list of robots in a robot army) , covering creating a list view, routing between views, how to handle exceptions by doing redirection, etc. One of the nice things about ASP.NET MVC is it has templates for a fair amount of the basic code for you, like lists, edits, details, etc.

One of the short comings of mvc out of the box is it isn't type safe, keep that in mind for when you change routing, it will create magic strings, this can be fixed but you have to explicitly do it.
Something else you need to do is protract your self from spoofing http posts. One way to get around this is to create a view object that only contains information you want to have submitted and then validate that data map the view object to the real object and then saving the real object, there is also an anti-forgery option to prevent sending bad data.

The MVC pattern allows you to create a single responsibility witch allows testing of the code, you can do this with asp.net forms but it's really painful, where mvc makes it a lot easier.

Some things the presentor sugested we look at are
  1. MVC code from codeplex http://www.codeplex.com/aspnet
  2. S#arp Architecture http://www.codeplex.com/SharpArchitecture
  3. CodeCampServer.com http://code.google.com/p/codecampserver/
  4. FUBU MVC http://code.google.com/p/fubumvc/
  5. NEW MVC BOOK (Free Chapter)
  6. Scott Hanselman MIX - "NerdDinner"

Session 6: Event Driven Programing using Delegates
Basically this allows different parts of your application to know indirectly what is going on in different parts of your application by subscribing to events.

This allows for a decoupled design that allows you to spin off a thread when an event is raised, with out the object that raised the event knowing or caring about what is going on with the event handlers. A good example of this is the asp.net web forum when you create event handlers for the onPageload or onButton_Click, etc. The event raiser (web forum code) doesn't know or care if anything is subscribing to it, but if something is then it executes the subscriber


//Sudo Code
...
Button1.click += new ButtonHandler_Click(eventHandler);
...


then runs the ButtonHandler_Click method

Closing and Giveaways:
I won the DevExpress Refactor

All in all it was a really good experience