Tuesday, November 4, 2014

NServiceBus Configuration API Webinar - errata corrige

In september I had the opportunity to drive the "Mastering NServiceBus Configuration API" webinar. The webinar recording can be found here: https://particular-1.wistia.com/medias/q8tdr6mnzz


This post is a sort of "errata corrige", a few things need clarification:
  • at minute 18: I said that "we can rely on DI in a INeedInitialization" implementation: wrong, we cannot. At this stage we cannot resolve any components yet, what we are guaranteed is that the container is setup and injected in NServiceBus so we can register components not yet resolve them;
  • At min 35: there is a self-hosting sample, since now the IBus interface implements the Idisposable interface it is much better to change the sample code using the "using" pattern, in order to correctly shutdown the bus:
    using( var bus = Bus.Create( cfg ) )
    {
        bus.Start();
        Console.Read();
    }
  • the AsAClient role is for SendOnly endpoints: wrong, the difference between AsAClient and AsAServer roles is the client one turns off transactions, SLR, Timeouts and purges queue at startup.
  • At min 45.40: talking about registering steps in the pipeline, I said the InsertAfter/Before is right after/before: it is not accurate, the registration just guarantees that the step is inserted after or before another step, it does not guarantee that it will be inserted right after or before, so there could be steps between the new registered step and the one that was configured to be after or before.
Thanks to John Simons (https://twitter.com/johnsimons_) for reviewing the material and highlighting the above issues.

Thursday, August 21, 2014

ASP.NET Web API Succinctly

Last week while travelling to London I had the pleasure to read “ASP.NET Web API Succinctly” by Emanuele DelBono, the book is part of the Syncfusion technical collection and I must admit that it is simply complete despite its brevity, I read it in not more than 2 hours.

Emanuele starts with a brief introduction to what REST is and to its philosophy, to deep dive into the ASP.NET Web API technical aspects and into how REST combines with the Web API technology.

The technical part of the book is the perfect combination between simplicity and in-depth analysis, given the nature of the book collection, everything is faced with the expected complexity rate, enough to give to the reader the information required to start moving with its own feet but much more enough to give all the information required to start diving into Web API topics independently. Topics that ranges from the routing engine to security management passing through the Web API extensibility pipeline.

A must read.

.m

Monday, April 28, 2014

RavenDB and the LoadDocument feature

To make a long story short: handle with care.

The long story…

In a relational world you must live with joins, full stop. It is not a problem neither an advantage it is a sort of a non-functional requirement, this is it, a relational model most of the time requires joins.

If you have in your object model a Person class with a list of Addresses it will be stored in 2 different tables and in order to load them there are 2 options:

  • shoot yourself in a foot and perform 2 queries;
  • issue a join and in one single round-trip to the db get all the data;

When it comes to document modeling in a non-relational world the available options are a bit more and ranges from model your document in a relational fashion (most of the time shooting yourself in a foot) or model them in a document oriented manner.

Modeling in a document oriented manner open up to an infinite range of options because it barely depends on the context, the usage, the type of the application and much more. For the purpose of the article consider the above Person class, one solution in a document database is the following:

{
   firstName: 'Mauro',
   lastName: 'Servienti',
   addresses: [{
      country: 'Italy',
      city: 'Milan'
   },{
      country: 'Ireland',
      city: 'Dublin'
   },]
}

We can embed everything in one single document with the consequence that we do not need a join to load the entire data set, it is one single trip in all the cases.

Nothing forces us to model the solution as in the above sample, even if is a good approach, we can model the solution in a relational fashion even if in this case will be the worst solution but in the end I’m just trying to find a simple sample use case for the LoadDocument feature :-)
What we can do is store persons and addresses as separate documents introducing a relation (application level relation) between them, something like:

{
   id: 'people/123',
   firstName: 'Mauro',
   lastName: 'Servienti',
   addresses: [ 'addresses/123' ]
}

{
      id: 'addresses/123'
      country: 'Italy',
      city: 'Milan'
}

There are valid use cases for the above choice, what we immediately lose is the ability to easily search a person given an address because with the first design choice we can define an index such as the following:

from doc in docs.People
select new 
{
   Content = new object[]
   {
      doc.FirstName,
      doc.LastName,

doc.Addresses.SelectMany( x => x.City ) } }

