The new location is http://nikosbaxevanis.com/feed.xml.
Thank you very much and sorry for any inconvenience this update may cause.
The new location is http://nikosbaxevanis.com/feed.xml.
Thank you very much and sorry for any inconvenience this update may cause.
Posted by Nikos Baxevanis on 09/06/2012 in Feeds | Permalink | Comments (0)
Prior to .NET 4, one had to implement the APM model in order to expose asynchronous methods. After a couple of years, the AsyncEnumerator class came out to simplify the APM by leveraging the use of C# iterators for asynchrony. In the meantime, Microsoft developed a new model for asynchronous (and parallel) programming. Since the new model was targeting the .NET 4, code written in previous versions have to keep using the AsyncEnumerator class.
I have been using the AsyncEnumerator class since 2008 and it works great. Today we have the new Async and Await keywords in C# 5.0 (together with the many improvements in the CLR) that will ship with .NET 4.5 and the recently added support for async unit tests on version 1.9 of the xUnit.net. So, I decided to move some .NET 2.0 code using AsyncEnumerator to .NET 4.5 using Async and Await.
Below is an interface of the sample type (described in this article) exposing both synchronous and asynchronous versions of a time-consuming method:
A unit test with the AsyncEnumerator can be similar to the one shown below:
However, since xUnit.net does not support methods of type IEnumerator<int>, we need to tell xUnit.net how to execute them:
Moving to .NET 4.5 and xUnit.net 1.9 we can create an Extension Method that returns a Task in order to use both the Async and Await keywords in production code and the async unit tests feature of xUnit.net.
Now the previous unit test with the AsyncEnumerator can be rewritten as follow:
This looks very nice and clean. As it seems though, if the class contains many async unit tests they will not run in parallel.
As an example, the following 3 tests will take 3 x 5 = 15 seconds to complete:
The output from xUnit.net:
That was the part of moving the unit tests from an older version of xUnit.net (and the AsyncEnumerator) to version 1.9 of xUnit.net (with Async and Await). Apparently, things become more challenging when moving to production code where one needs to deal with stuff such is the SyncrhonizationContext.
A gist with all the source code can be found here.
Posted by Nikos Baxevanis on 06/05/2012 in Asynchronous Programming, Power Threading Library, Unit Testing | Permalink | Comments (0)
Starting with version 2.10.0, AutoFixture supports the creation of Uniform Resource Identifiers and the Uri type.
It is now possible to create an anonymous variable for Uri as with any other common type:
By default, both the scheme name and the authority part are obtained from the context. A custom UriScheme class represents the URI scheme name while the authority part is an anonymous variable of type string.
Example URIs along with their component parts can be found here. Since both parts are received from the context, they can be easily customized.
Supplying a custom scheme name
The UriScheme type provides by default the name "scheme". However, by injecting a specific instance of this type we can easily override it with something else (for ex. "http").
Supplying a custom authority
Since the authority part is a string received from the context, it is possible to modify the base of all strings and get the desired name for the authority.
This is preferred only when each test constructs its own instance of the Fixture type since this change will apply for all the strings received from the context.
Supplying a custom Uri
As with any other generated specimen, it is possible to completely take over it's creation. Using a custom ISpecimenBuilder type, each time a Uri is requested, a predefined Uri will be returned.
An automatically published release created from the latest successful build can be downloaded from here. The latest version is also live on NuGet.
Posted by Nikos Baxevanis on 19/04/2012 in AutoFixture | Permalink | Comments (0)
An ISV sells ordering and billing systems written in C/C++ and VB6. Each system is consisted of two components and all share a relational database containing Tables, Views and Stored Procedures.
The server component does the data processing, accepting commands from the clients. The commands are stored inside a predefined directory in the form of ASCII-encoded text files. The legacy* command processor repeatedly checks for new text file availability. If a text file is available, it will be processed. This is a continuous process. The only way to update the database is to create and send a command which will be picked up and handled sequentially by the command processor. When a command is handled successfully, the system updates the shared database.
The client component connects to the shared database (accessed in a read-only fashion) to display data on screen and to send pre-defined commands. The client is either a VB6 GUI or a handheld radio device similar to this one.
Nowdays, in order to reach the mobile market, it is quite difficult (and expensive) to maintain and expand the above client as-is. However, since each of the components has no knowledge of the other separate component, the client can be easily replaced.
The new HTML5 client will consume HTTP services. A service here act as the entry point for creating the ASCII-encoded text files which will be picked up by the legacy command processor.
When the application wants to submit data to be processed (by the legacy command processor) it sends a POST request. At this point, the new system creates a message which is send via a Datatype Channel to its receiver.
The receiver, of each particular message, forwards the processing of the command. A compatible text file is created, which will be picked up by the legacy command processor in order to update the database.
When the application wants to retrieve data it sends a GET request. At that point, the ApiController uses a Gateway (and internally Dapper) to access the shared database.
On refresh, the client sends a new GET request and the ApiController will return the updated data.
Now, the client part has to be re-built with HTML5. That way, it will be accessible from the browser, Internet Tablets (similar to this one), and Smartphones.
Initially, Sencha Touch was a very good choice. It even has a designer. There is even Sencha Architect. Everything is written in JavaScript (which is good) and everything runs fast while testing on iPhone, iPad and other similar devices with fast hardware.
The company however is willing to sell the final product to a price which includes the cost of the devices. (That is, a license for 5 users should also include the purchase of 5 mobile devices.) This means that the price for the devices can become orders of magnitude higher than the actual price of the application itself.
The above lead to the fact that the application must ship with a not-so-expensive device. After doing some testing and comparison with other devices, a Sencha Touch application did not perform smoothly in slower hardware (like this one). (The most annoying part was the scrolling.)
After trying everything it looks like jQuery Mobile combined with {{ mustache }} are the best choices in terms of performance. The redistributable file is packed with PhoneGap and the application performs well even on slower hardware giving the flexibility to select among a wide range of mobile devices.
*"Legacy" The definition that Michael C. Feathers gives in his excellent book.
Posted by Nikos Baxevanis on 16/04/2012 in HTML5, REST | Permalink | Comments (0)
In this post I will discuss a possible solution for having Castle Windsor resolving types for both MVC controllers and Web API controllers. Since the former is well known I will focus mostly on the Web API part.
A team building a mobile web application uses the ASP.NET MVC stack combined with another web services framework. With the release of the Beta version of ASP.NET MVC 4 they decided to give Web API a try (side by side with MVC controllers) and see if it fits their needs.
The Controller-derived types are used only for rendering the views (the code is written in JavaScript) while the ApiController-derived types are used for returning data to the client.
The DependencyResolver class provides a method called SetResolver which acts as a registration point for resolving dependencies.
Be careful as there are more than one DependencyResolver types. One defined in System.Web.Mvc namespace and one defined in System.Web.Http namespace. We need the latter here.
Once we define the delegates and set a breakpoint we can see what types the framework requests.
At first an instance of the IHttpControllerFactory type is requested:
Followed by a request for an instance of the ILogger type and so on.
The first thing we want to do is to create a type implementing the IHttpControllerFactory interface.
Note that inside the WindsorHttpControllerFactory class the CreateController method takes a string for the name of the controller. That means we need to use the Windsor's Named method to set a name for each controller registration. (We can also trim the "Controller" part from the name and also pluralize the remaining part.)
Let's also create a NullLogger implementing the ILogger interface.
For all the other instances that the framework requests there are default implementations in the System.Web.* assemblies and we can now create a Windsor Installer to encapsulate the registration logic.
In the Application_Start method we add the installer and set the delegates for the SetResolver method. That way when the framework requests an IHttpControllerFactory instance, Windsor will supply the one we created earlier.
In order to have Windsor resolve regular controllers (side by side) we can create and add another installer as well as an implementation of the IControllerFactory interface.
Finally, a gist with all the source code can be found here.
References:
Posted by Nikos Baxevanis on 16/03/2012 in ASP.NET MVC, ASP.NET Web API, Castle Project, Dependency Injection | Permalink | Comments (0)
From version 2.9.0 of AutoFixture, the Likeness class contains a new feature for creating a dynamic proxy that overrides Equals on the destination type.
As an example, we want to compare instances of the following types:
We can have the following syntax (prior to version 2.9.0):
However, from version 2.9.0 there is also a new CreateProxy method on Likeness which returns a proxy of the destination type overriding Equals with Likeness's instance of IEqualityComparer (the SemanticComparer class):
Below is also an example, where we need to verify that an expectation was met:
Although the new Bar instance is created inside the DoSomething method, we can pass a proxied Bar instance on the mock's Verify method.
Internally, a custom Proxy Generator was written which also supports types with non-parameterless constructors. In order to create proxies of such types, the values from the source have to be compatible with the parameters on the destination constructor. (The mapping between the two is made possible by using the same semantic heuristics, as the default semantic comparison.)
Posted by Nikos Baxevanis on 20/02/2012 in AutoFixture, Test-Driven Development, Unit Testing | Permalink | Comments (0)
I have been using ServiceStack's RestServiceBase class with great success. Because of that I started looking for ways to automate a Layer Test for a simple scenario where a client requests a representation of a resource using GET and/or submits data to be processed to the identified resource using POST.
I found a very nice entry on the wiki and after writting a couple of tests I realized that I was repating the following steps over and over:
One solution is to have the base URI (and even the IRestClient) on a private field inside the test class and use it from all tests. However, a better approach would be to write Parameterized Tests that accept an instance of the IRestClient type.
Fortunately, this can be done using xUnit.net data theories. Furthermore, since the IRestClient is an interface, this is a great scenario for using AutoFixture together with xUnit.net data theories and auto mocking.
Below is a parameterized test:
The AutoWebData attribute provides auto-generated data specimens generated by AutoFixture as an extention to xUnit.net's Theory attribute.
Inside this attribute class we also pass a new instance of the Fixture class customized in order to supply an instance of the JsonServiceClient when an IRestClient is requested. (You can read more about AutoFixture Customizations here.)
The advantage of this approach is that we have abstracted the creation of the IRestClient instance from the test itself. The base URI is now hardcoded in only one place (the customization class). Furthermore, we can easily pass other parameters to the test method if necessary.
While this approach is applied to ServiceStack it can be easily generalized and used on other scenarios as well.
Posted by Nikos Baxevanis on 18/02/2012 in AutoFixture, ServiceStack, Unit Testing | Permalink | Comments (0)
A series of articles exploring the impact of writing tests after the code is written on the implementation part of SDLC.
Sin No.3: Ignoring cross-cutting concerns.
The problem with this approach becomes very clear. It will be hard and tedious work, inside each test, to create stubs and mocks for each and every aspect. The intent of the unit tests will also look wrong since, in reality, these aspects should not be treated as dependencies of the SUT.
Among others, logging and caching are cross-cutting concerns that can easily slip through the services (making us treat them as normal dependencies).
While the preferred way to model these aspects is using decorators and/or dynamic interceptors, there are many times that we see classes violating the SRP containing all-in-one logging, caching, auditing and other aspects (and even violating the ISP with a coarse-grained Header Interface).
Posted by Nikos Baxevanis on 18/02/2012 in Unit Testing | Permalink | Comments (0)
A series of articles exploring the impact of writing tests after the code is written on the implementation part of SDLC.
Sin No.2: Header Interfaces.
A good example is a data access layer combined with the use of an Object-relational mapper (ORM).
While an ORM provides (out of the box) a collection-like interface (ISession, DbContext) for accessing domain objects, most of the time a coarse-grained Header Interface is created on top of that.
Those interfaces usually contain high number of members making the overall architecture extremely inflexible.
The system is usually forced to live with only one implementation for each interface. That implementation is most of the times generalized.
Some examples,
In the second example, the implementation eagerly loads all the entities of an Aggregate Root which hurts performance.
Posted by Nikos Baxevanis on 28/01/2012 in Unit Testing | Permalink | Comments (0)
A series of short articles exploring the impact of writing tests after the code is written on the implementation part of SDLC.
Sin No.1: Production Code First.
By not writing tests upfront, the code becomes most of the times a Transaction Script. It usually lives at application boundaries. If not, then it usually delegates all method arguments to a method with the same name inside a Service Layer.
Most of the times, this code is responsible for aspects such is validation and persistence violating the SRP and likely most (if not all) of the other principles of class design.
Even worse, inside those methods, dependencies might be resolved using a Service Locator (which is not good) forcing us to mock the container (if that's an option at all) in order to successfully write unit tests afterwards.
At the end, a lot of time is spent to write a few Fragile Tests, resulting in a system which is (in most other places) not covered by tests at all.
Posted by Nikos Baxevanis on 28/01/2012 in Unit Testing | Permalink | Comments (0)