Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Billy McCafferty

  • S#arp Architecture 0.9 Released!

    I'm pleased to announce that S#arp Architecture 0.9 has been released at http://code.google.com/p/sharp-architecture/downloads/list.  Along with completely updated documentation (in /docs) and migration guidance (in /VersionHistory.txt), this release has a number of improvements to the SharpArch libraries including, among others:

    • Update of dependencies such as ASP.NET MVC Beta;
    • Inclusion of NHibernate.Validator and Fluent NHibernate (no more HBMs...although they're still supported if you love getting your hands dirty in XML);
    • A final resolution to Equals and GetHashCode; they're now completely independent from one another;
    • Interfaces for DomainObject (was "DomainSignatureComparable") and PersistentObject for rolling your own versions if you'd prefer;
    • A greatly simplified Repository interface and with a small addition of GetByProperties (and now being called "Repository" instead of "DAO" to be more inline with DDD nomenclature); the more advanced NHibernate-centric Repository interface is still available for use if needed;
    • Support for NHibernate configuration settings being elsewhere than web.config; and
    • An extracted DbContext, accessible from any Repository, to access methods such as CommitChanges and RollbackTransaction.

    The Northwind sample project code has also been developed further to include:

    • Plenty of examples of using Fluent NHibernate in various situations such as one-to-many, many-to-one, many-to-many;
    • Inclusion of NHibernate.Validator as the preferred mechanism for performing validation with S#arp Architecture (although other mechanisms may be used); and
    • A full CRUD life cycle example (trivial as it may be) for managing basic employee information.

    While feedback is always welcome and encouraged, I particularly hope to receive a lot of critiques, suggestions, and ideas for improvement of the employee CRUD example as this will serve as the basis for templates and scaffolding generators.

    To give you an idea of what stands between 0.9 and 1.0:

    • Add WCF integration
    • Add example of using a Unit of Work to encapsulate non-trivial controller logic
    • Add support for the Common Service Locator
    • Hone CRUD capabilities
    • Scaffolding generators!  I intend to include scaffolding generators for various presentation options such as ASPX, Ext JS and NVelocity.

    A big thanks goes out to Frank Laub, Simone Busoli, Luis Abreu, Kyle Baley, and Roy Bradley for the terrific insight, suggestions and all around assistance for this release.  Feel free to join in on the discussions at http://groups.google.com/group/sharp-architecture.

    Enjoy!

    Billy McCafferty

  • A Gem of a Lesson from Rails

    For the past few months, I've gotten the privilege to develop a good sized, production Ruby on Rails application.  I say privilege because it has shed light on many lessons for the way we develop in the Microsoft community.  The beauty of RoR is that you don't have to spend months or years reading books and blogs on how to put together a properly architected application.  This doesn't mean you're not going to shoot yourself in the foot, but it certainly reduced the risk!  Additionally, if you get a new job at a different Rails shop, you typically don't have to spend a couple months trying to figure out somebody else's homegrown architecture (if you're lucky enough to find any structure at all).  RoR is like a design pattern at the macro-level...pulling together the (albeit opinionated) best practices of data access, layering, and unit testing into a consolidated package.  Obviously, there is never a one size fits all - there are simply too many varying needs to have a single application design fit every scenario.  But it certainly fulfills the 80/20 rule...what RoR has proven is that it's highly effective, on many levels, to have a "preferred path" and common platform for the 80% of web-based application scenarios which it covers nicely.  The overwhelming benefit of having this common platform - with many technical decisions made for you, such as how to validate forms and models, how to setup CRUD communications, how to communicate with the DB, and how to organize applications - is that the community is able to converge on a consolidated preferred practice.

    When the GoF wrote Design Patterns, it gave the development community a formalized language to discuss common coding scenarios and recommended practices for addressing those situations. Martin Fowler did the same by formalizing "smells" and refactorings in Refactoring.  This formalization and common language has made it easier for developers to discuss solutions to a problem and to get new developers ramped up to a framework which leverages some of these formalized ideas...assuming they're used appropriately.  Likewise, Rails provides a formalized track for Ruby developers to develop data backed, web-based applications.  This has paid dividends in the availability of guidance, the facilitation of plugins/extension, the enabling of widely used scaffolding generators, and the removal of hours/days/weeks of research and trial & error to find out how the heck do we competently write a dynamic web application with Ruby.

    ASP.NET MVC is shaping up to be a spectacular framework.  Frankly, it is far more than a magnitude improvement over traditional ASP.NET.  But the remaining opportunity, if you will, is that it is too specific in nature to provide an end-all "preferred" path for .NET web application development.  What should we unit test with?  How should we talk to the DB?  Who should handle dependency injection?  Should the model really be in the same assembly as the web project?  ASP.NET MVC is similar to NHibernate wherein it's absolutely spectacular in providing a solution for accomplishing a specific task - NHibernate for providing DB communications in a domain driven design and ASP.NET MVC for bringing the MVC pattern to .NET web development.  That doesn't lessen its benefit; it simply doesn't do much to keep a developer from leveraging it inappropriately, knowing which tools should be used with it , and how to properly write a real world application.

    One of the primary challenges is that there are simply soooo many options to choose from beyond just deciding to go with ASP.NET MVC.  It's absolutely bewildering at times to know which assortment of tools and techniques are the best to select.  (Try to recall when you first started writing .NET apps!)  To further frustrate the problem, there is no "best" combination of tools and practices.  But just as RoR doesn't necessarily represent the quantifiably best practices/tools for developing web-based Ruby applications, it has given enormous benefit to the Ruby community by providing a formalized, preferred approach.  What's needed then, IMO, for Microsoft web development is an equivalent foundation which leverages ASP.NET MVC with a number of carefully selected tools to provide a best practice preferred path which will cover most web application scenarios.  To begin the plug, that's what I hope S#arp Architecture to be.  I don't intend for it to be merely an example of using ASP.NET MVC...I intend for it to be the Ruby on Rails for ASP.NET MVC which can enjoy benefit from scaffolding generators, standard practices, standard means for creating and sharing plug-ins, a common ground for sharing agreed upon best practices, etc.  Although it won't be applicable in all cases, I feel it's on its way to comfortably covering the 80% of domain driven, web-based applications.

    The challenges to aspiring to such a goal for #Arch, and any foundational architecture for that matter, include:

    • Keeping the solution simple enough to be easily learned and to develop with,
    • Keeping it flexible enough to use a variety of options for the presentation layer and other facets, such as the mechanism of dependency injection if desired,
    • Providing tools, such as scaffolding generators and project templates to realize one of the major benefits that such a consolidated framework can provide,
    • Making it dead simple for developers of all skill levels to get an application up and running quickly without being overly constrained by design and without leading to maintenance nightmares down the road, and
    • Keeping it lean enough to avoid the choice-overload that framework bloat often leads to.

    I suppose you could say that the above is my commitment to the users of the architecture.  In short, I'm attempting to provide just enough judicious planning for solving common problems without compromising flexibility.  To help you decide if S#arp Architecture is appropriate for your project, you'll want to consider the following assumptions, which aren't necessarily objective best practices, but which S#arp Architecture has built in:

    • Domain driven design is the preferred way to encapsulate your model and business logic (e.g., this is great for those of you who get the willies after looking at ADO.NET Entity Framework);
    • Tiers should be loosely coupled and employ separated interface (aka, dependency inversion) to separate service dependencies from domain logic;
    • The ability to unit test all code, from the controller action down to the lowly DB filtering, should be available while supporting a domain driven design (i.e., you shouldn't need to create your database to test all of your business logic);
    • Database access and communications should require little attention and should be minimally intrusive, but without limiting those capabilities; and
    • Preferred practices for a few key areas should be suggested, such as model validation, CRUD mechanics, and application layering.

    But even if you agree with these points, this doesn't mean that it'll be appropriate in every situation or that it won't be "too much" in very simple scenarios.  Indeed, the decision of using any base architecture is akin to employing a design pattern (but bigger)...it should only be leveraged when appropriate and only when it carries its weight.  At the beginning of any project, a number of architectural approach should be compared side-by-side to assist in picking the right tool for the job; a few options to consider besides S#arp Architecture include a homegrown solution, ADO.NET Entity Framework, Castle MonoRail, CSLA, or the full suite of Spring.NET tools.

    A commenter on http://codebetter.com/blogs/kyle.baley/archive/2008/11/11/overview-and-review-of-s-arp-architecture.aspx also brought up great points with respect to concerns of future bloat and unnecessary complexity as frameworks evolve and grow, as the life cycle of some architectures have fallen victim to.  These are enormous risks for any framework that attempts to cover the development needs of 80% of web-based applications; there are a few more tasks which need to be done to bring #Arch to version 1.0 and almost all of them are focused on further reducing complexity without limiting flexibility.  Certainly one of the success factors of Ruby on Rails is that it hasn't tried to continue to add tons of new functionality with each new release; it has simply attempted to solve one area - model driven web development with Ruby - in a very clean and competent manner...and then left its approach alone.  I hope S#arp Architecture emulates some of these lessons learned by providing a simple to use platform for developing domain driven, web applications with ASP.NET MVC.  And once it gets to that point with 1.0, I promise we'll leave it alone. ;)

    Billy McCafferty

  • Refactoring Service Dependencies to Separated Interface

    There are two factors which have a tremendous impact on a team's likelihood to abandon unit testing:

    • Fragile tests which break often and require regular maintenance; and
    • Slow tests which add excruciating seconds, if not minutes, to the total time of unit test runs.

    I find that fragile tests are often those that depend on data within a database, which can become out of synch with the assertions in the unit test, and those that depend on external services.  I use the term "services" loosely to define anything that represents an external resource; examples include web services (including RESTful services), file repositories, databases, and remote procedure calls.  But these dependencies on services aren't just bad for keeping unit tests running fast and stable; they can often lead to maintenance problems due to tight coupling.  This post presents a common scenario wherein business logic is tightly coupled to a service and provides instruction for refactoring the concrete dependency to a more testable and loosely coupled configuration.

    Separated Interface & Motivations for its Inclusion

    The design pattern known as "Separated Interface" (coined by Martin Fowler; aka "Dependency Inversion" by Robert Martin) is a technique for reducing coupling to concrete dependencies; it achieves this by coding to the interface of the dependency while maintaining the implementation details of the dependency within a separate application layer.  You'll find that the trick of using separated interface, as with any design pattern, is knowing when to use it appropriately, rather than how to use it, as the underlying mechanism is rather straight forward.  I find it best to use on most external services, as defined earlier, but should still be considered on a case by case basis.  You should ask yourself if introducing Separated Interface will make the overall application more maintainable and testable while keeping complexity to a minimum.  When used appropriately, the benefits of this decoupling include:

    • Improving the ability to unit test "around" the dependency using mocks/stubs,
    • Greatly increasing the performance of domain oriented unit tests as a side effect of using mocks/stubs,
    • Consolidating dependency communication details to a separate tier,
    • Providing a plug-in architecture for external dependencies to be easily swapped without recompiling (e.g., when that 3rd party tool gets upgraded), and
    • Allowing developers to develop and compile the domain logic without having all the dependencies in place (e.g., not having to install 3rd party tools A, B, and C just to develop and compile unrelated code).

    To illustrate, the following diagram shows two separate assemblies within the project solution.

    • The Project.Core assembly contains all of the domain logic for the application.  In addition to domain objects, such as Customer and Order, this example assembly also contains an interface to an external service; in this case, IOrderDao, which represents an interface to a data-access object.  Note that this is only the interface of that service; the domain logic has no idea (or dependency) on the underlying implementation details outside of its conformance to the interface.
    • The Project.Data assembly contains all of the implementation details for the interface and contains an assembly reference back to Project.Core.  This is the fundamental key to Separated Interface.  In most applications, the data communications and external dependencies are depended on by the business logic.  With Separated Interface, the reverse is true wherein the service implementation depends on the interfaces within the domain layer - the true core of the application.

    Separated Interface

    This pattern typically presents two challenges.  The first is, how does the domain logic get passed a reference to the actual concrete dependency if all it knows about is an interface?  The dependency can get passed to the domain object via its constructor or a setter either manually or with an IoC container, such as Castle Windsor or Ninject.  (See http://www.codeproject.com/KB/architecture/DependencyInjection.aspx for an example of doing so.)  The second and more challenging problem is, how can we get the external resource to depend on our domain layer interface when it's a third party tool?  Recall that we want the service to depend on the domain, not the other way around.  In these cases, it's appropriate to create a facade which wraps the complicated details of communicating with the dependency; then, we simply add an interface for the facade to our domain layer.  The following example will walk through looking at a real world smell of a concrete dependency on a third party API - exposed as a RESTful service - and making appropriate modifications to introduce Separated Interface.

    Real World Example (aka "the smell")

    To set the appropriate context, assume that (smelly) code has been developed to fulfill the following user story:  On a nightly basis, the application will download any new Observations added during the previous day, input into ExternalApp, so that they may be copied locally.  (An "observation" is the domain name of the record we're retrieving.)  The idea is that an external application exists, aptly called ExternalApp, which exposes a RESTful service to retrieve newly added records.  Our nightly process ties into the service, retrieves the appropriate records, parses the response, and copies the appropriate information locally.

    Our application currently has three tiers:

    • The MySynch.Tests assembly contains unit tests to verify these processes.  (No, of course we didn't call it "MySynch," but that'll work for now.)
    • The MySynch.Core assembly contains all of the business logic for communicating with the RESTful service and processing the results.  Assume it contains one object called ObservationMigrator which encapsulates this logic.
    • The MySynch.Console application which is the nightly process, which we won't concern ourselves with here.

    The following unit tests, found in the folder MySynch.Tests/Core, verify that the records can be retrieved and that the data migration is successful:

    The first test is really verifying if the communications with the RESTful service - the third party tool - are successful.  The second test is verifying if the data migration occurs successfully, assuming the communications with the RESTful service are successful.  Without even looking at the underlying code, these tests are already unveiling a number of smells:

    • It's obvious that the ObservationMigrator isn't adhering to the Single Responsibility Principle (SRP).  It's providing means to communicate with the service, via GetNewObservations, and it's responsible for migrating those records to whatever destination.  Consequently, it's likely that it's inherently complex and that it's likely to be touched often during maintenance for different reasons.
    • The second test is really just trying to make sure that the migration occurs successfully without necessarily wanting to retest proper communications to the RESTful service; that was what the first test was doing.  The problem with this is that if the service goes down, in addition to breaking the first test, it'll start breaking the second test which is really domain-oriented in nature.  It would be great if we could test the migration process without having to retest the communications to the service.
    • Finally, communicating with any external resource via unit tests, especially web-based services, adds seconds to running the unit tests.  This can add minutes with hundreds of unit tests.  Again, if all we really want to test in the second test is the domain logic for completing the migration, then we shouldn't be reconfirming communications are working and adding wasted time to running the tests.

    Indeed, if we look under the covers at the ObservationMigrator class, we confirm our concerns with respect to SRP and HTTP requests embedded into the business logic:

    Refactoring Mechanics

    In refactoring this code, we'll want to follow the steps below to reduce the amount of work done between tests and to minimize the amount of breaking code in the system at any given point in time.  Our goal is to always be very close to a check-in...the "don't anybody check anything out for the next two days" won't fly here.

    1. Refactor with Extract Class to pull the RESTful communication and parsing logic into it's own class.  This extracted class becomes the facade to the underlying RESTful API.
    2. Refactor with Extract Interface to create an interface for the new API facade.
    3. Refactor with Introduce Constructor Injection to replace the creation of the dependency with a constructor parameter.
    4. Refactor with Introduce Stub Object to modify the testing of the migration test to focus on the domain logic rather than on retesting communications with the API.
    5. Refactor Architecture by Tiers to move the implementation details to a separate tier.

    Step 1:  Extract Class

    So without further ado, let's start with step 1, extracting a class to act as a facade to the underlying RESTful API.  As always, we begin with a test; let's do so by adding a new test as follows:

    Note that we've added this fixture to a category called "ExternalApp Integration."  Doing so, we're able to conveniently turn off this slow-running category of unit tests while we're working on other areas of the application.  Compiling this breaks, so the next step is to add just enough code to MySynch.Core to get the test to compile:

    You should now be able to run the test and see it fail with a NotImplementedException.  Yes, you want it to fail...a failing test is your next goal to fix.  So now let's write enough code to get it to pass by copying the GetNewObservations() method from ObservationMigrator into ObservationRetriever:

    All the unit tests should now be passing again.  But we've introduced a problem...the smell of duplicated code.  We can remove this smell by replacing the ObservationMigrator.GetNewObservations() method with the creation of an ObservationRetriever object and the invocation of the method therein:

    You'll need to drop ObservationMigratorTests.CanRetrieveObservationRecords() to get it to compile; but all the tests should still be passing.  We've officially completed step 1 by extracting a class from the ObservationMigrator class into a facade class which only concerns itself with communicating with the RESTful API and parsing the results.

    Step 2:  Extract Interface

    Step 2 is introducing the interface to our service.  Instead of creating a new test, we simply modify the ObservationRetrieverTests.CanRetrieveRecordsToImport() method to invoke GetNewObservations() via an interface rather than the concrete object itself:

    Since a quick compilation shows that this isn't compilable (and it shouldn't be), let's add an interface to MySynch.Core which reflects the method on our facade class, and have ObservationRetriever then implement that interface.  First, the interface that we need to add to MySynch.Core:

    Then, simply have the ObservationRetriever class implement this interface:  public class ObservationRetriever : IObservationRetriever { ...

    All unit tests should be passing again...oh, happy days again.

    Step 3:  Introduce Constructor Injection

    The ObservationMigrator class still has a concrete dependency on the ObservationRetriever...damn that concrete dependency!!  So let's now introduce constructor injection to remove this tight coupling.  Guess where we're going to start...that's right, back in a unit test.  But here again, we don't need to add a new test, we simply need to alter an existing one, ObservationMigratorTests.CanMigrateObservationRecords().  The modified test should be as follows:

    All we're intending to do here is to pass an instance of IObservationRetriever to the migration utility rather than having it create its own.  Tying to compile breaks the build, so now let's write just enough code to get this puppy to compile...usually we'd write just enough to compile and then just enough to pass, but I'm getting tired of writing, so we'll combine the two here:

    With these changes, everything should now compile and the tests should be passing again.

    Step 4:  Introduce Stub Object

    As mentioned in the previous gripes against the original code, the ObservationMigratorTests.CanMigrateObservationRecords() test shouldn't be worried about communicating with the RESTful service; it should only be concerned with ensuring the migration occurs assuming the RESTful service is working as expected.  The ObservationRetrieverTests.CanRetrieveRecordsToImport() test is already verifying that the service is working, so it's just adding extra time and complexity to the ObservationMigratorTests.CanMigrateObservationRecords() test.  Therefore, let's now introduce a stub object to simulate communications with the RESTful service.  Keep in mind that this modification isn't being done to test new functionality; instead, it's a refactoring to an existing unit test to properly focus the test's attention on the domain logic.  Accordingly, the ObservationMigratorTests now reflects the following:

    In the unit test above, a stub object has been created which implements IObservationRetriever and fakes communications with the external service to retrieve three new Observation records.  The ObservationMigrator.MigrateRecords() method happily uses this stub, not knowing that it's actually not talking to the external RESTful service.  We're now focusing this unit test on testing the domain logic, outside of communicating with the RESTful service.  Again, the ObservationRetrieverTests fixture of tests is already testing the communications with this service and related parsing functionality...no need to retest it here.

    In such a simple case, where the interface only has one method to implement, a stub is perfectly adequate.  But we're passing three observations to the migration step without verifying that all three were processed...we might as well have just passed one, or none at all for that matter.  This test could be extended in two ways to verify the underlying migration processed each and every Observation appropriately.  The first is that we could include the status of how many observations were migrated within the Result object returned from the migration step.  The other way is to use a mock object, instead of a stub, which can verify that the expected behavior is occurring under the scenes.  Although mocking is beyond the scope of this post, I encourage you to take a look at http://xunitpatterns.com/ and Rhino Mocks for more information.

    Step 5:  Refactor Architecture by Tiers
    (i.e., add the "Separated" part of "Separated Interface")

    After all of this, we're finally at the point of culmination:  the introduction of the Separated Interface.  But by now, it's rather anticlimactic as the hard work has already been done.  Nonetheless...on with the anticlimactic conclusion!  A problem with the solution as it stands is that the service facade still physically resides in the MySynch.Core assembly.  Consequently, there's nothing we can do to prevent developers from bypassing our elegant interface and go straight to the ObservationRetriever class itself.  This is a wonderful side benefit of introducing Separated Interface; it forces developers to adhere to certain design decisions.  To mitigate this concern, and to remove all coupling from MySynch.Core to the implementation details of ObservationRetriever, we'll refactor the architecture itself to move the implementation details to a separate tier.  Let's head back to the tests assembly and add a new folder called ExternalAppIntegrator; recall that "ExternalApp" is the name of our 3rd party tool which exposes the RESTful service.  Now move the ObservationRetrieverTests class to this new folder.  This new folder represents the new class library that we'll be introducing.  The ObservationRetrieverTests class should then be modified to reflect the change in namespace and a using statement to pull in the class library which we have not yet created (remember...write the test and then write the code to get the test to pass):

    We've introduced some work for us here, but we will overcome!  Firstly, create a new class library called "ExternalAppIntegrator.Core" and add a reference to it from our MySynch.Tests assembly.  Next, move the class MySynch.Core/ObservationRetriever.cs to the ExternalAppIntegrator.Core class library...be sure you move it completely by deleting the original.  Ack...a new problem now!  We've moved the class but it depended upon IObservationRetriever.  Fear not!  Simply add a reference to MySynch.Core to the ExternalAppIntegrator.Core class library.  Since we've removed all other dependencies to the ObservationRetriever from MySynch.Core, all the unit tests will still pass.  As a matter of fact, we're done!

    But wait, how do we know it's working?  Although not necessary, since the unit testing has proven that all of the inner workings are in order, we can make sure our Separated Interface is working as expected with the rest of the migration process by going back to ObservationMigratorTests.CanMigrateObservationRecords() and replacing the creation of the stub object with our concrete implementation:  IObservationRetriever observationRetriever = new ObservationRetriever();  With that said, I'd quickly change it back to using the stub so that we can keep that unit test focused on the domain rather than communications with the RESTful service.

    In Conclusion

    We've taken some rather smelly dependencies and moved them to a dedicated class library which concerns itself with the management of a facade over the external API.  We finished by having this facade implement an interface found without our domain layer so that the domain layers could communicate to the external API without having a direct, concrete dependency on the implmentation details.  The hope is that this has made our code more testable, less coupled, and more maintainable down the road.  The cost has been the introduction of increased complexity.  Accordingly, care should be taken before the introduction of any design pattern to ensure that the pattern itself is "pulling its weight," so to speak.

    I have found immense value from this design pattern; it has been particularly handy for removing direct dependencies on data access objects.  The sample code that comes along with S#arp Architecture has a full example of just such an instance.  Happy coding!

    Billy McCafferty

  • Custom Collections with NHibernate, Part IV: Extensions!

    In part I of this series, we examined motivations for maintaining custom collections that are compliant with NHibernate.  Part II demonstrated the basics behind wiring up a custom collection.  Finally, part III refactored the solution into a nice reusable package with minimal intrusion (relatively speaking).  My complaint with all of this is that the proposed solution is complicated, difficult to explain, and leans towards Shotgun Surgery by requiring you to change the signature of both the POCO collection as well as the NHibernate collection every time you need to add a new method.  That's just not cool.  As much bad press that extension methods have received, I have found one instance (and only one so far) when extension methods truly shine:  extending collection interfaces, which NHibernate can happily bind to, with custom methods.

    Ideally, we want our custom collection to be completely ignorant that it's being bound to by an ORM.  In the previous suggestion (part III), we ended up with an IProducts interface to define the custom collection, a Products class to implement the custom methods, and a PersistentProduct class for NHibernate to bind to.  (We also had a very ugly HBM mapping, but I digress.)  This all seems a bit overkill and more than a stone's throw from being completely ignorant of the data-access mechanism.  For this demonstration, assume that a Customer has one or more orders; furthermore, we'd like to be able to add custom query methods onto the orders collection.  But since NHibernate has to bind to an interface, let's start there within our Customer class:

    Now that we're just binding to a collection interface, the mapping becomes trivially simple:

    Are you starting to get a sense for how much simpler this is going to be?  So we've got NHibernate binding to the collection, but we still need to provide custom methods on the collection; that's where extension methods come in!  Suppose that you have a need to regularly query the collection for all the orders that fall on a particular date.  As we concluded in part I of this series, we'd ideally like this mechanism to be on the collection itself.  By adding an extension method to the IList<Order> interface, our task is complete:

    With the extension method in place, we now have full use of the method from an IList<Order> collection with intellisense.

    Custom Collection Extension Intellisense 

    So where's the rub?  The drawback to this is that extension methods are a bit evil magical and can be difficult to notice if they're not kept well organized.  Accordingly, follow these guidelines when using this approach to make it easier for the next developer (usually yourself) who looks at your code:

    • Name the file (and class) which contains the extensions as <domain object plural>Extensions.cs; e.g., OrdersExtensions.cs, CustomersExtensions.cs.  This is similar to what we were doing before, e.g. Products, but tacks on the word "Extensions" to make it clear that these are extensions and not an actual collection object.
    • Put the extensions class physically next to the domain object which it works with.  For example, if the Order.cs class file sits in the directory MyProject.Core/Checkout, then OrdersExtensions should sit right next to it.  This makes it easier to spot when browsing the project files.
    • Keep each collection of extension methods logically contained in individual files, one for each domain object they work with.  Doing so emulates what we would have done if we were using "traditional" custom collection classes where we would have had e.g. Orders.cs and Products.cs.  Contrastly, you shouldn't put every extension method into a ginormous MyCollectionExtensions.cs class.  This breaks the SRP, makes it difficult to digest when it gets larger, and can quickly become a maintenance headache nightmare.

    I've been using this approach for the creation of custom collection behavior for the past six months or so and have been very pleased with the ease of use and extensibility.  They're also leveraged in the S#arp Architecture example code.  While extension methods may be a bit on the evil side, they make the challenge of using custom collections with NHibernate terribly trivial.  >-)

    Billy McCafferty

  • Prevent IIS from Binding to all Assigned IP Addresses

    By default IIS binds (listens) to all IP addresses assigned to the server it's running on.  This is problematic when you'd like one or more of the IP addresses to be used by another application, such as a Ruby on Rails app running on Apache or, in my case, Mingle.  In these instances, it is desirable for IIS to bind to only one or more specific IP addresses while allowing the others to be free for use by other services.  To do so, you must explictly set IIS to listen on the IP address(es); doing so will automatically free all other IP addresses for other uses.  To explicitly add an IP address to the IIS IP Listen list:

    1. Ensure that you have the HttpCfg.exe utility installed onto the server.  If you're running Windows Server 2003, it'll automatically be available, but if you're running Windows XP you can download HttpCfg.exe as part of the Windows XP Service Pack 2 Support Tools.
    2. Open a command prompt and type the following, replacing ###.###.###.### with the IP address you'd like to add to the IIS IP Listen list:
      httpcfg set iplisten -i ###.###.###.###
    3. Upon success, it'll return the following confirmation:  HttpSetServiceConfiguration completed with 0.
    4. Restart the HTTP service.

    After restarting the HTTP service, IIS will only bind to the IP address added to the IP Listen list.  You can use the HttpCfg utility to inform IIS to listen to more than one IP address as well.  If you want to see all IP addresses that IIS is listening to, simply run "httpcfg query iplisten" in a command prompt.

    Billy McCafferty

  • Exposing Multiple Computers via Remote Desktop over a Single IP Address

    [Post publish note - 8/19/08:  Frank Laub has provided a tip, in the comments below, for alternatively configuring your router for port forwarding rather than setting up a new listener port for each computer.  This is exactly why I like to blog...for others to tell me an easier way to do things!]

    I often have a need to remote onto one of the multiple computers on my home network from offsite but am too cheap to get more than one IP address.  Instead of getting more IP addresses (and without installing a third party tool), you can easily accommodate this by modifying the listening port, from the default of 3389, of each computer on your network.  You'll then be able to remote desktop into each of your computers via <your IP address>:<custom listening port number>.

    To make this possible, take the following steps (performed on Windows Server 2003 with Windows Firewall enabled):

    1. Enable the computer to accept Remote Desktop connections
      1. Right click the My Computer icon and bring up System Properties and go to the Remote tab
      2. Check the Enable Remote Desktop option
      3. Select users which will have Remote Desktop access to the computer
    2. Change the listening port of the computer you'd like to remote desktop onto (http://support.microsoft.com/default.aspx/kb/306759):
      1. Start Registry Editor
      2. Locate and then click the following registry subkey:
        HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp\PortNumber
      3. On the Edit menu, click Modify, and then click Decimal
      4. Type the new port number, and then click OK
      5. Restart the computer
    3. Expose the new port through the Windows Firewall
      1. Open Network Connections
      2. Open the properties of the Local Area Connection and go to the Advanced tab
      3. Click the Windows Firewall Settings button and go to the Exceptions tab
      4. Click Add Port... and provide the following:
        • Name = "Remote Desktop (<custom listening port>)"  (What you name this is arbitrary, but this helps to identify it.)
        • Port Number = <custom listening port>
        • TCP should remain checked
        • Change Scope should be set to Any Computer (if you want to remote desktop over the internet), My Network (if you only want to be able to remote desktop from internally - but then there's no point in changing the listening port), or Custom List
    4. If you are using a hardware firewall as well, you'll also want to poke a hole in it for the custom listening port and have it redirect traffic on that port to the respective computer.

    And that should do it!

    Billy McCafferty

  • ASP.NET MVC BindingHelperExtensions.UpdateFrom with NHibernate loaded objects

    An interesting issue was brought up on the S#arp Architecture discussion today (it was actually brought up on the old S#arp forum...but then I couldn't plug the new location! ;).  If you use System.Web.Mvc.BindingHelperExtensions.UpdateFrom to copy fields from a submitted ASP.NET MVC form into an object loaded using NHibernate's Session.Load() method, no data may be copied to the object.

    Mark, the person who brought up the issue, noticed in the debugger that the object being updated was actually a proxy using Castle.Core.Interceptor.IInterceptor.  The reason that this is occurring is that, by default, NHibernate lazily loads objects.  For example, assume you load a Customer from the DB using Session.Load(); NHibernate won't take the time to talk to the database and set the object's properties until one of the object's properties or methods are invoked on the myCustomer object.

    To make this magic trick work, NHibernate gives you a proxy object that informs NHibernate when it's time to actually hit the database; NHibernate uses the Castle Proxy project to facilitate proxying.  Since UpdateFrom uses reflection to update the object's values, it won't kick off the proxy's "time to talk to the database and load the real object" trigger.

    You have three options to work around this limitation of UpdateFrom trying to update the proxy object:

    • Add lazy="false" to the opening class tag within the object's HBM file.  This will ensure that the object is not loaded lazily and will not give you an intermediary proxy.
    • Load the object from the database using NHibernate's Session.Get() method.  This method will never return a proxied object.  (This replaced NHibernate's deprecated Find() method.)
    • Look at one of the properties or invoke a method on the object before your call to UpdateFrom.  This will force NHibernate to replace the proxy with the actual object loaded from the database.  (Albeit, not a very elegant solution.)

    The first and second options are the cleanest approaches and, as a nice side-effect, you won't have to add "virtual" before that object's properties and methods if you set lazy="false" in the class declaration.

    Related references:

    Billy McCafferty

  • S#arp Architecture: a new home, upgrades and a logo!

    S#arp ArchitectureTo facilitate better integration with SVN clients, S#arp Architecture has been moved to Google Code at http://code.google.com/p/sharp-architecture.  Additionally, a discussion group has just been setup on Google Groups at http://groups.google.com/group/sharp-architecture to support use of the architecture, discuss the ideas and patterns behind it, offer suggestions for improvement, and exchange ideas for using it in real-world applications.

    So why a bonsai tree on the logo?  Bonsai trees are small, have years of practice trained into their shape, and have a solid core...all the attributes that I hope S#arp Architecture exhibits.  Besides, if they're cool enough for Mr. Miyagi, then the choice is obvious!

    By the way, S#arp Architecture 0.7.3 currently supports ASP.NET MVC Preview 4 and NHibernate 2.0 CR 1.

    Enjoy!
    Billy McCafferty

  • When to use many-to-one(s) vs. many-to-many with NHibernate

    A common question when developing with NHibernate is:  when is it appropriate to use a many-to-many relationship vs. two many-to-one relationships?  And does an intermediary domain object need to be introduced to reflect a many-to-many relational table?

    As a rule, when using NHibernate, you should rarely, if ever, have to model your domain to accommodate the constraints of relational model, and vice-versa.  For example, suppose you have a Customers table and an Addresses table.  Each Customer can have multiple Addresses and each Address can be associated with multiple Customers; e.g., the same address could be associated with multiple family members in the same household.  Accordingly, you'd have a Customer_Addresses relational table in the DB to hold the many-to-many relationship entries; this table would simply have two foreign key columns:  CustomerFk and AddressFk.

    At first glance, this might imply that you'd have to create a CustomerAddress object in your domain model to reflect this relationship table in the DB; that's not the case with NHibernate.  Instead, you'd simply add a many-to-many association to the Customer.hbm.xml which indicates that the CustomerAddresses table should be used as the lookup for managing this many-to-many relationship.  (See the NHibernate documentation at http://www.hibernate.org/hib_docs/nhibernate/html/collections.html for implementation details of mapping a many-to-many relationship.)  This many-to-many mapping assumes that the Customer class contains an IList<Address> property (and you could optionally have the inverse relationship from the Address class).  Consequently, the domain model maintains a clean, domain-driven design, while the DB reflects a normalized relational model.  But keep in mind that a many-to-many relationship should only be used for a true many-to-many relationship table wherein the relational table only contains foreign keys to other tables.

    Now suppose, down the road, we add a bit column called IsCurrent to the Customer_Addresses table.  With this added, each row in the Customer_Addresses table is now an entity object with state, masquerading as a many-to-many relationship.  When this occurs, steps must be taken to "upgrade" this many-to-many relationship to a domain object with two many-to-one relationships to Customer and Address, accordingly:

    1. If not done so already, an identity column (or other unique identifier) needs to be added to the Customer_Addresses table; e.g., CustomerAddressId.  This is now the primary key of the table and will be the ID property of our domain object.
    2. A CustomerAddress.cs class needs to be added to the domain model having a many-to-one relationship to Customer as "public Customer Customer {...}", a many-to-one relationship to Address as "public Address Address {...}" and, of course, the "public bool IsCurrent {...}" property.
    3. CustomerAddress.hbm.xml needs to be added which reflects the same property and many-to-one relationships as indicated in step 2.  This HBM would map to Customer_Addresses table.
    4. The IList<Address> collection property within the Customer class should be modified to be IList<CustomerAddress>.
    5. Finally, the Customer.hbm.xml needs be modified to replace the existing many-to-many declaration with a one-to-many to the CustomerAddress object.
    6. (If your Address.hbm.xml contained a bi-directional reference back to IList<Customer>, you'd then have to take the same steps to replace the "other side" of the many-to-many with a one-to-many to CustomerAddress.)

    With this done, the many-to-many has been removed, a domain object has been introduced, and proper associations have been established.  Many-to-many(s) are handy, but as soon as they starting doing more than just being a relationship, action should be taken to promote the relational object to the domain.

    Billy McCafferty

  • S#arp Architecture 0.7 now supports NHibernate 2.0 Beta 1

    S#arp Architecture 0.7 represents a major upgrade to the infrastructure of S#arp Architecture - but the overall architecture, with respect to application layering, remains the same.  This release is far simpler to work with than previous versions while still providing plenty of flexibility.  A huge thanks goes out to Frank Laub who has provided terrific feedback and guidance on making S#arp Architecture simpler while using it on real-world web applications.  This release's many changes include:

    • NHibernate 2.0 Beta 1 integration is now included.
    • Integration with Spring.NET has been dropped. Spring.NET is a fantastic library with world class AOP, IoC support, and many other modules. But for S#arp Architecture, a simpler approach was found for performing dependency injection without the need for external configuration files. If you're still in need of many of Spring.NET's terrific libraries, you'll want to take a look at release 0.6.* which comes preconfigured with Spring.NET.
      • The ~/SpringConfig folder no longer exists
      • There is no more SpringInteropController
      • The Spring XML generator has been dropped from ProjectBase
    • GenericDAO now uses the native NHibernate session.
    • HTTP Modules are no longer needed to support the Open-Session-in-View pattern for NHibernate session management.
    • All configuration, such as the DB connection string, is now just within web.config.
    • Concrete types needed for Dependency injection are now declared at the top of each dependency interface; e.g., IOrderDao.
    • NHibernate session storage mechanisms, for both web and unit-tests/winforms have been added to ProjectBase.Data and ProjectBase.Web.
    • The Identity attribute has been renamed to DomainSignature to better reflect its purpose.
    • Controllers now simply inherit from the base MVC Controller.
    • ProjectBase.Web.ControllerFactory has been introduced with built in dependency injection.

    I'm confident you'll be very pleased with the changes and would highly recommend upgrading your project if you're already using this framework and do not need the many powerful utilities found within Spring.NET.

    http://www.codeplex.com/SharpArchitecture

    Billy McCafferty

  • Streamline Business Processes using Swim Lane Diagrams

    The following is an original article written by Kurt Sloan, printed here with permission.  Kurt's a terrific BA that I am fortunate enough to work with.  A template for the described processes below may be found here.

    Swim lane diagrams are good tools to use to map a process flow and identify potential problem areas that need to be corrected.  Read on to learn what a swim lane diagram is, what information you need to use it effectively, and how to apply it to an existing business process.

    The more we use a given business process the more complacent we become with its inherent inefficiencies.  This is true whether the process is examining a location to identify right-of-way owners, capturing and collecting a series of as-built drawings, or simply tracking a series of project-related information requests.  By nature, most people tend to get used to doing a job in a certain way, even when it is not the best way.  It can be very difficult to change our ways unless we have a significant reason to change our behavior.
     
    If you suspect that you have a business process that is not running as efficiently as it should be, you can use a swim lane diagram to map out that process and identify areas where it can be modified to become more efficient and effective.

    What is a swim lane diagram?

    A swim lane diagram (sometimes referred to as a “Deployment Process Map” or a “Cross Functional Flowchart”) is a graphical representation of a process flow that shows the interaction of different parties on the process and how the process progresses naturally through the different phases of the project. 

    Swim lane diagrams can be tailored to reflect individual situations as needed, but almost always include the following information:

    • Process:  The actual process and flow that is being tracked through its identified progression steps.
    • Actors:  The people, groups, teams, etc, who are performing the steps identified within the process.
    • Phases:  These might reflect the phases of the project, different areas of the project, or any secondary set of key elements that the process flow needs to traverse to successfully complete this process.
    • Symbols:  These are the physical symbols used to graphically represent what is happening in any given step of the process.

    There are different schools of thought for how to properly layout a swim lane diagram. One popular method, which we will use here, is the vertical “Actors” and horizontal “Phases” matrix.

    Workflow Symbols

    The area that holds most opportunity for individuality, and is the greatest source of debate in the development of swim lane diagrams, is in the selection and usage of workflow symbols.  A multitude of symbols is available to choose from when creating a process flow. The actual symbols you choose, however, are not as important as is providing the reader with the proper identification of those symbols and the meaning you are implying with them.  This is done most effectively by creating a detailed symbol legend.

    Minimize the number of symbols presented on a diagram to reduce the chance of confusing readers.  If you are creating the process map as part of a team assignment, it is important to get team agreement on symbol meanings and usage prior to mapping out the process. 

    The following symbols are basic to most swim lane diagrams and are usually sufficient to successfully conduct a process mapping, although users can add to or modify this to suit their tastes and needs:

    Map Out Your Process

    Step 1, Identification.  The first step is to identify the process that you want to analyze.  Identify a name and then a description for the process so that readers of the diagram can quickly and easily understand the intentions of the chart.  Put this information at the top of every page that you create. 

    Step 2, Map the Process Steps.   You are now ready to identify your process steps and map them out using a swim lane diagram . Start by creating a blank matrix and then begin filling it in starting in the upper left-hand corner (which indicates the first actor at the earliest stage of the process) and moving down and to the right.  As you identify new actors add new columns to the right of the matrix.  New phases of the process are represented by adding new rows to the bottom of the matrix.

    A basic swim lane diagram will look similar to the figure shown here:

    Step 3,  Get Details from Others.  As you beginning mapping out the detail of your process it is recommended that you schedule time with key actors as you identify them and ask them to describe the steps they go through for each section of the process that they touch.  These interviews will help you complete your physical process flow and can often help to identify misconceptions about the process that are currently in place.

    Additionally, you may find it useful to add another column to the far right that represents the “System” as a unique user.  This can be very useful in showing how the process being mapped interacts with different project applications in place on the project.  For example, if you were mapping out a project scheduling process and the project is using Primavera Project Manager for tracking the scheduling activities, you might want to add a column to the far right of the chart called “Systems” or “P6” and use this column to show the calls to and the data returned from the system that affect the process.

    Identify Areas of Inefficiency and Ineffectiveness

    To gain the maximum benefit from a swim lane diagram , it is important to review the process mapping with a focus on process improvement and not just on process identification.  Once you have captured the existing process as it occurs today, take the time to go through the steps and look for areas of inefficiencies.  The process improvement effort is highly dependant on maintaining an open mind and looking at the process flow with the intent of finding ways to do things more efficiently.

    Hand Offs.  Common process improvement points can be found in those areas on the process map where there are a larger number of hand-offs (process steps moving from one actor to another) or turn-arounds (typically shown as circular process movements back to an originating actor) than you would expect.

    Every time a process is handed off to another actor, there is an inherent risk of time delay based on the large number of hand-off methods that could be used.  For example, if the process calls for the transfer of an information request from a sub-consultant to the project manager, it would be beneficial to identify how those hand-offs typically take place (e.g., via e-mail, faxed form, phone call) to determine if they are being handled in the most efficient and expedient manner possible.  You can then modify the process on paper and discuss it with the actual actors before initiating the actual improvements.  This allows the different players in the process to participate in the improvements that will affect them.

    Turn-Arounds.  “Turn-arounds” are activities where the current actor in the process flow must contact a previous actor for clarification or pass the process back to the left on the chart in order to “advance” the process.  It is important to note that process flow advancement is typically shown by an upper-left to lower-right movement across the diagram.  A turnaround changes the direction of the flow in order to “advance” it.

    Turn-arounds are often seen as an indicator of problem areas in a process.  When you see these on your process flow, ask yourself the following questions:

    • What is happening at this point in the process that requires Actor A to touch this item again?
    • Was there anything we could have done prior to Actor A’s first handing off this item to alleviate the need to pass it back at this point?
    • Is there a way to modify the process so that Actor B can complete this step without passing the process back to Actor A?  If so, what would need to occur/change to make this happen?

    Conclusion

    My experience has shown that swim lane diagrams are extremely effective when mapping out an existing process that touches multiple areas within a project, and especially when it requires multiple people to complete the process.  Remember, this isn’t rocket science.  If there is a symbol you don’t like, replace it.  If you prefer to have your phases laid out as the columns and not rows, do it.  Find what works for you and do it that way.  The key to the successful use of this tool is the actual use of this tool.

    Kurt Sloan

  • Performing Join Queries with NHibernate CreateAlias

    [Updated 6/16/08:  A bug has been fixed in the Supplier.hbm.xml; the current version is now 0.6.3.]

    A common scenario that arises when using NHibernate concerns performing join queries across tables via collection properties. For instance, assume a supplier sells a number of products, each of which belongs to a category. Furthermore, assume that you own an up and coming grocery store set to take over the world if only you could find the right suppliers. To help in your search for the appropriate supplier, you're wanting to perform a query that will accept a category ID and return a list of suppliers who carry products within that category. While there are a number of ways to do this, let's assume that the database will be leveraged to do the filtering for us.

    To begin, what follows is the domain model which includes the objects we're interested in. As shown, each supplier has a one-to-many association with products as an IList . Each product then has a many-to-one relationship with a category.

    Domain Model

    The database model to support this domain is then as follows:


    Finally, HBMs exist are defined to tie the tables to the classes:

    Supplier.hbm.xml

    Product.hbm.xml

    Category.hbm.xml

    The challenge is to create an NHibernate ICriteria to perform a join query from suppliers to a category name, via the suppliers' product collection. As a first attempt, one would typically try to compare the category name to "Products.Category.Name." The reason this approach fails is that NHibernate assumes you're referring to an explicit property name and is unclear as to how the object model should be traversed. The key to the solution is in the use of NHibernate's CreateAlias. CreateAlias allows you to create a simple alias for a collection or object traversal. The following code demonstrates how to solve our current issue using this technique: