No, NSK is not (about) Northwind

So it seems my pet project has been Ayende-ified; Oren has been so kind to let me have a preview at his posts and that urged me to talk a bit about what NSK is and what it is aimed for.

I started NSK in 2004 in order to have a “one size fits all” demo for the talks and classes I and my colleagues at Managed Designs were holding; all I wanted was a way to showcase topics such as:

  • How an O/RM works (Unit of Work, proxies, queries & fetch plan management, …)
  • How to implement common presentation design patterns (MVC, MVP, …)
  • How to unit test code

Other than having that demo, I also wanted to make everyone able to have it up & running as frictionless as possible, so I:

  • Made it open source (choosing IBM’s OSI-approved Common Public License) and downloadable from Sourgeforge
  • Had it use the “ubiquitous” Northwind database

I knew from the start that such a db would have impaired my ability to design an effective Domain Model, but I didn’t care ‘cause that was code that I was expected to show (and comment), and not targeted to the casual downloader.

Let’s just have an example: in order to allow me to explain how an O/RM works and avoid early adopters (remember, we are talking about year 2004/2005) fear for “O/RMs black magic”, I defined both a IUnitOfWork interface and my own query object, and then implemented both delegating the real work to NHibernate. I even implemented proxies for a couple of entities in order to show how O/RMs manage concurrency. Frankly, I did not pay much attention to my implementation of UoW/query object/proxies, because that implementation wasn’t neither expected to go live in a “production” system nor looked at as an advice to encapsulate an O/RM. That “poor man’s” O/RM, let me stress about that, was only meant to allow me to talk about how an O/RMs works without having to resort to NHibernate source, which IMHO would have been overkill. And when DLINQ Linq 2 SQL came to us, I renamed the IUnitOfWork interface to IDataContext in order to better adhere to .NET’s emerging jargon: again, I was only trying to have a “companion demo” which fitted my own presenting needs so, when the “pioneering era of O/RM” relating to the .NET community ended (which, IMHO, happened with Microsoft releasing L2SQL and then EF) I considered my “introduce O/RMs by explaining the inner workings” strategy obsolete, made a branch for those still interested in having a look to that code and had NSK switched to the LINQ side of the Force.

And then came the book (to which, BTW, both me and Dino refer to as “the brick” <g>): we needed a companion demo, and ultimately chose to use NSK so I had to fit into the codebase a bunch of samples covering nearly all the book’s topics, such as:

  • The book talks about IoC and unit testing, so I ended implementing custom factories for both ASP.NET MVC (which at the time was in the “v1 beta” timeframe) and WCF in order to inject dependencies and/or mock objects
  • the book talks about validation and we wanted to show the capabilities of Enterprise Library’s Validation Application Block (which I still think is pretty gorgeous), so I did put in demos using both the custom attributes and the xml rulesets to validate the domain model

Again, the codebase was intended to be looked at while being guided by the book and not as a fully fledged application (please note that NSK still does not sport a release) or as an example of how to implement a Domain Model. If you look to NSK this way, you will find a lot of thing you would do very differently in a “real” application. Just to make an example: you have a look at the CalculateTotalIncome() method of the Customer class and find the following, pretty sub-optimal, code:

   1: public virtual decimal CalculateTotalIncome()
   2: {
   3:     Contract.Ensures(Contract.Result<decimal>()>=0);
   5:     decimal income = this.Orders.Sum(o => o.CalculatePrice());
   6:     return income;
   7: }

In a “real world” application, should the evaluation of the total income be a mere sum, I’d have the O/RM generating a proper query. But, for the sake of the project, I only wanted both a mockable customer repository and the above shown method in order to set up a unit testing demo for the following service:

   1: public virtual decimal CalculateSuggestedDiscountRate(string customerId)
   2: {
   3:     Contract.Requires<ArgumentNullException>(customerId != null, "customerId");
   4:     Contract.Requires<ArgumentException>(!string.IsNullOrWhiteSpace(customerId), "customerId");
   6:     Customer customer = customerRepository.FindById(customerId);
   7:     decimal income = customer.CalculateTotalIncome();
   8:     decimal discount = 0;
   9:     if (income > 5000)
  10:     {
  11:         //Suggests a 6% discount if income>5000USD
  12:         discount = 0.06M;
  13:     }
  14:     else
  15:     {
  16:         //Suggests a 1% discount for every 1000USD of income
  17:         discount = income / 100000;
  18:     }
  19:     return discount;
  20: }