and we immediately get full text search capabilities even on addresses, and that is pretty cool. In the second scenario with separate documents the application must decide where to search and if we need to search as in the first scenario we need to issue 2 search queries.

LoadDocument to the rescue

from doc in docs.People
let addresses doc.Addresses.Select( x => LoadDocument(x))
select new
{
    Content = new object[]
    {
        doc.FirstName,
        doc.LastName,
        addresses.SelectMany( x => x.City )
    }
}

The above index definition solves the problem, we have basically defined a join in an index that at indexing time will load related documents and indexes also their content.

Handle with care

What we need to take into account, if we decide to use the above feature, are the side effects that the above decision introduces. Under the hood what RavenDB does is to keep track of the fact that we have defined the relation, in the index, between a bunch of documents, this is done so that whenever an address document changes the index will be marked as stale simply because this is the expected behavior otherwise the above index will always produce stale results.

Think about it for a minute: keeps track of the relation to re-evaluate the index at each related document change.

Once again: …at each related document change…

Why am I telling all this?

Simply because we have clearly outlined something that can be a real problem if not handled with care, imagine a scenario where you have a huge team of experienced developers migrating an application from a relational model to a document based model where they approach the migration in a relational manner, as in the second sample, introducing indexes with a lot of “load documents” (where “a lot” means more than 10 per index) everywhere.

trust me, the result is a nightmare :-) it surely works, on the developer machine only…

.m

Tuesday, April 1, 2014

NServiceBus endpoints aggregation

When developing a distributed solution using NServiceBus one the usual caveat is that you end up with tons of projects in the solution just to mimic the deployment topology of the production environment.

note: it is not a NServiceBus issue, it is in the nature of the distributed development process.

Currently there is an open issue, in the GitHub repository, followed by an interesting discussion where the core of the issue is a request to support multiple endpoints in the same host, hosting each endpoint in a different AppDomain so to have per endpoint configuration.

Do we really need it?

I mean: do we really need different configurations for each endpoint? my general answer is that at development time this is generally not a real issue. Why am I focusing on the development time? because if you dive into the above discussion what emerges is that the annoying issue is having too many processes that start, and that need to be maintained, during the development process.

So?

The new question now is: can we, on the developer machine, merge everything down in a single host process? if configurations can be “merged”, without generating conflicting configurations, the answer is simply yes.

How?

The first thing is to understand what happens when we bootstrap the bus via the NServiceBus configuration API or using an EndpointConfig class. NServiceBus scans all the assemblies looking for message handlers, sagas and classes that implements NServiceBus configuration interfaces, such as but not only, IConfigureThisEndpoint.

Given the fact that all this process is done via reflection looking in the “bin” folder what prevents us to:

  • Create a dummy class library project that will be used only on the developers machines;
  • Add a reference via NuGet to the NServiceBus.Host package;
  • Define our endpoints and sagas and all the rest related to the business logic in another, or lots of them as per the deployment topology, class library project;
  • Add a reference to the business logic into the dummy host project;
  • Define all the configuration in the config file of the dummy project;
  • Run the dummy project on the developer machine;

In the end we can think about hosts only as aggregation services whose only role is to give us all the plumbing required to live in the operating system that is hosting us. All what we need now are a bunch of scripts and config transforms that can split down pieces to prepare segmented hosts to be deployed in production.

We are currently using the above approach to manage a pretty complex solution that in production is deployed into 16 different windows services, on several machines, but on the developers machines is made of 3 dummy hosts, why 3 and not 1? configurations :-) we aggregated all the endpoints that conceptually share the same configuration, ending up with 3 main groups.

.m

Wednesday, March 12, 2014

Azure ACS relying party configuration: weird, but correct behavior.

Every time I do it I do it wrong and it takes me too much time to remember why it is wrong.

Let me explain the situation:

Everything seems fine and correct…fail…it does not work, when you try the application the result is:

  • Request to https://mydomain.com;
  • The authentication process kicks in and redirects to the Azure ACS hosted login page;
  • The use choses the authentication provider and perform the login;
  • The authentication provider redirects back to the ACS that redirects back to your application @ https://mydomain.com/FooBar;
  • HTTP 405, Method Not Allowed :-\

Can you spot the bug?

The return Url definition misses the trailing “/”, it must be https://mydomain.com/FooBar/, but why?

Because the process is not so simple as we can expect:

  • ….bla bla bla…
  • The authentication provider redirects back to the ACS that redirects back to your application @ https://mydomain.com/FooBar/ via a POST request;

