Archive for the 'Programming' Category

Setting up a FubuMVC Project from Scratch

I am going to start a series of articles on using FubuMVC for web projects. I have several reason for writing these, one of which is FubuMVC has a lack of documentation right now, so these articles will help out that cause. Also I am starting to do mostly web work, and want to do these apps with FubuMVC as opposed to Asp.net MVC. (This is purely for personal reasons).

Upcoming Topics:

Setting up the Bootstrapper and Global.asax
Creating Models, Views, and Controllers with FubuMVC
Adding database connectivity
Using HTML helpers

I will most likely cross post these to the FubuMVC wiki once they are refined and final, so if any of you have comments, ways to do things better, or find things I should explain or do differently, please leave me a comment.

Before You Begin

Before you start your setup, head over to the FubuMVC website, grab the latest version of the source and compile it. This way you will have the references I am using below.

Project Setup

The first thing you need to do is go setup your project and folder structure. I am not going to detail the process here, because most people have thier own preferences and naming conventions but for my sampl I will be using the following folder structure:

  • FubuSample
    • lib
    • src
      • FubuSample.Core
      • FubuSample.Web
      • FubuSample.Tests
      • FubuSample.sln

    You may have noticed above that I am using three different projects: FubuSample.Core (class library), FubuSample.Web (Web Application) and FubuSample.Tests (class library). Setup these projects and we will move on, mine look like this:

FubuSampleProjectSetupv1

Got it, great. Next thing I am going to do is add references required for FubuMVC to work. I added the following references to my projects:

    1. FubuSample.Core
      1. FubuMVC.Core
      2. FubuMVC.Container.StructureMap
      3. StructureMap
      4. Microsoft.Practices.ServiceLocation
    2. FubuSample.Web
      1. FubuSample.Core
      2. FubuMVC.Core
      3. FubuMVC.Container.StructureMap
      4. StructureMap
      5. Microsoft.Practices.ServiceLocation
    3. FubuSample.Tests
      1. FubuSample.Core
      2. FubuSample.Web
      3. FubuMVC.Core
      4. FubuMVC.Container.StructureMap
      5. NUnit.Framework
      6. Rhino.Mocks
      7. StructureMap

Once all the references are are in your 3 projects, you are almost ready to get going. The next thing to do is to setup a basic folder structure inside your projects. In the web project I added a Views folder and a Content folder; under the content folder I added seperate folders for images, scripts and stylesheets. Moving on to the Core project I added top level folders for  Config, Domain, and Web. Under the Web folder I also added folders named Controllers, DisplayModels, Html, and WebForms. My folder structure now looks like this for my projects:

FubuSampleProjectSetupv2-AfterFolders

Next up, setting up the Bootstrapper, Global.asax and Web.config for FubuMVC

TeamCity - Build failed on WPF Unit Tests

I have been working today with Jeremy Millers’ ScreenBinder stuff and ran into a problem today with the tests. The tests all passed fine in Visual Studio, and with rake at the command line on my computer. The problem however came when I checked the code into source control, I got a nasty test failure message in TeamCity:

 

BuildError

Here is the error: Test(s) failed. System.Runtime.InteropServices.COMException : The program issued a command but the command length is incorrect. (Exception from HRESULT: 0×80070018)

So I did some googling around and found there is a bug in the .NET Framework 3.5 SP1 regarding this issue. So a little more work and I found a work around. I believe this bug only pertains to WPF stuff.

 

Workaround

On the build agent do the following:

  1. Stop the TeamCity Build Agent service (Start –> Run –> services.msc –> TeamCity Build Agent –> Right Click –> Stop)
  2. Browse to the service file (C:\TeamCity\BuildAgent\launcher\bin)
    Files1
  3. Right click TeamCityAgentService-windows-x86-32.exe and click Properties
  4. Go to the Compatibility Tab
    Properties1
  5. Click Show settings for all users
  6. Change the Compatibility mode to be Windows XP (Service Pack 2)
    Properties2
  7. Click OK a few times to close all the windows
  8. Start the TeamCity Build Agent service.

You should now have a working build with WPF unit tests. Hope this helps somebody out as I was banging my head on the wall trying to figure it out.

Success01

CSLA - first base was fun, but I want a relationship

The scene opens on a typical fall Saturday evening at the local sports bar filled with enthusiastic football fans cheering loudly at the myriad of TV screens scattered around. In one small corner sitting around a high table is a group of people visiting about software development. Two guys, eager to make friends, walk up introduce themselves and let slip they’ve been developing software with CSLA for the past few years, and are looking for redemption.” The rest of the table then looks at each other and responds in chorus, “I’m Sorry!”

 