This way, I could write down the following test:

   1: [TestMethod]
   2: public void Test_Calculation_Of_Suggested_Discount_Rate_For_Customers_With_Total_Income_Of_Less_Than_5000_Dollars()
   3: {
   4:     decimal generatedIncome = 3500;
   5:     string customerId = "FAKE1";
   6:     var custMockBuilder = new Mock<Customer>();
   7:     custMockBuilder.Setup(c => c.CalculateTotalIncome()).Returns(generatedIncome);
   8:     var repoMockBuilder = new Mock<ICustomerRepository>();
   9:     repoMockBuilder.Setup(r => r.FindById(customerId)).Returns(custMockBuilder.Object);
  11:     MarketingServices svc = new MarketingServices(repoMockBuilder.Object);
  12:     Assert.AreEqual<decimal>(0.035M, svc.CalculateSuggestedDiscountRate(customerId));
  13: }

To cut a long story short: the reader should look neither at the CalculateTotalIncome nor at the CalculateSuggestedDiscountRate service per se, but at the unit test. Think about it as a MSTest + Moq demo, and maybe you’ll get the picture I wanted to give to the reader. Being the code targeted at someone who has attended a class/talk or read the book, I thought there was no way to have someone misunderstanding the scope of the project.

The same goes for the domain model at large: if you take a look at it, you’ll notice that aggregates encapsulation is pretty low; I just managed to:

  • define an aggregate root abstraction (the IAggregateRoot interface), and built an eco-system aware of it (i.e. the repositories which uses IAggregateRoot explicit implementation and code contracts to enforce domain logic)
  • have the aggregate roots implement factories in order to prevent bad instantiation to happen (builder pattern anyone?)
  • encapsulate some navigation properties having the domain model “users” forced to use domain logic (i.e. the, AddProduct method of the Order entity which is the only way to add a product to the order… or avoiding that, from a domain logic perspective)
  • added a bunch of domain services (i.e.: GetRelatedProducts, CalculateSuggestedDiscountRate, …) in order to show the differences lying in implementing domain logic within the model and/or by means of services

Again, that was enough for my own needings; demo after demo, technology after technology (code contracts, entity framework POCO mapping, jquery, MVVM) NSK grew up and nearly became the “one size fits all” demo I needed in my talks. Up to late 2010/early 2011, I only managed to update NSK in order to remain useful for my own needings.

All of a sudden, though, “developing” NSK wasn’t fun anymore so I settled down and asked myself what I wanted to do with it; my answer was: “make it a real application under the form of an Amazon-like e-commerce web site”. That would have justified the complexity DDD kicks in and also (hopefully) make the project a foundation for solutions we build at Managed Designs. I opted to go for the CQRS way and started focusing of the front-end: so I quickly implemented a read model and started implementing a couple of user stories only to define a structure for the project (architecture, file system, NuGet-based pre build actions, …), only to discover that such a project is too much of an effort for a single person which is going to develop it in his spare time, so I contacted a bunch of friends in order to ask for their support. Then we stopped committing code and started writing down the user stories that will lead our effort from now on.

That’s why the read model and the domain model appear so similar, being the former a mere database reverse engineering and the latter the model that fitted my own “demoing” needings, but we’ll remove this model (and other code, such as the repositories) as soon as we’ll have the new ones, which will emerge from the user stories. Remember that I *still* need demoes for my talks, so I won’t be able to remove “demoable” code until when I have a replacement for it. The nice part is that we think that the new model will be composed by “real” aggregates and that we’ll switch from SQL server to a NoSQL database, so the “R” and “C” parts are going to be pretty different.

At this very moment, being the “code writing” on a hiatus, the only code I would recommend a casual downloader to look at is the stack that shows the recommended projects onto the home page, which picks the products following the following strategy: “Given all products->Choose the ones we are selling (which, of course, aren’t all the products we have in the db)->Then select only the available ones->Let’s pick up the projection we need within this view”. That happens picking them (the products) by means of an expression tree that is composed while goin’ up the application stack: that’s an idiom we at Managed Designs nicknamed LET (which stands for Layered Expression Trees) and we think that it’s a pretty powerful idiomatic way to express logic in a DDD context. I’ll talk about it at the next local event, and dedicate soon a blog post to it.

To sum it up: if you’re looking for a sample application, you’d better search for a project sporting a release version (which is something NSK still doesn’t) or, at least, wait for we to implement some more user stories in order to allow the whole design to consolidate. In the meantime, the project can still be looked at in order to take advantage of some “pills” you could be interested in for your projects, such as:

  • JQueryUI integration with ASP.NET MVC (i.e.: the DateTime partial view implemented for both WebFormsEngine and Razor engine)
  • MVC and WCF custom factories
  • NuGet-based pre build actions in order to easen you first “compile&run” (for those using the recently released v1.6 of NuGet, I’d recommend to have a look at the “package restore” feature)
  • Code Contracts aware IRepository interface (don’t focus on actual designs: the real meat lies in having IAggregateRoot + code contracts enforcing your validation even when application code “forgets” to do domain object validation)
  • Rss and Atom custom ActionResults for ASP.NET MVC, taking advantage of framework’s built-in serializers

That’s all code you can use (and refactor to satisfy your own needings) due to the license chosen. Enjoy NSK!

P.S.: I know, project’s description on Codeplex sucks bad. Mea culpa: I’ll fix it ASAP.

NHDay debriefed

“Astonishing”: that’s the only way I have to describe how much I enjoyed living the NHDay: I sincerely thank the staff, the speakers and all attendants for having made possibile such an event. As a “side note”, here are the slides & demos I’ve shown. Ad maiora!

Technorati Tag: ,

NHDay, as one of the other speakers

In real life, you are not allowed to drive a car without a licence: that’s both for your own and other’s safety. In our dev life, we can start using O/RMs without knowing what an identity map or an object space is, which leads to low-perf, memory hungry applications and, in the end, to ourselves blaming O/RMs for them.

If the Five Ws of O/RMs matter to you, then we could meet here.

Technorati Tag: ,

NSK goes to CodePlex

Northwind Starter Kit has moved to CodePlex: the new home page is here.

Technorati Tags:  

INETA web site talks about italian UG meetings

Thanks to my friend Lorenzo, the italian page of INETA Europe website is up and running. Even better, the page shows the annoucement of UGIdotNET's next meeting. All hail for Lorenzo!

Technorati Tags:  

Northwind Starter Kit source code released

As my friend Dino already announced, the Northwind Starter Kit has finally been released. Let me just bore you with a little bit of history. During the last years, I noticed a growing interest within the .NET community for topics (I'm in love with) like: design patterns, unit testing, (agile) methodologies and so on. Being a regular speaker at Microsoft events here in Italy, I found myself in need to set up presentations and demos covering these topics. Instead of creating "synthetic" code, I decided to create a simple "reference" application in order to show it during my talks. This app:

  • Should be based on a layered architecture, implemented as a service layer and sporting a "real world" domain model
  • Should use well-known design patterns and eventually idiomatic design considerations, showing the rationale behind all these choices
  • Should use Northwind as its default database, in order to easen its deploy. It should also be decoupled from the physical structure of the database, in order to allow to use different stores
  • Should offer unit tests
  • Should be available with both web-based and smart client GUIs
  • Should be documented in... some way :-)

Since I'm not a full time speaker/trainer/author (I must confess that in my real life I work as a software architect at Managed Designs), I could only use spare time in order to implement the the application: I had some working code, but it was far from being (and still is, to be honest) the "reference app" I dreamt about. So I looked around in order to make this app a community supported project, christening it "Northwind Starter Kit" (NSK) and releasing it under the Common Public License. Then I contacted luKa and Ricky that accepted to be part of the "core team" of the project, and later even Dino joined the project. Last week we released a first drop of the code, on which we're still working. So, what re we going to do from now on? We won't save the world. We'll simply continue to work on the project, hoping to see both the app and the team growing as time passes. There's still a *lot* of work to do. Would you like to help us? Download the archive, expand it, modify the connection string stored within the config file, and run your favourite flavour of the GUI (windows or web). Should you: have trouble doing this, experience exceptions using the application or spot errors within the source code, please contact me or discuss the issue(s) using the forums in order to give us feedback. We hope we will be able to set up a collaborative development process: time will tell, but in the meanwhile, we'll continue to work onto NSK.

Technorati Tags:

New kids on the... blog

It seems that my friend (and VB/WPF guru at Managed Designs) Corrado started its english blog. Don't miss it!

[OT] Anders Powers

Ok... Coulnd't resist to reveal Anders real identity to the world: the truth is out there! <g>

Membership API article (reloaded)

Dino just told me that our article has been puslished in the european edition of MSDN Magazine, too. Honest: I'm waiting to receive my copy in order to understan how this new edition of the mag differentiates from the US one.

Some thoughts about ASP.NET 2.0

As Soma pointed out, VS2005 is finally out: it's been a long way since the early bits we (alpha testers) got in May 2003. These are a bunch of thoughts of mine about ASP.NET v2 I wrote for Microsoft EMEA "Beta Experience" newsletter.