Posts in English

.NET is not an enterprise application platform (yet)

…Windows is. If you have been convinced by Microsoft that .NET is an application platform for the enterprise, here is a list of arguments proving that it is not (yet).

  • IIS is not an application server. All it provides is serving dynamic web pages and hosting WCF web services.
  • AppFabric have not delivered on its promise. Nobody is using workflows so the only widely usable part of it is the distributed cache (which, I must admit, is nice).
  • IIS does not allow to host scheduled tasks. For these you have to use Windows Scheduler which operates on OS level.
  • IIS does not work well with custom threading models so things like NServiceBus have to be hosted as Windows Services.
  • IIS does not have a decent monitoring & management story. You have to use WMI which, again, is an OS level service that does not speak .NET language and is quite cumbersome do use.

Convinced? So here’s a list of things which you, as a developer, can do to fix this problem

  • Extend IIS or create a complementary service that can use the same model as IIS (one core process per system + process per application) that would host scheduled tasks and could incorporate custom threading models thus allowing to run things like NServiceBus.  TopShelf would be a good starting point.
  • Assembly is not longer a good deployment unit — it is too small. Provide a packaging system that would allow to package several assemblies (a functional module) together. Such a module could be easily deployed (and undeployed) from the application server as a whole.
  • Create a decent scheduling library. The only one there is, Quartz.NET, is probably one of the oldest .NET open source projects still in use. It desperately needs a replacement that follows today’s design practices.
  • Think about how you could contribute to NetMX or come up with a completely new, lightweight, monitoring & management framework.

Having all these things built, it would be quite easy to assemble an open source private cloud infrastructure. The goal would be to have a farm of servers running either Windows or Linux/Mono that can be treated as one logical machine to which I can easily deploy all kinds of components including (but not only)

  • web applications (using various MVC frameworks)
  • scheduled services
  • message consumers (using various frameworks like NServiceBus or MassTransit)
  • web services (using, again, variety of frameworks like WCF or OpenRasta)