The shock on their faces at the collective “I’m Sorry” was a bit much. They knew some people have very differing opinions about different frameworks and tools, but hearing it confessed out loud was a breath of fresh air.

Recently our development team decided to stop developing with the CSLA framework. Before I get into specifics, I want to be very clear about something up front. I have no problem with people that continue to use CSLA. We used CSLA for nearly 4 years and it has worked in way it was designed.

 

While Hiren and I were at KaizenConf in Austin we made sure to find a few minutes each evening before getting caught up with a large group, to recap the day and share some new things we each learned. One of these nights while relaxing and evaluating what we’d been learning we came to the conclusion that it was time for us to step away from new development with CSLA and migrate existing codebases as well. Over the past week we have been outlining and discussing these ideas and why we have made the decision to move away from CSLA.

 

It all started a few months ago when we first started getting introduced to the Alt.Net ways of developing software. What I mean by the Alt.Net ways are things like S.O.L.I.D. principles, ORM use, unit testing, Domain Driven Design, Mocking, TDD, etc… All of this has really changed the way we think about and develop software. Even before this though Hiren and I made a very dangerous combination of developers because we are never satisfied with a piece of code once it is written, we usually have to talk one another into just leaving it alone because it works and is as good as it needs to be to get the job done.

 

There are several driving forces behind this decision, but the primary one is that our CSLA business objects just leave a bad taste in our mouth. Our systems are moderately complex and it is not uncommon at all to have a class with 1500 – 2500 lines of code, in fact that is probably an average line count in most business objects. The other thing that really smells to us is that the “model” contains a lot of stuff that is not directly related to the model, namely data access.

 

I would like to take a minute to point out some of the things I really like and will miss about CSLA, and some of the other reasons for making the switch.

 

 

CSLA, I will miss some of you:

  • Validation Rules System
  • Data binding Support
  • Combo of these == reach UI validation for user
  • Good set of guiding principles and samples to get started with.
  • Rocky’s Books!

I won’t miss these parts though:

  • Data Access code in business object
  • Difficult to mock out data access in mocking
  • N-Level undo – I never, ever used this but had to contend with it, like it or not
  • “Super” Classes

These are purely my opinion so take them as they are. I still think CSLA has a place for some people and unlike others I have run into on the internet, I will not bash you or think you are stupid for using it. CSLA was an excellent stepping stone for us; it introduced and really engrained the Object-Oriented Programming style of thinking into our minds. I/we just feel like we have matured to a new level of development through better understanding of our software development process and how apply those skills to our situation.

 

We are still learning and don’t yet know exactly what our development style is going to be end-to-end on this project. We have a long way to go before we are completely comfortable with all these new tools. Luckily, the Alt.Net community seems to be an open and accepting group and nearly everyone is willing to help us out along the way.

What I do know is that no team can just take what one person or one book says and do it that way. It won’t work. What we are doing is educating ourselves on different practices and tools and using what works for us, we do a lot of spikes right now. We are also building our domain model with POCO’s which gives us a great amount of flexibility in the infrastructure and presentation layers of our system. As we continue this process I will post successes and failures here on my blog.

Strongly typed Collections of Abstract Objects

Some of you know that we are in the process of not using Csla anymore, this is a decision that just seems logical for us, but that is another post. I need a little help implementing a problem in my domain. Now the sample I am posting is out of a dumbed down version I have been using to spike with. Take a look at the following class diagram and then I will explain what is going on and what my problem is:

Order-ClassDiagram01

What is going on here you ask? Order is the primary object type, but it is abstract. I have maybe 7 different types of orders, service order, make order, repair order, etc… each order has several attributes that are always present on every order. What makes each order unique is the attributes that are not shared between all orders. This is why I have decided to use inheritance.

One of the items that are common between all types of orders is that they all have many parts. However, I want the base Order class to have a collection of base OrderPart objects. OrderPart is the mapping object in between Order and Part for the Many To Many relationship, I am using an object because this association has state of it’s own. Now to complicate matters even more, each concrete Order can have a different concrete type of Part and OrderPart assigned to it.

I have the model all setup and Have written some tests against it as I wrote it, not really test first but hey, I am spiking here. So below is one of the tests that shows most of this in action.


