You are currently browsing the category archive for the 'Development' category.

As always, business requirement went over existing code base to ask for a minor change that wasn’t compatible with our existing infrastructure: all surrogate keys are unique identifiers (Guid) and all infrastructure was built around that. The business people asked to add to an existing domain entity a natural key - integer identity number (auto increment field), to serve as a reference number.

We had two choices:

  • to generate the identity from business code
  • to let database manage it for us.

The second approach it preferable for us because it’s the database’s job to generate the keys.

Out of the box NHibernate doesn’t support such a thing. Answers to my question in NHibernate Users discussion group led to the next solution.

Given the class:

public class Entity
{
    public int Id { get; set; }
    public int Id2 { get; set; }
}

First “Id” is the primary key, the second is the key that we want to map to identity column. To have that done we should do two things:

  • Map “Id2″ property as “generated”
  • Use “database-object” to drop the column generated by NHibernate & create new one, with IDENTITY set on.

The complete mapping:

<hibernate-mapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    namespace="NHibernate.Playground"
    assembly="NHibernate.Playground"
    default-lazy="false" xmlns="urn:nhibernate-mapping-2.2">
  <class name="Entity">
    <id name="Id">
      <generator class="increment" />
    </id>
    <property name="Id2" type="int" generated="always" insert="false" />
  </class>
  <database-object>
    <create>
      ALTER TABLE Entity DROP COLUMN Id2
      ALTER TABLE Entity ADD Id2 INT IDENTITY
    </create>
    <drop>
      ALTER TABLE Entity DROP COLUMN Id2
    </drop>
  </database-object>
</hibernate-mapping>

I like the flexibility offered by NHibernate. Even if you don’t have required feature, you can always use naked ADO.NET or raw SQL.

I’m evaluating the NServiceBus communication framework for using it in some parts of application that we’re working on. I like the messaging infrastructure that it offers and how it all is implemented - behind a simple interface is hidden a modular, extensible, reliable and extremely powerful messaging engine. Sure, like any other framework, it has his own pitfalls and places that requires a special knowledge about how things works to use it efficiently.

One of those tricky places is his configuration system. To start use NServiceBus you have to do few steps to properly configure it. You have to use 2-3 “app.config” configuration sections with approximately 10-15 various parameters and few configuration classes provided by NServiceBus.

Another place that make me stuck is his integration with IoC (Inversion of Control) container. It has an abstraction over all container stuff, so you can pretty easily create an adapter to use it with container of your choice. I don’t like how this abstraction is used and implemented, a bit unnatural for my habits on how to put container to work.

Anyway, we have to deal with it, and use the NServiceBus with Castle Windsor container. As I said to do that you have to create an adapter for IBuilder interface. The NServiceBus Contrib project contains a patch that do this, but it is done in a completely wrong way - by mimicking the adapter for Spring framework. Bad, bad, bad…

So let’s take our big gun - Binsor from Rhino.Tools (I wrote about here) that should do all dirty work by configuring NServiceBus and integrating it in our existing Windsor container. The link to VS solution with all code shown here is provided at the end of the page.

Here we go - how to configure a subscriber for Pub/Sub interactions:

1. Binsor configuration (.boo file):

import System.Reflection
import NServiceBus
import NServiceBus.Unicast
import NServiceBus.Serialization
import NServiceBus.Serializers.Binary
import NServiceBus.Unicast.Transport
import NServiceBus.Unicast.Transport.Msmq
import NServiceBus.Unicast.Subscriptions
import NServiceBus.Unicast.Subscriptions.Msmq

import ObjectBuilder
import nServiceBus.CastleIntegration

component IBus, NServiceBus.Unicast.UnicastBus:
    MessageOwners = {"Messages":"messagebus"}
    MessageHandlerAssemblies = [Assembly.Load("Subscriber1")]

component ITransport, MsmqTransport:
    InputQueue = "worker"
    ErrorQueue = "error"
    NumberOfWorkerThreads = 1
    MaxRetries = 5
    IsTransactional = false
    PurgeOnStartup = false

component IMessageSerializer, MessageSerializer
component IBuilder, Builder

 

2. Program initialization:

var container = new WindsorContainer();

BooReader.Read(container, "nServiceBus.boo");

container.Register(SagasAndMessageHandlers.From(typeof(EventMessageHandler).Assembly));

var bus = container.Resolve<IBus>();

bus.Start();

 

That’s all. Now you can start send/receive messages.

For my taste this is much more readable and maintainable than traditional NServiceBus configuration. Less code, no XML, much cleaner, container friendly.

To make this work you have need for adapter class itself. His responsibility is to forward IBuilder.Build<T> calls to Castle’s Resolve<T> methods. Also, a small helper class that will register Sagas and MessageHandlers in container. Here it is:

public static class SagasAndMessageHandlers
{
    public static IRegistration[] From(params Assembly[] assemblies)
    {
        var registrations = new List<ComponentRegistration>();
        foreach (var assembly in assemblies)
        {
            var types = assembly.GetTypes();
            foreach (var type in types)
            {
                var implementedInterfaces = type.GetInterfaces();
                foreach (var interf in implementedInterfaces)
                {
                    if (!interf.IsGenericType)
                        continue;
                    var genericArguments = interf.GetGenericArguments();
                    if (genericArguments.Length != 1)
                        continue;

                    if (!typeof(IMessage).IsAssignableFrom(genericArguments[0]))
                        continue;

                    var sagaHandlerType = typeof(ISaga<>).MakeGenericType(genericArguments[0]);
                    if (sagaHandlerType.IsAssignableFrom(interf))
                    {
                        registrations.Add(CreateRegistration(type, sagaHandlerType));
                        registrations.Add(CreateRegistration(type, type));
                    }

                    var messageHandlerType = typeof (IMessageHandler<>).MakeGenericType(genericArguments[0]);
                    if (messageHandlerType.IsAssignableFrom(interf))
                        registrations.Add(CreateRegistration(type, type));
                }
            }
        }
        return registrations.ToArray();
    }

    private static ComponentRegistration CreateRegistration(Type type, Type handlerType)
    {
        string componentName;
        if (type == handlerType)
            componentName = type.FullName;
        else
            componentName = type.FullName + handlerType.FullName;

        return (ComponentRegistration)Component
                                          .For(handlerType)
                                          .ImplementedBy(type)
                                          .LifeStyle.Is(LifestyleType.Transient)
                                          .Named(componentName);
    }
}

 

One thing to notice here, NServiceBus required that a saga to be registered as a saga handler ( ISaga<Message>) and as a Saga class itself. A better way will be to use Castle’s newly added forwarding ability, when a component implementation can be accessed through multiple interfaces all forwarded to component’s instance. Bud I had no time to play with this feature yet, so this duplication will still here some time given the fact that no bugs showed up.

You can download a Visual Studio solution with all code shown here from this place. It contains all infrastructure code and two working sample projects ported from original NServiceBus samples - Pub/Sub & Saga.

In our projects we’re using Binsor to configure services in our Windsor container. Main reason to do that is Binsor’s extreme expressiveness. It’s much easier to write and maintain next fragment:

import MyApp.Services
component IMyService, MyService


compared with standard way of configuring components in Windsor:

<component
    id="my_service"
    type="MyApp.Services.IMyService, MyApp"
    service="MyApp.Services.MyService, MyApp" />

Difference is more evident when you have to maintain files with tens and hundreds of components. Sure, you can use some kind of “autoregistration” for components, this can reduce dramatically size of configuration files.

But, since Binsor is a kind of DSL, is not always evident how to configure complex components that have dependencies and configuration properties to specify. The Binsor’s unit tests are the place where to look for samples, but they don’t cover everything.

Today, I had to configure a NHibernateIntegration facility from Castle with Binsor. After some time I had next solution for configuring two factories:

import Castle.Facilities.NHibernateIntegration
import Rhino.Commons
import NHibernate.Playground
facility NHibernateFacility:
    configuration:
        factory:
            @id = 'factory_1'
            settings(keymap):
                dialect = 'NHibernate.Dialect.MsSql2005Dialect'
                connection.provider = 'NHibernate.Connection.DriverConnectionProvider'
                connection.driver_class = 'NHibernate.Driver.SqlClientDriver'
                connection.connection_string = "Server=.\\SQLEXPRESS;initial catalog=test;Integrated Security=SSPI"
            assemblies:
                assembly = 'NHibernate.Playground'
    configuration:
        factory:
            @id = 'factory_2', alias = 'test2'
            settings(keymap):
                dialect = 'NHibernate.Dialect.MsSql2005Dialect'
                connection.provider = 'NHibernate.Connection.DriverConnectionProvider'
                connection.driver_class = 'NHibernate.Driver.SqlClientDriver'
                connection.connection_string = "Server=.\\SQLEXPRESS;initial catalog=test2;Integrated Security=SSPI"
            assemblies:
                assembly = 'NHibernate.Playground'

You can see here the XML way to configure NHibernate facility.

This time it’s about useful macro that speeds up writing test names. Although we’re not using yet BDD development style (BDD is for Behavior Driven Design) I like to give to my test BDD-style names. You know, something like

[Test]
public void When_user_pressed_OK_message_should_be_prepared_and_sent()
{
}

Writing down these names, when words are separated by underscores is not easy and error prone.

Fortunately, Jean-Paul S. Boodhoo has posted in his blog an updated macro for formatting test names in BDD-style manner:

Using this macro you can write test name as an usual sentence, having words separated by spaces. After running the macro it will replace all space characters by underscores.

For me it was first macro written for Visual Studio, but after some rambling within VS I have the macro running and working well. Thereafter, found these links than can help to setup and use VS macros:

It seems to be that Patterns & Practices team continues to do what they do the best - creating guidance within different development areas.

The last release of this group is the WCF Security Guidance. It contains description for a few application scenarios & a list of various How-Tos, including few video walkthroughs of common WCF solutions.

It’s different from usual way to dig into WCF infrastructure details. It’s not crawling over hundreds of MSDN pages, it’s not like reading MSDN samples trying to understand what’s going on.

It is a very detailed step-by-step description on how to do some tasks touching different aspects of WCF, starting from opening a certificates store, and ending with deployment advices.

Keep it going, P&P!

I have shown today few tricks with ReSharper to one of my teammates. I think it worth to be shared/stored in the blog.

1. View the code used from a referenced assembly

Very often you want to see how a referenced assembly is used in your project. We can use dedicated tools to work this out (for example, NDepend) or you can just click on a project in solution explorer, expand “References” node, select an assembly, right-click and select “Find Dependent Code“. You will see a nice “Find Results” window with all places where this referenced assembly is used.

Same way, you can analyze project dependencies in a multi-project solution. I think you will be rewarded in future if your presentation assemblies will not depend from a project with database stuff.

2. Setting a keyboard shortcut to run a unit test

I’m sure that any keyboard ninja knows it. Do you want to learn a bit of kung-fu? Go to keyboard settings configuration in Visual Studio (Tools > Options… > Environment > Keyboard), find a command named “ReSharper.UnitTest_ContextRun” and assign a shortcut to it. I hang it to “Ctrl+1″.

Now, when you’re editing a class containing unit tests, you can just press your newly created shortcut and ReSharper will run the tests: if you’re inside a test method (method marked with [Test]) only the current test will run; if you’re somewhere in the class, but outside of a test method, R# will run all tests from this class.

WCF infrastructure allows you to store context sensitive data in InstanceContext of the service instance. For that you should implement from IExtension<InstanceContext> and plug that class into WCF’s infrastructure in any of available ways.

When I worked on a class that can store contextual information in Web context or WCF context depending on some configuration parameters, I preferred to have similar idioms, and I wrote an HttpContext-like class for WCF.

///<summary>
/// This class incapsulates context information for a service instance
///</summary>
public class WcfInstanceContext : IExtension<InstanceContext>
{
    private readonly IDictionary items;

    private WcfInstanceContext()
    {
        items = new Hashtable();
    }

    ///<summary>
    /// <see cref="IDictionary"/> stored in current instance context.
    ///</summary>
    public IDictionary Items
    {
        get { return items; }
    }

    ///<summary>
    /// Gets the current instance of <see cref="WcfInstanceContext"/>
    ///</summary>
    public static WcfInstanceContext Current
    {
        get
        {
            WcfInstanceContext context = OperationContext.Current.InstanceContext.Extensions.Find<WcfInstanceContext>();
            if (context == null)
            {
                context = new WcfInstanceContext();
                OperationContext.Current.InstanceContext.Extensions.Add(context);
            }
            return context;
        }
    }

    /// <summary>
    /// <see cref="IExtension{T}"/> Attach() method
    /// </summary>
    public void Attach(InstanceContext owner) { }

    /// <summary>
    /// <see cref="IExtension{T}"/> Detach() method
    /// </summary>
    public void Detach(InstanceContext owner) { }

}

Now, you can use this class to store and retrieve data in the same manner as you’re working with HttpContext:

    WcfInstanceContext.Current.Items["key"] = new MyClass();
    MyClass myClass = WcfInstanceContext.Current.Items["key"] as MyClass;

 

Of course, when doing this you should be inside of WCF session…

Enjoy!

Just a note to myself…

If you want to use SQL Server Management Objects (SMO) in your .NET applications you should reference assemblies from “C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies”. This is described in almost all articles about how to work with SMO (for example this one).

But if that folder doesn’t exist or required files are missing, they are 2 ways to solve that:

  • Extract required files from GAC
  • Install an additional component for SQL Server: Software Development Kit

Second choice was easier to do for me. So, I just downloaded SQL Server 2005 Express Edition with Advanced Services SP2 and installed the required SDK.

Installation of last Visual Studio on my Vista was enough painful for me to make me post my troubles and solution in hope that may be they will help somebody else…

The nasty problem starts with installation of .NET Framework 3.5, which is a part of and a prerequisite for VS 2008: when installing it, Windows Update will ask you to restart your system. If you will accept rebooting while setup is still running, you will  end up with damaged and unfinished installation of .NET Framework 3.5. So, on Vista you shouldn’t accept restarting computer until installation of .NET Framework 3.5 or Visual Studio 2008 is not finished. The whole problem is described in Aaron Stebner’s weblog: How to avoid OS reboot prompt when installing the .NET Framework 3.5 on Windows Vista. It describes how to avoid it, but not how to make you system back and ready for a next installation, where you will follow recommendations and ignore restart proposal.

