Tuesday, March 3, 2015

Changing TransactionScope - Timeout at runtime

So... TransactionScope...

If you have worked with the TransactionScope in the past you might have noticed that it can be tricky, and even dangerous if you don't use it correctly.

So anyways, I have tried to change the TransactionScope timeout property at runtime and the thing still goes back to the default timeout of 10 minutes.

This is because the 'TransactionScope' uses the following object to get the maximum timeout for a transaction: TransactionManager.MaximumTimeout. If you decompile it you will see the following:

if (!TransactionManager._cachedMaxTimeout)
{
  lock (TransactionManager.ClassSyncObject)
  {
    if (!TransactionManager._cachedMaxTimeout)
    {
      TransactionManager._maximumTimeout = TransactionManager.MachineSettings.MaxTimeout;
      TransactionManager._cachedMaxTimeout = true;
    }
  }
}

Pay special attention to: TransactionManager.MachineSettings.MaxTimeout

It always reads from the machine settings defined on the machine.config (C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config)

And this specific section is defined as follows:

<sectionGroup name="system.transactions" type="System.Transactions.Configuration.TransactionsSectionGroup, System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null">
   <section name="defaultSettings" type="System.Transactions.Configuration.DefaultSettingsSection, System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null"/>
   <section name="machineSettings" type="System.Transactions.Configuration.MachineSettingsSection, System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null" allowDefinition="MachineOnly" allowExeDefinition="MachineOnly"/>
</sectionGroup>

Note that it's marked with: allowExeDefinition="MachineOnly" that's why we cannot override it in our config files - shame :(

So basically I can think in two options to increase the maximum transaction timeout:

Updating the machine.config file

You could do it although I wouldn't recommend it so I won't bother to show you how... well take a quick look

Hacking - using reflection

Or do it the Ninja way...

private void ConfigureTransactionTimeout(TimeSpan value)
{
    //initializing internal stuff
    // ReSharper disable once NotAccessedVariable
    var timespan = TransactionManager.MaximumTimeout;

    //initializing it again to be sure
    // ReSharper disable once RedundantAssignment
    timespan = TransactionManager.MaximumTimeout;

    SetTransactionManagerField("_cachedMaxTimeout", true);
    SetTransactionManagerField("_maximumTimeout", value);

    Condition.Ensures(TransactionManager.MaximumTimeout, "TransactionManager.MaximumTimeout").IsEqualTo(value);
}

private void SetTransactionManagerField(string fieldName, object value)
{
    var cacheField = typeof (TransactionManager).GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static);

    Condition.Ensures(cacheField, "cacheField").IsNotNull();

    cacheField.SetValue(null, value);
}

And use it like:

ConfigureTransactionTimeout(TimeSpan.FromMinutes(20));

var timespan = TransactionManager.MaximumTimeout;

var transactionOptions = new TransactionOptions
{
    IsolationLevel = isolationLevel,
    Timeout = timespan
};

var ts = new TransactionScope(transactionScopeOption, transactionOptions);

There you go

Monday, March 2, 2015

Testing Ninject container

I've found really useful to test our IoC container to make sure that all the components that are registered can be resolved.

This is the way I usually test my Ninject container

The model

so let's say that we have the following model:

public interface ICommand { }

public interface ICommandHandler<in T> where T : ICommand
{
    void Handle(T command);
}

public class DeploySqlScriptsUsingAGlobalTransactionCommand : ICommand
{
    public DeploySqlScriptsUsingAGlobalTransactionCommand(IEnumerable<string> scripts)
    {
        Scripts = scripts;
    }

    public IEnumerable<string> Scripts { get; private set; }
}

public class DeploySqlScriptsUsingAGlobalTransactionCommandHandler :
    ICommandHandler<DeploySqlScriptsUsingAGlobalTransactionCommand>
{
    private readonly IScriptDeployerService _scriptDeployerService;

    public DeploySqlScriptsUsingAGlobalTransactionCommandHandler(IScriptDeployerService scriptDeployerService)
    {
        _scriptDeployerService = scriptDeployerService;
    }

    public void Handle(DeploySqlScriptsUsingAGlobalTransactionCommand command)
    {
        //shalalalalal
        command.Scripts.ToList().ForEach(_scriptDeployerService.Deploy);
        Console.WriteLine("Scripts deployed");
    }
}

public interface IScriptDeployerService
{
    void Deploy(string script);
}

Note that we don't have a concrete implementation of IScriptDeployerService

The test

So we create this test to make sure that the container is valid:

[TestMethod]
public void it_should_resolve_all_registered_components_in_the_container()
{
    #region Binding container

    var kernel = new StandardKernel();

    kernel.Bind(config =>
    {
        config.FromThisAssembly()
            .SelectAllClasses()
            .BindAllInterfaces();
    });

    ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(kernel));

    kernel.Bind<IServiceLocator>().ToConstant(ServiceLocator.Current); 

    #endregion

    #region Testing container

    var field = typeof (KernelBase).GetField("bindings",
        BindingFlags.Instance | BindingFlags.NonPublic);

    field.Should().NotBeNull();

    var bindingsMap = field.GetValue(kernel) as Multimap<Type, IBinding>;

    bindingsMap.Should().NotBeNull();
    bindingsMap.Should().NotBeEmpty();

    var locator = ServiceLocator.Current.GetInstance<IServiceLocator>();

    locator.Should().NotBeNull();

    bindingsMap.SelectMany(x => x.Value).ToList()
        .ForEach(binding => ServiceLocator.Current.Invoking(instance =>
        {
            var services = instance.GetAllInstances(binding.Service);

            services.Count().Should().BeGreaterOrEqualTo(1);

            if (services.Count() == 1)
            {
                instance.GetInstance(binding.Service);
            }
        }).ShouldNotThrow());

    #endregion
}

The error

When we run the test we receive the following error from Ninject:

Result Message: Did not expect any exception, but found Ninject.ActivationException with message "Error activating IScriptDeployerService No matching bindings are available, and the type is not self-bindable. Activation path: 2) Injection of dependency IScriptDeployerService into parameter scriptDeployerService of constructor of type DeploySqlScriptsUsingAGlobalTransactionCommandHandler 1) Request for ICommandHandler{DeploySqlScriptsUsingAGlobalTransactionCommand}

Very explicit

The fix

So now let's fix it:

Let's add the missing concrete implementation:

public class ScriptDeployerService : IScriptDeployerService
{
    public void Deploy(string script)
    {
        Console.WriteLine("Script deployed: {0}", script);
    }
}

The result

And now our test pass =) Awesome