public void CanCreateOrderWithCustomerAndParts()
{
var order = new CustomOrder();
order.Customer = new Customer
{
Name = "John Smith",
Address =
new Address
{
Street = "45623 Easy",
State = "TX",
City = "Dalals",
ZipCode = "73884"
}
};
order.OrderNumber = "Y984939";
order.Amount = (decimal) 1234.33;
order.CustomOrderDescription = "Testing adlkfjl 123";
order.Parts =
new List
{
new CustomOrderPart
{
Part =
new CustomPart
{
PartNumber = "Part456sdf34",
Description = "Test Partasd 87",
CustomPartText = "TEST",
},
Quantity = 12
},
new CustomOrderPart
{
Part =
new CustomPart
{
PartNumber = "PARTWITHNULLPULLLOCATION",
Description = "Test Part 848sasd8243",
CustomPartText = "TEST",
},
Quantity = 251
}
};

With.Transaction(() => Repository.Save(order));

Order createdOrder = Repository.Get(order.Id);

Assert.IsNotNull(createdOrder);
Assert.AreEqual(2, createdOrder.Parts.Count);
}

Don’t make fun of my test code, like I said, it’s a spike. But when I create a CustomOrder I am creating Parts as a new List<OrderPart> which is how it is implemented. But then I had new CustomOrderParts and CustomParts into that collection. NHibernate will persist this information correctly into the database and will retrieve it correclty from the DB. So seemingly all works fine right, sure I guess. Maybe it is just because I have been in Csla land so long that I don’t know any different but what I am really missing is being able for the concrete order object to know what concrete type of  OrderPart is contained in the parts collection. As I wrote that I just kicked myself, if that isn’t a violation of Seperation of Concerns I don’t know what is, or is it? I mean Order or a concrete Order is basically an Aggregate Root in DDD terms so it is the responsible entry point into the chain/web of objects that make up the aggregate.

So, for my real question which I am not sure of now, How would you tackle this design problem? How do you handle child collections? Am I just way off the reservation?

NHibernate Caching Explained, finally!

Gabriel Schenker has just posted an excellent article explaining in detail how to the 1st and 2nd level cache in NHibernate works. This is a long overdue article on caching that will greatly benefit the community. The article also explains the differences between Get(id) and Load(id) when retrieving entities through NHibernate. I am recommending this article because it is an in depth look at one of the pieces I covered earlier on Ayende’s session from KaizenConf.

LEAN -Software Development in Small Teams - Part 2 – KanBan Board v1 - v2

In the first part of this journey I posted about two value stream maps we created. The next step after doing Value Stream Maps of our two primary processes was setting up our KanBan board. I would first like to explain some of the thought we put into setting up our KanBan board. During our discussion on KanBan in Small Teams Dave said to not over complicate your KanBan board, and I agree. Especially for smaller teams there is no need to have a 15 state KanBan board. So what Hiren and I cam up with is shown below:

KanBan-BoardV1

What we have is 3 states for a task to be in: Backlog, Work In Process (WIP) and Done. I think there are several important parts to our KanBan board:

  1. Limits– Notice there are limits on the first two columns (Done is a feel good state, no limit), this is to create blocks when necessary and to prevent a state from filling up with a pile of inventory as is possible with other methodologies. The limits are in place to effectively block processes up stream from piling up. When a state is blocked no other work can be performed in that state.
  2. WIP has two tracks – We are a small company so we are developers and IT guys both so we decided we should leave a spot open in WIP for an IT task. I am thinking about making it so that if a Red IT task is in the slot then that “Stops the Line”, a Red task would be an emergency or super high priority that was really preventing any other work from being done.
    1. I decided to keep the WIP limit at 2 thinking that we won’t have an item in IT very often and if we do someone is probably not working on a Dev item anyway.
  3. Standard word definitions / Constraints – Below the bottom horizontal line is where we list the standard work definition or other constraints that are associated with each state.

So this board is setup and we were just about ready to start using it when I started watching the video from the open spaces session Chad uploaded on viddler, see KaizenConf Article. When I got to the point we were talking about laying out boards I realized I had forgotten a column. So we will call the board above v1 and the one below v2.

KanBan-BoardV2

In version 2 we have added a column between WIP and Done called Deploy. My thought behind this was that we don’t do release per feature, yet, and we also don’t have a set release schedule but what I want to do is release features in batches of about 3. So the standard work definition for deploy is if there are 3 or more tasks/features in this state then we should schedule a release. I don’t have it in the picture but I am going to have a limit of 5 or 6 on this state.