delivered in easy to use packages.

    VN:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)

    Global Day of Code Retreat

    Last Saturday I attended the second Kraków Code Retreat which was a part of the Global Day of Code Retreat. The event was organized by Kraków Software Craftsmanship society, [sckrk].

    The organizers did a great job preparing the meeting. There was even a coffee machine for those who, like myself, can’t start a proper coding day without a cup of coffee (or two). Because the event started so early (between 8 and 9 AM), the organizers ensured that we have sandwiches for breakfast. It was a very nice surprise.

    On the contrary, the form of the event was not a surprise for me. Partially because I attended the previous code retreat [sckrk] organized in April and partially because the form of these events is pretty much standardized. There are 5-7 sessions, each about 45 minutes long. During each session we try to solve exactly the same problem (the most popular one is Conway’s Game of Life) the best way we can. The assumption is that we work in pairs and we all employ TDD. The amount of time is calculated in such a way that it should be very difficult to finish the solution. The reason for this is, during a code retreat, you should not focus on getting things done but, instead, on writing the most beautiful code you can.

    I was quite surprised by the fact that we (I paired with Piotr Leszczyński for this session) managed to solve the problem within the provided time frame. Especially given that I did not manage to solve it during the event in April. The key to our ’success’ (remember, it’s not the completeness of the solution what matters here) was probably the fact that we both have had some experience in both pair programming and TDD. What is more, we did practice these disciplines together in some point in time. I really enjoyed these 40 or so minutes. It would be worth attending the event even for this one session. On the solution side, it was not particularly clever or beautiful. It was not purely object oriented and some abstractions were missing. But my feeling was it was a good SOLID code. The downside of having a complete solution in first try was that I was under it’s influence for the rest of the day. It was hard to think in a completely different way.

    The effect was, I spent two sessions refining this solution. One of the improvements was making the coordinates a class on its own. It encapsulated the way neighbourhood (the key concept in Game of Life) is defined. We didn’t have enough time to make the last step and make our game board generic of T where T is an implementation of some Coordinates. It would make changing the coordinate system (for example to spherical or 3D) a trivial task.

    The other improvement was made in the method that returned neighbouring coordinates for a given coordinate. In the first solution we just hard-coded it like this:

    yield return new Coordinates(x, y - 1);
    yield return new Coordinates(x, y + 1);
    ...
    yield return new Coordinates(x + 1, y);
    

    The improved solution looked like this:

    return (from x in Enumerable.Range(-1, 3)
    from y in Enumerable.Range(-1, 3)
    select new Coordinate(x, y))
    .Except(this);
    

    It puts grater emphasis on the intent. It would be even better if Enumerable.Range method has min and max parameters instead of min and count.

    Like I said before, one of the assumptions of core retreat is to test drive the design. The problem with this approach is, it is hard to force a completely different solution only be means of writing proper tests. I wanted to try something different so I convinced Piotr to leave TDD aside for one session. We agreed to use test-first approach but implement the design I proposed. Piotr suggested that we should also refrain from writing any conditional statements (if, switch). This sounded like a fair deal.

    What we tried was an actor-based approach. Every cell was an actor which was able to respond to various events. The environment was responsible for routing these events so that cells get events generated by their neighbours. The solution was turn-based so that in the beginning of each turn every cell got events from other cells and at the end — a clock event from the environment. The response for this event could be either ‘alive’ or ‘dead’.

    The other interesting thing about this solution was, it allowed us to get rid of conditional statements in a quite elegant way. We used a state pattern to process the events:

    public interface IState
    {
       IState ConsumeAliveEvent();
       IEvent GetResponse();
    }
    

    There can be four possible states in the game: base (cell will die in next round), after consuming one alive event (will also die), after two (will survive), after three (will survive) and more than three (will die).

    Unfortunately we didn’t have enough time to finish the code, but it was quite promising. Especially the tests which were in form of statements like this

    given these (events) happened, the cell should generate these events

    In quick summary I would like to encourage you to take part in every code retreat event that is organized in you neighbourhood. It is really worth it, event if you have some experience in TDD and/or pair programming.

    VN:F [1.9.13_1145]
    Rating: 5.0/5 (3 votes cast)

    Events are not an implementation detail

    When listening to many discussion about Domain-Driven Design and Event Sourcing, subjects which I am recently very into, sometimes I have a feeling that events are considered merely a way of persisting aggregates. People tend to discuss benefits events have with regards to storing historical data, having possibility to generate any read model out of events and so on. Reducing event sourcing to such ‘housekeeping’ duties is castrating your architecture.

    This point of view is expressed in a way people model their event-based solutions: thinking first about the aggregates and then, within each aggregate, about events they generate. Sometimes the process is even more event-UNcentric when people first implement a command and then start thinking about what event types should be created.

    Given the fact that most Event Sourcing practitioners have a background in DDD, we tend to bring our experience from working in data-centric environment to the event-centric world. There is, however, a fundamental difference between these two.

    When building a behaviour-oriented DDD solution on top of a data-centric infrastructure (a database) you do your best to hide the database and its schema from the business layer. Over the years we learnt that it is better treated as implementation detail because it does not provide concepts useful to model behaviour. There concepts must be built on top of it. The underlying data layer must not be visible to the outside world because of it’s volatility — it has to change whenever the behaviour it supports needs to change.

    On the other hand, when building a similar solution on top of event-centric infrastructure you can (and should) leverage events to model the behaviour. They (not aggregates or anything built on top of them) are the central concept here. Whenever business changes, new event types appear and some old are no longer generated but no event is ever lost. Whatever happened, happened.

    Returning to my original thought, in an event-centric solution aggregates should not be treated as first-class citizens. Don’t get me wrong, they are very useful. In a healthy design probably a vast majority of events would be generated via aggregates, but some would not. Aggregates are priceless when it comes to modelling concurrency and to encapsulating business logic.

    You may now want to ask a question when should you use aggregates and when not? The answer seems to be simple. Whenever your system needs to respond to some external activity, you just directly inject an event representing what have happened into your system. The idea is, again, whatever happened, happened. You can’t throw concurrency exception at The World saying it is wrong to raise this event right now. You have to humbly acknowledge the fact and record the information. On the other hand, when it is your system who conducted the activity to be communicated by an event, you should use an aggregate to have full control over how and when the event is published.

    Have fun building event-centric solutions!

    VN:F [1.9.13_1145]
    Rating: 4.8/5 (4 votes cast)

    What kind of manager are you?

    Few weeks ago I have become a true manager in the sense I have 3 people I have to take care of. My responsibility is managing all aspects of software ‘construction’ (meaning coding). For those of you who don’t know me, I spent all my career (something like 6 years) trying to avoid any management roles. And now I had to step into this role of manager. First thing I’ve done was asking myself what kind of manager I am going to be.

    The answer is complex because it is based on several factors. One of them is my personal preference. The other is my capabilities. And so on and so forth. Somewhere in the middle lies what’s achievable and feasible.

    I believe it is very important to think about it for a while. We are not created equal and there is certainly not only one good management style. If you want to blindly mimic someone else’s style (no matter how good it is) you are going to fail because you are different. You have different strong (and weak) points. Something that works for your colleague may not work for you and vice versa.

    Take a look at me as an example. As I said, I have quite strong software engineering background. Technical excellence gives me professional self confidence and courage to say ‘no’ whenever I feel it’s necessary. Because of my activity in the community (both on-line and off-line) I have quite a few friends in the field. I also enjoy teaching. Last but not least I think that if you want to do something you better do it well or don’t touch it at all.

    All of these define the style of management I am going to use. I am more reluctant to cut corners and thus compromise quality so I am not a good candidate to manage a short project with critical deadline. On the other hand I may be the right guy to run a long term project with quickly changing requirements (good code quality makes changing easy). I will object whenever quality of our product is in danger and you better have good arguments when you try to hurry my team. I will say ‘no’ and won’t be afraid of consequences because you’re not the only software house in town, right?

    Because I am a bit shy and from time to time I even think about myself as a sociopath, I am not going to entertain my team. Probably working on my team won’t be the best social experience you can get and my people won’t be super-integrated. On the other hand, they can get technical guidance of much higher quality than from an average manager. They may be sure that if I have a cool piece of work I won’t do it myself but instead I will give it to the guy who can benefit most from doing it.

    That’s the kind of manager I want to be. Long project, small team, focus on quality and on growing people. There are only a few things I can offer to my team

    • no hurrying or overtime
    • technical advice (code review, pair programming)
    • tasks that correspond to your interests
    • no obstacles (I will take care of shitty CI server and a annoying business analyst)

    but I believe it is enough for them to grow and become independent very quickly and for the project to maintain high quality level.

    And what kind of manager are you? Or what kind of manager you would like to have?

    VN:F [1.9.13_1145]
    Rating: 4.0/5 (1 vote cast)

    Classic DDD example, renewed

    I’ve spent some time recently renewing my old DDDSample.NET project. I understand that it is the projection of my subjective and uninformed view of Domain-Driven Design, but still I see a value in having some implementation compared to having nothing — it provokes discussion. That’s why I will continue to invest my time in it. If you happen to read this and want to take a look at the code, please remember that is is a sample (as the name suggests), not a guidance. The difference is following: a sample shows how I am doing things while a guidance would show how you are supposed to do things.

    Journey through the stack trace

    Classic version of DDDSample is a web application with simple UI created with ASP.NET MVC. This is where all starts. I would like to take you on a journey through the stack trace to explain various architectural decisions. Let’s register a new handling event.

    NHibernateAmbientSessionManager

    The very first class that gets a chance to process the request is NHibernateAmbientSessionManager. It is responsible for creating an ambient NHibernate session that will be bound to the request. After processing the request the session is released. It can be accessed anywhere in the code statically through CurrentSessionContext class. This is a built-in feature of NHibernate.

    public void CreateAndBind()
    {
        CurrentSessionContext.Bind(_sessionFactory.OpenSession());
    }
    public void UnbindAndDispose()
    {
        var session = CurrentSessionContext.Unbind(_sessionFactory);
        if (session != null)
        {
            session.Dispose();
        }
    }
    

    HandlingController

    Next is the HandlingController and it’s RegisterHandlingEvent method/action

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult RegisterHandlingEvent(string trackingId, DateTime? completionTime, string location, HandlingEventType type)
    {
        if (!completionTime.HasValue)
        {
            ViewData.ModelState.AddModelError("completionTime", @"Event completion date is required and must be a valid date.");
        }
        if (!ViewData.ModelState.IsValid)
        {
            AddHandlingLocations();
            AddHandlingEventTypes();
            return View();
        }
        _handlingEventFacade.RegisterHandlingEvent(completionTime.Value, trackingId, location, type);
        return RedirectToAction("Track", "Tracking", new { trackingId });
    }
    

    There’s nothing fancy here, but is shows in a nice way that in this design, the responsibility of a controller is data validation and parsing (mostly done by MVC internals). After ensuring that data conforms to the required format, it is passed to another class which is…

    HandlingFacade

    This class hides the design of internals of the application from the UI. As far as controllers are concerned, business logic is implemented in façade’s methods. The truth is slightly different, however.

    public void RegisterHandlingEvent(DateTime completionTime, string trackingId, string location, HandlingEventType type)
    {
        var command = new RegisterHandlingEventCommand
                            {
                                CompletionTime = completionTime,
                                TrackingId = trackingId,
                                OccuranceLocation = location,
                                Type = type
                            };
        _pipelineFactory.Process(command);
    }
    

    All the façade is doing is packing the arguments into a command object and sending this command to the pipeline where it is processed. Why create a separate class instead of putting this method on the controller? I like my controllers to be concerned only by the UI and have only one reason to change.

    NHibernateTransactionCommandFilter

    Before the command is actually executed, a number of filters are invoked. I use a very simple command pattern implementation I’ve written a few weeks ago for the sole purpose of using in DDDSample. It allows me to define these filters in a nice (again, subjective view) way

    public void OnHandling(object command)
    {
        _ambientSession = CurrentSessionContext.Unbind(_sessionFactory);
        _session = _sessionFactory.OpenSession();
        _transaction = _session.BeginTransaction();
        CurrentSessionContext.Bind(_session);
    }
    public void OnHandled(object command, object result)
    {
        CurrentSessionContext.Unbind(_sessionFactory);
        _transaction.Commit();
        _session.Close();
        CurrentSessionContext.Bind(_ambientSession);
    }
    

    Before handling a command an aforementioned ambient NHibernate session is unbound from the current context. We are not going to use it while processing the command because we need a clear workplace. We open a new session and a a new transaction. Whatever happens in the command handler, stays in the command handler. After a command succeeds we unbind the session it used and commit the transaction. Then we restore the ambient session so that UI can use it.

    Why don’t we just use a transaction on this ambient session? There is a couple of reasons. First, there can be a transaction started before processing the command and we don’t want to take part in it. Second, we want to be absolutely sure we don’t have any entities in the session-level cache. Why? Because we might use some hints to fetch them more efficiently in context of command processing (like for example force eager load on some relations). And last but not least, if command fails we don’t want to break the session UI was using because it may need it for whatever reason after the command processing attempt failed.

    The corollary of this is, we don’t want to put any persistent (tracked by NHibernate) into the command. If we allowed this, we could attach it by mistake to this other session and very strange things could happen. The side effect is we can safely serialize commands which allows us, if the need comes, to put our domain model on a separate tier then its client (the web application).

    RegisterHandlingEventCommandHandler

    When we have the new session and transaction in place it’s time to do the actual work. Here’s how a typical command handler look like

    public object Handle(RegisterHandlingEventCommand command)
    {
        var trackingId = new TrackingId(command.TrackingId);
        var cargo = _cargoRepository.Find(trackingId);
        var occuranceLocationUnLocode = new UnLocode(command.OccuranceLocation);
        var occuranceLocation = _locationRepository.Find(occuranceLocationUnLocode);
        var evnt = new HandlingEvent(command.Type, occuranceLocation, DateTime.Now, command.CompletionTime, cargo);
        _handlingEventRepository.Store(evnt);
        return null;
    }
    

    The idea here is to have only one method or constructor invocation on an Aggregate Root in one command. As you can see, command handler’s responsibility is to convert the raw data from the command to the proper Value Objects. The validation of data is performed when constructing VOs. In this case we create a new AR so we first instantiate a new object and then call repository to store it.

    HandlingEventRepository

    What happens in the repository?

    public void Store(HandlingEvent handlingEvent)
    {
        Session.Save(handlingEvent);
        _eventPublisher.Raise(handlingEvent);
    }
    

    Two things. First, we save the newly created AR to the command’s session. Then we use an Event Aggregator to publish this AR as an event. I based this approach on Eric Evans’ What I’ve learned about DDD since the book presentation where he explains that in many domains you encounter Aggregate Roots that are immutable. He calls them Events.

    CargoWasHandlerEventHandler

    The Event Aggregator publishes the event to all interested parties. In our case there is only one

    public void Handle(HandlingEvent handlingEvent)
    {
        handlingEvent.Cargo.DeriveDeliveryProgress(handlingEvent);
    }
    

    It calls a method on a Cargo Aggregate Root to notify it about the event. One thing worth notice here is we are doing it synchronously in the sample but our contract does not guarantee synchronicity. We write our event handlers in such a way that they can be executed asynchronously to the transaction that published the event. It is good to have such possibilities open in case we need to scale.

    Cargo

    This is how we reach the Cargo AR

    public virtual void DeriveDeliveryProgress(HandlingEvent lastHandlingEvent)
    {
        Delivery = Delivery.DerivedFrom(RouteSpecification, Itinerary, lastHandlingEvent);
    }
    

    The method looks very simple and it is not a coincidence. In classic DDD we have limited testing options since we can’t set our Entities to proper state easily (as easy in if we use Event Sourcing). That’s why we don’t want to test Entities. We want to test Value Objects because they are immutable and truly persistence ignorant. All we do in an Entity is pass the arguments to a VO and replace the current value with a new one. The probability that we make a bug in this one-liner is small, at least I hope so.

    Delivery

    Finally we arrived at our destination, the Value Object. Here I won’t include any code as it is quite complex and lengthy. I’ve already said probably the most important thing about VOs in this approach: they are immutable. This property allows us to test them easily. The compromise we are willing to accept in regards to Value Objects is, we expose their state via properties. Because we don’t have Command and Query Responsibility Separation, we use same objects (but remember, fetched via different session) to read and to write.

    Summary

    I hope you enjoyed this journey through the layers of the onion. Remember that this is just a sample. Most of its features were tested in the field but some combinations of them were not. I am eager to hear what you think about this approach and also to hear about your approach to DDD when size and/or complexity does not justify CQRS.

    VN:F [1.9.13_1145]
    Rating: 5.0/5 (2 votes cast)