September, 2010 Archives

26
Sep

Interception with LinFu

by Mikael Lundin in Programming

I have previously showed you how you can do interception with both Castle DynamicProxy and with Unity. Now it is time to do the same with LinFu, which is suprisingly easy if you have done it with the previous two.

Implement the IInvokeWrapper

There are several ways for interception with LinFu but I like the InvokeWrapper, because it’s so easy to use. Just implement the LinFu.AOP.Interfaces.IInvokeWrapper.

public class MyInvokeWrapper : IInvokeWrapper
{
	private readonly IBookRepository target;
	public MyInvokeWrapper(IBookRepository target)
	{
		this.target = target;
	}

	public void BeforeInvoke(IInvocationInfo info)
	{
		Debug.WriteLine("Before {0}", new[] { info.TargetMethod.Name });
	}

	public void AfterInvoke(IInvocationInfo info, object returnValue)
	{
		Debug.WriteLine("After {0}", new[] { info.TargetMethod.Name });
	}

	public object DoInvoke(IInvocationInfo info)
	{
		Debug.WriteLine("Invoking {0}", new[] { info.TargetMethod.Name });
		return info.TargetMethod.Invoke(target, info.Arguments);
	}
}

Now that’s quite self explanatory.

Create a new ProxyFactory and intercept away

Now all you need to do to get your proxy class is the following.

var factory = new ProxyFactory();
var repository = new StoreRepository();
var myInterceptor = new MyInvokeWrapper(repository);

return factory.CreateProxy<IBookRepository>(myInterceptor)));

Go here for a full example, or download as a zip archive.

23
Sep

Interception with Unity

by Mikael Lundin in Programming

I’ve already written about this here but this is such a obscure topic that it really doesn’t hurt with some more examples.

In this example we have a bookstore with two repositories defined as below.

public interface IBookRepository
{
    IList<Book> GetAll();
}

public interface IAuthorRepository
{
    IList<Author> GetAuthorsForBook(string isbn);
}

I would like to measure how long these calls take, but I don’t want to change the implementation. This can be done with AOP and interception.

ICallHandler

We create a class that implements ICallHandler. This is the code that will intercept the calls.

public class MeasureLatencyCallHandler : ICallHandler
{
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        var watch = new Stopwatch();
        Debug.WriteLine("Begin: {0}", new[] { input.MethodBase.Name });

        watch.Start();
        var result = getNext()(input, getNext);
        watch.Stop();

        Debug.WriteLine("End: {0} ({1} ms, {2} ticks)", input.MethodBase.Name, watch.ElapsedMilliseconds, watch.ElapsedTicks);
        return result;
    }

    public int Order { get; set; }
}

The strange call getNext()(input, getNext) is the actual call to the method that is intercepted. The Order property controls the inner order of interceptions.

IMatchingRule

Interception is done by putting a proxy class on top of the class/interface that should be intercepted. But how do we control that only some methods on that class/interface should be interrupted? We implement a IMatchingRule.

public class AnyMatchingRule : IMatchingRule
{
    public bool Matches(MethodBase member)
    {
        return true;
    }
}

This matching rule always returns true, which means that we want to intercept everything on that class/interface. Otherwise we could use the MethodBase argument to return true or false.

Container configuration

Last, but not least, we have to tell the Unity container to intercept these interfaces with out MeasureLatencyCallHandler filtering the methods with our AnyMatchingRule.

container.AddNewExtension<Interception>();

container.RegisterType<IMatchingRule, AnyMatchingRule>("AnyMatchingRule");
container.RegisterType<ICallHandler, MeasureLatencyCallHandler>("MeasureLatencyCallHandler");

container.Configure<Interception>().AddPolicy("TracePolicy")
	.AddMatchingRule("AnyMatchingRule")
	.AddCallHandler("MeasureLatencyCallHandler");

container.Configure<Interception>().SetInterceptorFor(typeof(IBookRepository), new InterfaceInterceptor());
container.Configure<Interception>().SetInterceptorFor(typeof(IAuthorRepository), new InterfaceInterceptor());

That’s it! You will find the source here, or you can download as a zip archive.

21
Sep

Lazy loading property with Castle.DynamicProxy2

by Mikael Lundin in Programming

Today I will solve a problem concerning single responsibility principle and lazy loading properties using Castle DynamicProxy. My example application is a simple bookstore, that can display books from an XML.

public interface IStoreRepository
{
    IList<Book> GetAll();

    IList<Author> GetAuthorsForBook(string isbn);
}

Because the Author object would require a JOIN, we would like to lazy load the values – meaning, when we access the property it will be loaded with values from the datasource.

Castle.DynamicProxy2

Download the dynamic proxy and reference it in your project.

Now create a ProxyBuilder that will be responsible for creating proxies instances for the Book class. It is also possible to create proxies from classes but that is something you may discover by yourself.

public interface IProxyBuilder
{
    T ProxyFromClass<T>() where T : class;
}

public class ProxyBuilder : IProxyBuilder
{
    private readonly IInterceptor[] interceptors;
    private readonly ProxyGenerator proxyGenerator;

    public ProxyBuilder(IInterceptor[] interceptors)
        : this(interceptors, new ProxyGenerator())
    {
    }

    public ProxyBuilder(IInterceptor[] interceptors, ProxyGenerator proxyGenerator)
    {
        this.interceptors = interceptors;
        this.proxyGenerator = proxyGenerator;
    }

    public virtual T ProxyFromClass<T>() where T : class
    {
        return proxyGenerator.CreateClassProxy<T>(interceptors);
    }
}