We are going to run with this KanBan board for a week or two and see if we need to make further improvements on it in that time. If we do I will post them up here, if not then I might make the lines a bit more permanent so they are straight.

Next up I am going to discuss the layout of our KanBan cards.

I have also lost my virginity (and you should too)

UPDATE: I have lost my virginity in regards to attending my first software conference, just in case that wasn’t clear… you know who I am talking to.

I just read Brian Mavity’s latest post and am obviously rowing the same proverbial boat that he is. This is not only my first software development conference but the first software development conference our company has ever sent anybody to. I personally have already taken more away from this than I ever imagined. Just sitting around at dinner or socializing with the same people whose blogs I follow is somewhat intimidating, but they are all very welcoming and want to help us new guys get going. I have had conversations (okay, mostly absorbing) with Ayende, Chad Myers, and Jeremy Miller. I have also been able to speak one on one with others and will most definitely get the opportunity to do some more.

Same as Brian Mavity, if you your company does not care enough about their development team to spare a little time and money to get you involved, you should consider finding a place that does or making your voice heard better to accomplish this.

I am really looking forward to the next few days worth of activities.

KaizenConf Workshops – Advanced NHibernate

As some of you know I am attending KaizenConf for the next few days. I am going to use my blog as my notepad as I take notes during different workshops and sessions. My note taking skills sometimes have a lot to be desired so be patient if these notes look very sketchy. I will try my best to come back through and make sense of them later.

Advanced NHibernate

I am currently sitting through Ayende’s workshop on Advanced NHibernate and there is some really good stuff going on here. Three of the topics I have found most interesting is Multi-Tenancy, Full text indexing with NHibernate Search, and caching with NHibernate. NHibernate search is a project that combines Lucene, a proven java index tool, and NHibernate to alleviate strain on the database engine by keeping indexes on disk and performing queries on that data faster. Indexing is accomplished by decorating entities with attributes. Of all these topics caching with NHibernate has really grabbed my attention as it probably has the greatest results for the applications I am currently working.

Caching with NHibernate

1st Level cache –Contains Identity Map – Session – Single instance of an object in a particular session

2nd Level Cache – contains the SessionFactory – lives for the entire application lifetime, it also has 4 levels of cache within it:

timestamp
query cache
collection cache
entity cache

 

Caching Configuration

Enable query cache <property name=”cache.use_second_level_cache”>True</property> in NHConfig – A single on off switch in the application to enable/disable caching is not a good solution because caching is complex and could affect business rules and performance. So you have to enable caching for a specific entity by using Cache_usage = CacheMode (ReadWrite for Ayende’s samples) in the entity mapping file. The NHibernate cache hashtables are stored like below:

Entities Cache:
————————-
Blog#1 : { Name: “…”}
Post#1 : {…}
Post#2 {…}

Collection Cache
—————————
Blog#1.Posts { 1,2,3,4,5,6} – stores id’s only

Query Cache:
—————————
“select top 5 * from Post” : {1,2,3,4} // stores id’s only

Ayende used his blog sample for all of the code examples today. When he put caching on the Blog, and the collection of posts in the blog map and on the post entity the fewest calls to the database occurred. To enable query caching the property cache.use_query_cache = true in the config file.

Session.Load vs Session.Get

Load == I know the entity exists in the database, it returns a proxy to the object. Throws an exception if the object is not lazy loaded and cannot be found.

Get == NH really goes to the database and fetches a row or throws an exception if it does not exist.

Which one of these to use depends on the business rule for the entity.

 

NHibernate Contrib project descriptions

NHibernate cache libraries:

PrevelanceCache – persistent caching for smart client applications

SysCache – using ASP.net caching – gives it the ability to put things in the cache and forget about it – only works if you have one machine.  Other wise you get cache poisoning.

SysCache2 – ASP.net caching in the farm – maybe application is not the only thing that updates the database. This is good when the application is not the sole owner of the database.

MemCache – a distributed hashtable, thats it basically it is distributed caching.– Server sitting on TCP with a hashtable – the Client caches the key and always goes back to same server in farm for cache retrieval. Very simple, works very well. This is also known as MemCacheD and is the same caching strategy that Facebook uses.

SharedCache – SharedCache from CodePlex

Velocity – From Microsoft – more complex than memcache, more options but they validate the cache space you have.

 

Other NHibernate Contrib Projects