When you perform a request to the extension less MVC Url handler the Url handler mst append a trailing / to the Url, if missing, otherwise all the runtime evaluated links on the client side will be wrong, in order to do that the handler can only perform a redirect to the same Url with the “/” appended, a redirect is generally dropped and not honored if the HTTP verb is POST, and for a good reason.

.m

Thursday, March 6, 2014

AngularJS, UI Router and Breadcrumbs: easy peasy

AngularJS is simply amazing, the intrinsic power of its architecture and the nature of JavaScript (with which I go on in a love & hate manner) gives us so much power that we cannot fall in love with it.

UI Router

AngularJS has a built-in routing engine (that in the later versions has been detached from the core and transformed into a plug-in) that is really similar to the Asp.NET MVC routing engine, for whom has experience with it.

But…I strongly suggest to give a try to the AngularJS UI Router plug-in that replaces the default routing engine introducing a routing engine that is conceptually based on a state machine, where states are identified by routes (or route matches), take a look at the following sample configuration:

$stateProvider.state('viewById', {
    url: 'view/{id}',
    views: {
        '': {
            templateUrl: 'itemView.html',
            controller: 'itemController'
        }
    },
    data: {
       settings: {
           displayName: 'View Item'
       }
    }
})

 

We are using the state provider, from the UI Router, to define route states, telling it that there is a state called “viewById” that matches the given url, in this case with parameters, and that when matched should inject in the AngularJS UI composition engine the given view and controller in the default (unnamed) view.

ne of the really powerful aspect of the UI Router is that it introduces the concept of route hierarchy, we can define routes in the following manner:

$stateProvider.state('sample', {
    url: '/sample',
    ....
})
.state('sample.item', {
    url: '/{id}',
    ....
});

Notice the “.” in the definition of the second route, it identifies a parent/child relationship between 2 routes, in the above sample the “sample.item” route is child of the “sample” route, thus the url of the second route is “/sample/{id}”, a composition.

Data…data?

The data object does not exist on the state object, it is there thanks to the dynamic nature of JavaScript that let me append anything to an existing object, powerful and risky too, but powerful :-)

We are currently using it t append some custom information to the state itself, in this case the display name.

Breadcrumbs

Ok, now…our aim is to build something like the following:

image

Given a route, the highlighted one in the address bar, we want to display a breadcrumb automatically generated, with the ability to customize what the breadcrumb displays for each of the items.

First things first: HTML

From the UI point of view we want to be able to simply define the following:

<breadcrumbs></breadcrumbs>

Nothing else, full stop. Given the above markup the generated result will be the following: Expenses Accounts –> Account, where all the display values are retrieved (how in a few lines) from the current state of the UI Router.

Given the requirement that we want to customize all the values:

<breadcrumbs item-display-name-resolver="myResolver(defaultResolver, state, isCurrent)"></breadcrumbs>

We can introduce our own display name resolution logic.

Walking like a shrimp :-)

Since we are going backward let’s move on backward ;-)

$scope.myResolver = function (defaultResolver, state, isCurrent) {
    if (isCurrent) {
        return '"' + item.name + '"';
    }

    return defaultResolver(state);
}

In the controller of the view where the breadcrumbs directive is defined we can attach to the current $scope our custom resolver, what the resolver gets as inputs are:

  • the default built-in resolver that can be called in order to get the default value;
  • the current state object of the UI Router;
  • an isCurrent Boolean value that can be used to determine is the state object represents the current state, basically the last in hierarchy chain, or if we are still walking down the tree;

What the controller does, given that the “item” object instance represents the current item we want to display, is simply say that if we are trying to build the display value of the last state, the current one represented by the url, the name property of the object is returned, otherwise let the default resolution logic kick in and do its job.

The directive

Finally we can give a look at how the breadcrumbs directive is defined, starting from the template:

<ul class="breadcrumbs">
    <li ng-repeat="state in $navigationState.currentState.path">
        <span ng-if="!$navigationState.isCurrent(state)">
            <a href="#{{ state.url.format(params) }}">{{$navigationState.getDisplayName(state)}}</a>
            <span class="glyphicon glyphicon-chevron-right"></span>
        </span>
        <span ng-if="$navigationState.isCurrent(state)">
            {{$navigationState.getDisplayName(state)}}
        </span>
    </li>