If this where a larger application I would use a DI framework and register different instances of IProxyGenerator, for example.

container.Register<IProxyBuilder>("LazyAuthors", new[] { new LazyLoadAuthorsInterceptor() });

Our implementation of the interceptor that will be triggered on every virtual member of the class where it’s put.

public class LazyLoadAuthorsInterceptor : IInterceptor
{
    private readonly IStoreRepository repository;
    private const string MethodName = "get_Authors";

    public LazyLoadAuthorsInterceptor(IStoreRepository repository)
    {
        this.repository = repository;
    }

    public void Intercept(IInvocation invocation)
    {
        if (invocation.Method.Name == MethodName)
        {
            var isbn = ((Book) invocation.InvocationTarget).Isbn;
            invocation.ReturnValue = repository.GetAuthorsForBook(isbn);
        }
    }
}

Now we can create a proxy class of book, and when we call the Authors property, the authors will be loaded and returned from IStoreRepository.

var proxyBuilder = new ProxyBuilder(new [] { new LazyLoadAuthorsInterceptor(new StoreRepository()) };
var book = proxyBuilder.ProxyFromClass<Book>();

// Will call IStoreRepository.GetAuthorsForBook
var authors = book.Authors;

You may get the code for this here, or you may download it as a zip package.

15
Sep

UL and LI list elements in WatiN

by Mikael Lundin in Programming

Update 2011-02-16: This is no longer needed as of Watin 2.0 Final Release.

I’ve been missing the UL/LI element querying in WatiN since I started to use it, but I’ve never even thought about doing something about it. Thanks to WatiN’s excellent extensibility it was proven not too hard.

[ElementTag("ul")]
public class Ul : ElementContainer<Ul>
{
	public Ul(DomContainer domContainer, INativeElement nativeElement) : base(domContainer, nativeElement)
	{
	}

	public Ul(DomContainer domContainer, ElementFinder elementFinder) : base(domContainer, elementFinder)
	{
	}

	public LiCollection Items
	{
		get
		{
			return new LiCollection(DomContainer, CreateElementFinder<Li>(
				delegate(INativeElement nativeElement)
			{
				return nativeElement.Children;
			}, null));
		}
	}
}

[ElementTag("li")]
public class Li : ElementContainer<Li>
{
	public Li(DomContainer domContainer, INativeElement nativeElement) : base(domContainer, nativeElement)
	{
	}

	public Li(DomContainer domContainer, ElementFinder finder) : base(domContainer, finder)
	{
	}
}

public class LiCollection : BaseElementCollection<Li, LiCollection>
{
    public LiCollection(DomContainer domContainer, ElementFinder elementFinder) :
        base(domContainer, elementFinder)
    {
    }

    protected override LiCollection CreateFilteredCollection(ElementFinder elementFinder)
    {
        return new LiCollection(DomContainer, elementFinder);
    }
}

You’ll notice at once that most of the code is inheritence and calling base. The magic is all in the type declarations and their ElementTag-attributes.

Now you can use the UL element in a page declaration to give easy access to the UL list.

<ul id="colors">
	<li>Blue</li>
	<li>Green</li>
	<li>White</li>
</ul>
public class IndexView : Page
{
    private const string ColorListId = "colors";

    public Ul ColorList
    {
        get { return Document.ElementOfType<Ul>(ColorListId); }
    }
}

And you use this in a test as usual.

[Test]
public void ShouldHaveListWithThreeColors()
{
    using (var browser = new IE("http://localhost:51562"))
    {
        var index = browser.Page<IndexView>();

        Assert.That(index.ColorList.Items.Count, Is.EqualTo(3));
        Assert.That(index.ColorList.Items[0].Text.Trim(), Is.EqualTo("Blue"));
        Assert.That(index.ColorList.Items[1].Text.Trim(), Is.EqualTo("Green"));
        Assert.That(index.ColorList.Items[2].Text.Trim(), Is.EqualTo("White"));
    }
}

This was made with Watin 2.0 RC 1.
You can download the complete source and example here.

8
Sep

Backup plan for SQL Server Express

by Mikael Lundin in Technicalities

I’m using SQL Express for a lot of my projects. Both my private projects and when the customer does not see the need of investing in a SQL Server license.

Unfortunatly there are some missing features in Express, to make you want to buy that license. The backup scheduler is one of them. But don’t dispair, all the functionality for creating a backup is there. You just have to do it in another way.

Backup your database

First, open up the backup dialog in SQL Management studio express. Select to script the backup and save it as a file.

Now we edit this file so that it looks the way we want it. This is my backup script.

DECLARE @pathName NVARCHAR(512)
SET @pathName = 'D:\Backups\CMS\backups\cmsDatabase-' + Convert(varchar(8), GETDATE(), 112) + '.bak'
BACKUP DATABASE [cmsDatabase] TO  DISK = @pathName WITH NOFORMAT, NOINIT,  NAME = N'cmsDatabase-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

Now, all we have to do is schedule this to run every week. Create a new powershell script in the same folder as your backup script. Mine is called job.ps1

sqlcmd -S KINO\SQLEXPRESS -U backupUser -P backupUserPassword -i schedule.sql

Where schedule.sql would be our previous backup script. I would also like to backup the whole website directory at the same time, so I add the following to my powershell script.

$date = Get-Date -format yyyyMMdd
$env:Path += ";C:\Program Files\WinRAR\"
rar.exe a cmsWebsite-$date.rar C:\inetpub\cmsWebsite

Open up Windows Scheduler and create a schedule where you run this script every monday 1 am.

That’s it! Works like a charm.