Solutions can be very different, it can depend from your concrete situation. After a bunch of tries, ~10 OS restarts, running tools, googling, reading MSDN forums I found my symptoms to be similar to those described here in “Issue 2″ and solution that worked for me:

  1. Install .NET Framework 3.5 beta 2. (I’m not sure if this is really required, but it worked for me)
  2. Uninstall .NET Framework 3.5 beta 2. Restart.
  3. Locate and uninstall any of updates named:
    • Hotfix for Microsoft Windows (KB110806)
    • Hotfix for Microsoft Windows (KB929300)
    • Hotfix for Microsoft Windows (KB930264)
  4. Reboot.

At that moment I was able to run successfully .NET Framework 3.5 installation and after that Visual Studio 2008.

Don’t forget: don’t accept restarting your Vista until installation of .NET Framework 3.5 or Visual Studio 2008 is finished.

And a link mini-dump with places to look for troubleshooting installation problems of Visual Studio 2008 and other related stuff:

Happy coding!

Just finished a big refactoring which led to deletion of a bunch of files. Our large solution is under Subversion, so the process of deleting a file looked like:

  • search with Resharper if class is not used anymore
  • locate it in windows explorer
  • delete file with TortoiseSVN
  • finally, come back to Visual Studio and delete file from solution.

Huh! Not simple, not fast. No surprise, that longest operation was locating file in Windows explorer. But I way lucky enough to remember that I had installed a small but very helpful add-in - CoolCommands 4.0. One of his really cool commands is that from a opened file’s context menu you can “Open containing folder” that not only opens right folder, but also highlights the file. Cool, no?

This is  the case when having right tools around and using them can save you enough time to write a small blog post make you more productive developer.

Unfortunately, CoolCommands doesn’t have a dedicated site and last place where you can find a download link is comments for this post on Gaston’s Milano blog. Direct link to download latest version - CoolCommands 4.0.

And, as a follow up, a list of “cool commands”:

  • Collapse all projects
  • Command prompt here
  • Open project folder
  • Demo font
  • Send by email
  • Copy reference
  • Add as string resource
  • Visual Studio Prompt Here
  • Copy Reference.
  • Locate in solution explorer.

And a picture to help explain how you can find the commands:

CoolCommands's context actions

I like the tools like this. They make you go faster, feel smarter and program better. Enjoy!

…reading feeds this evening:

Ted Neward - The First Strategy: Declare War on Your Enemies (The Polarity Strategy):

…there are numerous forces that are at work trying to drag the project down into failure. As a software development lead (or architect, or technical lead, or project manager, or agile coach, or whatever), you need to learn how to spot these enemies to your project, identify them clearly, and make it clear that you see them as an enemy that will not be tolerated.

Other enemies are not to be tolerated at any level: apathy, sloth, or ignorance are all too common among developer teams. Ignorance of how underlying technologies work. Apathy as to the correctness of the code being created. Sloth in the documentation or tests. These are enemies that, given enough time and inattention, will drag the project down into the tar pits of potential failure. They cannot be given any quarter. Face them squarely, with no compromise. Your team, if they hold these qualities, must be shown that there is no tolerance for them. Hold brown-bag lunches once a week to talk about new technologies, and their potential impact on the team or company or project. Conduct code reviews religiously, during active development (rather that at the end as a token gesture), with no eye towards criticizing the author of the code, but the code itself. Demand perfection in the surrounding artifacts of the project: the help files, the user documentation, the graphics used for buttons and backdrops and menus.

I’ll send these sentences to everyone in my team. I hope that this will justify some of my decisions and actions like pointing to bad names, duplicated code, tight coupling and  other, definitely bad, software development practices.

Someone has said: “power is in details”. If we will let bad small details to invade our code base, architecture and minds this will be first step to a failing software project - we will loose the war…

“Don’t Live with Broken Windows”. Do you read “The Pragmatic Programmer: From Journeyman to Master”? If you’re a software developer or want to be a better one and you don’t know this book - go for it. One of the best books written about software development. It contains a lot to help you win the war. But nothing will help you win this war more than discipline:

Discipline takes many forms and permeates every aspect of software development. Start small. Say your database schema contains three primary key table columns named “list_id”, “ListId”, and “list_value”. There should be a Gunnery Sergeant Hartman on your development team who will.. gently.. remind the team that it might be a good idea to fix problems like this before they become institutionalized in all your future code.

To my team: -  Sorry guys. I’m your sergeant. We’re at war…