</ul>

As simple as an UL with a repeater that iterates over the state hierarchy, the path property of the currentState represents the state tree, and if the state is the current state simply adds a SPAN element, otherwise adds a SPAN with an A to create a hyperlink to allow navigation, preserving the state parameters, that is really important (state.url.format( … )).

From the code point of view what we have is pretty simple:

(function () {

    angular.module('radical.directives')
        .directive('breadcrumbs', ['$log', '$parse', '$interpolate', function ($log, $parse) {
            return {
                restrict: 'EA',
                replace: false,
                scope: {
                    itemDisplayNameResolver: '&'
                },
                templateUrl: 'directives/breadcrumbsDirective.html',
                controller: ['$scope', '$state', '$stateParams', function ($scope, $state, $stateParams) {

                    var defaultResolver = function (state) {

                        var displayName = state.data.settings.displayName || state.name;

                        return displayName;
                    };

                    var isCurrent = function(state){
                        return $state.$current.name === state.name;
                    };

                    var setNavigationState = function () {
                        $scope.$navigationState = {
                            currentState: $state.$current,
                            params: $stateParams,
                            getDisplayName: function (state) {

                                if ($scope.hasCustomResolver) {
                                    return $scope.itemDisplayNameResolver({
                                        defaultResolver: defaultResolver,
                                        state: state,
                                        isCurrent: isCurrent(state)
                                    });
                                }
                                else {
                                    return defaultResolver(state);
                                }
                            },
                            isCurrent: function (state) {

                                return isCurrent(state);
                            }
                        }
                    };

                    $scope.$on('$stateChangeSuccess', function () {
                        setNavigationState();
                    });

                    setNavigationState();
                }],
                link: function (scope, element, attrs, controller) {
                    scope.hasCustomResolver = angular.isDefined(attrs['itemDisplayNameResolver']);
                }
            };
        }]);

})();

Lots of code, I am assuming that the reader has a basic knowledge of how AngularJS directives works. Let us concentrate on the controller, where the interesting part is:

  • we depend on the $state and $stateParams object of the UI Router, and on our $scope, in this case the directive has its own isolated scope;
  • we define the default resolver that looks for our data object on the state and fallbacks to the state name if no data object can be found;
  • we define the logic that determine is the current state is the last in the hierarchy;
  • we define the logic to build the navigation state:
    • in the navigation state there is the logic that can handle custom display name resolvers;
  • we finally hook the navigation event we are interested in to sync the navigation state;

An AngularJS directive is not a simple concept but in this case we can say that building a breadcrumb is an easy peasy, lemon squeezy story :-)

.m

Tuesday, December 17, 2013

AngularJS: modules 2 phase startup

Index:

Now that we have modules it is time to try to understand what we can do with modules and why we need them in the end.

Let us start by saying that if we define something this something must be registered in a module, we’ll see soon what is the meaning of “define”. Going on with our comparison with the .net world, if we define a class this class must be defined in a namespace, or at least in an assembly.

At startup AngularJS iterates over all the referenced modules, declared and dependent, and performs its 2 phase startup:

  • Configuration Phase: each module has the option to execute a “config” phase, during this phase a module cannot rely on any other module since nothing is guaranteed to be configured or running at this time;
  • Run Phase: each module has the option to execute a “run” phase; at this time each module is guaranteed to be at least configured, so we can rely on other modules during this phase;

In order to hook in these phases we can write the following code:

<!DOCTYPE html>
<html>
<head>
    <title>My First Sample</title>
    <script type="text/javascript" 
            src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
    <script type="text/javascript">
    (function () {
      'use strict';
      
      var app = angular.module('my-app', []);
      app.config(function(){
        console.log('App config phase');
      });
      
      app.run(function(){
        console.log('App run phase');
      });
      
    }());
    </script>
</head>
<body data-ng-app="my-app">
    <input type="text" data-ng-model="name" placeholder="Write something here..." />
    {{name}}
</body>
</html>

Obviously we are not required to hook both phases.

We said that during the run phase, for example, we can rely on other modules. What does this means and how can we do that?

app.run(['$log', function($log){
        $log.debug('App run phase');
 }]);

We can replace a part of the above code with the sample just provided and see what happens looking at the browser console.
As you can imagine we are injecting dependencies into the run phase of the module: Dependency Injection will be our next topic.

Stay tuned.
.m