NHibernate.Linq – pretty good, handles most of the common scenarios, does not handle the crazy scenarios that are capable in LINQ. Currently working on a fully functional LINQ library.

NHibernate.Validator– Just as you can specify constraints in SQL Server. You can specify constraints in your mapping file and the validator will validate that for you.

Spatial – GIS applications

Shards – partition the data across multiple db’s – written by Google to deal with problem of having multiple database. You can teach NHibernate a sharding strategy so that it knows which database to use. This is a strategy that is used by companies such as Facebook.

 

Another very interesting topic Ayende talked about is self optimizing queries. This would be used by session.Future<TYPE>() you could use this in your repositories on all lists/CreateCriteria methods. This creates a MultiCriteria which returns multiple result sets in one database trip. This is very similar/exactly like multiple result sets in stored procedures.

IRepository Code

This is by request from Frank Mao, he was wanting me to post up the code I am using for IRepository<T> so here it is:


public interface IRepository<T>
{
//IList<T> FetchList();
ICriteria CreateCriteria();
T Get(object id);
void Load(T obj, object id);
void Delete(T entity);

void DeleteAll();
void DeleteAll(DetachedCriteria where);
T Save(T entity);
T SaveOrUpdate(T entity);
T SaveOrUpdateCopy(T entity);
void Update(T entity);
long Count(DetachedCriteria criteria);
long Count();
bool Exists(DetachedCriteria criteria);
bool Exists();
IList<T> FindAll(DetachedCriteria criteria, params Order[] orders);
IList<T> FindAll(Order order, params ICriterion[] criteria);
IList<T> FindAll(Order[] orders, params ICriterion[] criteria);
T FindFirst(params Order[] orders);
T FindFirst(DetachedCriteria criteria, params Order[] orders);
T FindOne(params ICriterion[] criteria);
T FindOne(DetachedCriteria criteria);

ProjT ReportOne<ProjT>(ProjectionList projectionList);
ProjT ReportOne<ProjT>(DetachedCriteria criteria, ProjectionList projectionList);
IList<ProjT> ReportAll<ProjT>(ProjectionList projectionList);
IList<ProjT> ReportAll<ProjT>(bool distinctResults, ProjectionList projectionList);
IList<ProjT> ReportAll<ProjT>(ProjectionList projectionList, params Order[] orders);
IList<ProjT> ReportAll<ProjT>(bool distinctResults, ProjectionList projectionList, params Order[] orders);
IList<ProjT> ReportAll<ProjT>(DetachedCriteria criteria, ProjectionList projectionList, params Order[] orders);
IList<ProjT> ReportAll<ProjT>(bool distinctResults, DetachedCriteria criteria, ProjectionList projectionList, params Order[] orders);
}
}

I should note that this is a slightly modified version of IRepository that I got from the UnitOfWork tutorial code that is posted here: http://hibernatingrhinos.googlecode.com/svn/trunk/UnitOfWork/src/NHibernateRepository/

Csla Project Tracker + ObjectFactory + Altdotnet = Goodness

I will start off by giving my regular disclaimer, I am not an expert on this, however, I am also not an idiot either.

 

How It Was

 

We have been using Csla as a business object framework for about 3 years now and have had good results with it. That and we like things to just work and it does. Now a few months ago we started to get introduced to the altdotnet way and have seen the light and the need for many of the principles of altdotnet in our organization, it just makes sense. A few weeks ago Rhockford Lhotka release the beta version of Csla 3.6 and with it he has introduced support for an extensible ObjectFactory. This custom ObjectFactory takes the place of the DataPortal_XYZ() methods in the business object.

 

Now with the old way I had to make an object and write at least 3 lines of data access code for every property. This is cumbersome and just plain stinks. But good news! There is a better way.

 

The Better Way

 

So with this new ObjectFactory in Csla I can now spread some altdotnet goodness into my Csla projects. To be more specific here is what I have done, this has increased the dependencies of the project but has made the code much more flexible and easier to test.

Hopefully this little overview has intrigued you enough to go download the source code for the Csla sample redone with an ObjectFactory implementation. The source code and zip file are available at http://code.google.com/p/cslaptrackerfactory/ I will update the repository as I make changes/ additions to the code. I have created this as an open source project because I know that my method is not the only method and hopefully we can collectively come up with a way to use Csla with altdotnet goodies in a more standard way. So with that said, if you want to join the project, drop me a line.

 

I will post more articles that go in depth on how/why I did things a certain way in this project later, I hopw.

Next Page »