Thursday, October 29, 2009

Organizing mutiple Visual Studio solutions and multiple SVN repositories

Often when developing a project that has many components solution grows so big that it becomes quite messy, VS lags. When you check out Editor you'd like to work with you have to drag rest projects sitting there in repository. And so on.

The typical scheme will look like this:
What do we have here? We have project Core that holds domain objects and logic. Next in the same solution we have ReportsGenerator settled down. Also there some of your mates work on editor that also is using Core project indirectly.
Now say you want to develop/bugfix/just check what's going on in your ReportsGenerator. You have to checkout whole repository full of other logical parts like Editor and load big-ball-of-mud-solution with alot of files you dont care about at all.

However when working with VS solution you're able to reference project from another solution so it isnt nessesary to work with one big solution at all. You create your own solution ReportsGenerator, inside of it you create projects you would like to work with and then you reference to Core project of another solution. The developer working on Editors does pretty much the same thing. So now you both have references to the same Core project while working in 2 separate solutions.

Now lets think how does this work with SVN repository. One way is to keep everything in single repository. That way when you would like to checkout your ReportsGenerator solution you're in trouble: which referenced projects should be checked out as well? How will you know that ReportsGenerator is dependant on Core? Maybe it also has dependecies in Controllers project?

To solve this problem SVN repository externals property can be used. Whole picture is going to look like this:


Every solution now sits in its separate repository allowing easy check outs.

With externals tuned another developer checking out WPF_Editor code from its separate repository will also trigger check out for Controlers repository and Core repository. And he will work in his own separate solution for WPF_Editor. He has full access to Core solution, he can alter some classes and check them in, everyone else working on other dependant projects will notice that Core changed and can update it with SVN as usual.

Externals property can be used to reference a specific revision of folder in another repository so you wont get surprised when 3rd party library drastically changes.

Good guide into externals properties of SVN can be found here:

Thursday, August 13, 2009

Problems with conversion operator in abstract classes

Sad truth - no way to implement operator convertion in abstract class like this:
public abstract class DoubleValueBase
{
protected DoubleValueBase(double value)
{
AssertThatValueIsWithinRange(value);
this.Value = value;
}
public double Value { get; private set; }
public static implicit operator DoubleValueBase(double value)
{
return (DoubleValueBase)Activator.CreateInstance(??);
}
public static explicit operator double(DoubleValueBase value)
{
return value.Value;
}
protected abstract void AssertThatValueIsWithinRange(double value);
}
So it isn't possible to derive Power class from DoubleValueBase and write

Power power = 5.3;

unless you create implicit convertion operator in Power class. Now imagine, that you need to have 20 classes derived from DoubleValueBase.

P.S. If anybody have an idea if it is possible to do with languages like Boo or Nemerle give me a call please.

Tuesday, August 4, 2009

ValidateLambdaArgs and problems with casting linq Expression

Was stuck with a problem while implementing strogly typed mappings via linq expressions for a while. The problem was with passing Expression into method with reflection.

typeof(SomeClassRepository)
.GetMethod("LoadBy")
.Invoke(repository, new object[] { lambdaExpression, valueToMatch });
Actual signature of LoadBy looks like this:
public SomeClass LoadBy(Expression<Func<SomeClass, object>> expression, string value)
I want to build expression like x=>x.SomeProperty and pass it to LoadBy via reflection. The problem however arise its head when trying to pass value types when building expression:

var intPropertyName = "IntProperty";

var type = typeof(SomeClass);
var parameterExpression = Expression.Parameter(type, "x");
var memberExpression = Expression.Property(parameterExpression, intPropertyName);
var delegateType = typeof(Func<,>).MakeGenericType(new Type[] { type, typeof(object) });

var lambdaExpression = Expression.Lambda(delegateType,memberExpression, new[] { parameterExpression });

Here's definition of SomeClass:
public class SomeClass
{
public int IntProperty { get; set; }
}
Building such lambda expression raises System.ArgumentException in System.Linq.Expressions.Expression.ValidateLambdaArgs. Exception will say that you cannot use System.Int32 for return type System.Object.

To avoid this I found no way other than to use more reflection stuff and make a hack. Building lambda expression with following code instead of Expression.Lambda(...) fixed the problem:

var onlys = new ReadOnlyCollection<ParameterExpression>(new List<ParameterExpression> { parameterExpression });
var specificType = typeof(Expression<>).MakeGenericType(new System.Type[] { delegateType });
var lambdaExpression = Activator.CreateInstance(specificType,
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new object[] { memberExpression, onlys },
null);

Wednesday, July 22, 2009

How to get type masked by Castle Dynamic Proxy

Hello there, back from my vacation.

When writing "ORM" for Sharepoint lists I've encountered a problem with Castle Dynamic Proxy. I had to get the type which was wrapped with proxy and had no way to get that type in any other way besides getting it from the proxy itself.
Here's a little hack that does that through reflection:
var objProxy = obj as IProxyTargetAccessor;
if (objProxy != null)
{
var proxyTargetType= (Type)objProxy.GetType().GetField("typeTokenCache").GetValue(objProxy);
}
Note, however, that implementation of Dynamic Proxy might change and this hack will stop working then.

P.S. If anybody knows how to do it in a "right" way, post please.

Thursday, June 18, 2009

Just got myself NDepend license!

Got myself NDepend pro license from Patrick Smacchia (lead dev). Patrick, thanks alot! ;)

In short NDepend is code base analyzer which might reveal many weak links in your solution and discover many ways to improve overall structure.

I'm going to post my finding about its features while exploring this tool.

P.S. There are alot of learning demos and screenshots on official site you might want to check.

Strongly typed mapping

Often there is a need to map some properties on of class to properties of another class or columns in DB. There might be few ways to do that. The most popular ways are via code or via xml files. While working on my sharepoint-lists-to-objects mapper I had to create some way to map class properties to sharepoint fields and decided to go with code implementation. So I'm going to talk how to do that via code file in strongly typed manner.

Lets say I have a class
public class MyClass
{
public int MyProperty{get;set;}
}

and I want to map property in strogly-typed manner. So instead of typing
MapField("MyProperty", "ColumnName");

I want to have
MapField(x=>x.MyProperty, "ColumnName");

This gives a nice opportunity to refactor, as when renaming MyProperty to something else you will rename it in the mapping as well (though R# can do that for you as it can search literals with property name when renaming a property).

So we need to determine what's the name of property we're passing and also might be interested in it's type.
MapField method should have this signature to work
public void MapField(Expression<Func<MyClass, object>> expression, string columnName)
{
//get field/property name and type from expression
}


Now we have to parse that linq expression. To get required info I've wrote a class with following interface
public interface ILinqExpressionReader<T>
{
string GetFieldOrPropertyNameFromBodyOfExpression(Expression<Func<T, object>> expression);
Type GetFieldTypeFromBodyOfExpression(Expression<Func<T, object>> expression);
}


and here is the implementation:
public class LinqExpressionReader<T> : ILinqExpressionReader<T>
{
public string GetFieldOrPropertyNameFromBodyOfExpression(Expression<Func<T, object>> expression)
{
var memberInfo = GetMemberInfoFrom(expression);
return memberInfo.Name;
}

private static MemberInfo GetMemberInfoFrom(Expression<Func<T, object>> expression)
{
MemberInfo member;
if (expression.Body.GetType() == typeof(UnaryExpression))
{
var unaryExpression = (UnaryExpression)expression.Body;
if (IsMemberExpression(unaryExpression.Operand))
{
member = ((MemberExpression)unaryExpression.Operand).Member;
}
else { throw new ArgumentOutOfRangeException("expression", "Should use the following syntax: x => x.PropertyName (or x => x.FieldName)"); }
}
else if (IsMemberExpression(expression.Body))
{
member = ((MemberExpression)expression.Body).Member;
}
else { throw new ArgumentOutOfRangeException("expression", "Should use the following syntax: x => x.PropertyName"); }
return member;
}
private static bool IsMemberExpression(Expression expression)
{
return expression.GetType() == typeof(MemberExpression);
}

public Type GetFieldTypeFromBodyOfExpression(Expression<Func<T, object>> expression)
{
var memberInfo = GetMemberInfoFrom(expression);
switch (memberInfo.MemberType)
{
case MemberTypes.Property:
return ((PropertyInfo)memberInfo).PropertyType;
case MemberTypes.Field:
return ((FieldInfo)memberInfo).FieldType;
default:
throw new Exception("Cannot get types for anything but Properties and Fields");
}
}
}


Implementation uses reflection to get info that is required. Also works fine with properties or fields of Enum type.

Monday, June 15, 2009

Resharper top 5 features

Resharper has tons of ideas that can significantly improve your performance in Visual Studio making it an essencial tool for any developer who ever used it.



I wanna share what I find the most useful, so without further delay

1. Quick "goto" context menu

Where is this function used? How does the class of this variable look like? What is the implementation of this interface method? All of this questions lead to a single shortcut [Ctrl+`] It opens context menu with appropriate gotos.



2. Quick navigate to Type/Filename by name.

What? More navigation rutine? Well couldn't live without this in any mediocre to large scale solution. It's actually becomes very natural way to navigate around in time, you'll forget about forest of files in solution explorer. It is possible to navigate to class, to file and to class member by name with use of [Ctrl+T] (for types) and [Ctrl+Shift+T] (for files). Just press shortcut and type few first letters. Note that wildcards are supported as well.


3. Generation of rutine code.

[Alt+Ins] pops up a menu for fast constructor/property creation. Just hit this combo, select operation, few specifications of what you really want and you are done.



4. Reformat code

While working with source files it becomes pretty messy over time, you have public methods mixed up with private, field declarations all over the place, etc. And since you must implement features fast you don't have much time to clean up visual aspects of code. However with resharper it's just the matter of issuing a single command named full clean up - [Ctrl+E, Ctrl+C] (you might create lesser jobs too). It will move everything around to match the pattern of file layout you provide, add this. qualifiers and do some other nice stuff to keep your code well styled. Pattern should be shared among teammates to keep considtent look of source files.

5. Duplicate code. [Ctrl+D] is very nifty when it comes to duplicating. Put a cursor on a line you'd like to dup and just press Ctrl+D. Hidden benefit of this that it doesn't even touch your clipboard! (so everything in buffer stays) Duplication works horizontally too, just select a piece of line and dups will be created to the right.

6. Beyond that

Resharper extends refactorings supported by VS. Extract method [Ctrl+M] and Introduce variable [Ctrl+V] are the most commonly used by me. There are also tons of other useful refactorings waiting for you.

Tuesday, June 9, 2009

Working efficiently with sharepoint lists

A very nice guide on this topic can be found here:
http://www.infoq.com/articles/SharePoint-Andreas-Grabner

Author gives suggestions how to greatly reduce roundtrips to content database and reviews typical scenarios with really large lists.

Sunday, June 7, 2009

Need code formatting for blog or wiki?

http://formatmysourcecode.blogspot.com/ 
has a nice webscript that generates HTML for your piece of code like this:

Console.WriteLine("Hello world");

Easy component registration for Windsor Container

If you are tired of forests of declarations for WindsorContainer you might find this do a trick for you:
var container = new WindsorContainer();
container.Register(AllTypes.Pick()
.FromAssembly(Assembly.GetExecutingAssembly())
.WithService
.FirstInterface());
This piece of code will search all types within running assembly and register them in container.

Implementing AOP logging with windsor container

Long time no see :) Today I'm going to describe how to create some AOP functionality based on attributes and we'll see how to implement a very common task - logging with attributes. The same way you can implement audit, OpsDB writes, security, caching and so on, whatever you will want to.

So let's head on and write a logger:
    public static class Logger
{
private static readonly List<string> _logs = new List<string>();
public static void Log(string logMessage)
{
_logs.Add(logMessage);
}

/// <summary>
/// Returns a readonly collection of log messages
/// </summary>
public static IList<string> Logs
{
get
{
return _logs.AsReadOnly();
}
}

public static void CleanWholeLog()
{
_logs.Clear();
}
}


And now the class we're going to use to test our logging, lets start with something really simple:
    [LoggedClass]
public class Calculator
{
[LoggedMember]
public virtual int AddWithFullLogging(int a, int b)
{
return a + b;
}
}

Now we want our attributes to work for us (Im not posting attributes code to spare some space as they are just empty classes inherited from Attribute). We would like to log parameters and return values of this method.

Lets head on with a unit test:
    [TestFixture]
public class When_calling_add_of_calculator
{
private const int FIRST_OPERAND = 2;
private const int SECOND_OPERAND = 3;
private const int RESULT = 5;
private readonly Calculator _calculator = ObjectFactory.GetCalculator();

[TestFixtureSetUp]
public void TestFixtureSetUp()
{
Logger.CleanWholeLog();
this._calculator.AddWithFullLogging(FIRST_OPERAND, SECOND_OPERAND);
}

[Test]
public void Both_parameters_and_return_value_get()
{
Assert.That(Logger.Logs.Count, Is.EqualTo(2));
}

[Test]
public void Parameters_are_logged_correctly()
{
var expectedParametersLogMessage = "Calculator.AddWithFullLogging method call. Parameters: :firstParam, :secondParam";
expectedParametersLogMessage = expectedParametersLogMessage.Replace(":firstParam", FIRST_OPERAND.ToString());
expectedParametersLogMessage = expectedParametersLogMessage.Replace(":secondParam", SECOND_OPERAND.ToString());
Assert.That(Logger.Logs[0], Is.EqualTo(expectedParametersLogMessage));
}

[Test]
public void Return_value_is_logged_correctly()
{
var expectedReturnValueLogMessage = "Calculator.AddWithFullLogging finished call. Return value: :returnValue";
expectedReturnValueLogMessage = expectedReturnValueLogMessage.Replace(":returnValue", RESULT.ToString());
Assert.That(Logger.Logs[1], Is.EqualTo(expectedReturnValueLogMessage));
}
}

We clear whole log before tests and then make a call to add function. Then we expect three things to happen: 
  1. logger has 2 new entries - one for parameters and one for return value
  2. parameters are logged correctly
  3. return value is logged correcly

We're using object factory to create calculator for us. This is needed, because otherwise we wont be able to attach interceptors to its methods.
Here's the code for ObjectFactory class:
    public static class ObjectFactory
{
private static WindsorContainer _container;
private static void Init()
{
if (_container == null)
{
_container = new WindsorContainer();
_container.AddFacility("LoggingFacility", new LoggingFacility());
_container.Register(Component.For(typeof(Calculator)));
}
}
public static Calculator GetCalculator()
{
Init();
return _container.Resolve<Calculator>();
}
}

It registers calculator in container and just before that it adds Logging facility which will be intercepting registrations and add interceptors if it will find proper attributes.

Ok, so now we have it all setup lets proceed with implementation of our logging facility. In our case we would like to add logging interceptor to every method tagged with [LoggedMember] within the class tagged with [LoggedClass].
    public class LoggingFacility : AbstractFacility
{
protected override void Init()
{
Kernel.AddComponent("LoggingInterceptor", typeof(LoggingInterceptor));
Kernel.ComponentModelBuilder.AddContributor(new LoggingContributor());
}
}



    public class LoggingContributor : IContributeComponentModelConstruction
{
public void ProcessModel(IKernel kernel, ComponentModel model)
{
if (model.Service.GetCustomAttributes(true).OfType<LoggedClassAttribute>().Count() == 1)
{
if (ServiceHasNonVirtualMethodsMarkedWithLoggedMemberAttributes(model))
{
throw new Exception("Cannot use LoggedMember attribute on nonvirtual members");
}
model.Interceptors.Add(new InterceptorReference(typeof(LoggingInterceptor)));
}
}

private static bool ServiceHasNonVirtualMethodsMarkedWithLoggedMemberAttributes(ComponentModel model)
{
return model
.Service
.GetMethods()
.Where(x => x.GetCustomAttributes(true)
.Where(y => y.GetType() == (typeof(LoggedMemberAttribute))).Count() == 1
&& !x.IsVirtual ).Count() > 0;
}
}

Lets run through the code. First we are defining our facility. It adds contributor to our model plus it registers interceptor that intercept calls and give logger a call. 
Then we difine contributor that checks if our service (in this case Calculator class) is tagged with [LoggedClass] attribute. If it is we're checking that every member with [LoggedMember] attribute is virtual, because we cannot intercept nonvirtual method calls thus making attribute not really working when used with nonvirtual members.
If all conditions are met we're adding logging interterceptor to method calls of calculator.

Now the easy part, we just have to implement interceptor:
    public class LoggingInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (invocation.Method.GetCustomAttributes(true).Where(x => x.GetType() == typeof(LoggedMemberAttribute)).Count() > 0)
{
Logger.Log(GetParamsMessageFor(invocation));
invocation.Proceed();
Logger.Log(GetReturnValueMessageFor(invocation));
}
else
{
invocation.Proceed();
}
}

private static string GetReturnValueMessageFor(IInvocation invocation)
{
var message = ":methodNameWithClassSpecifier finished call. Return value: :returnValue";
message = message.Replace(":methodNameWithClassSpecifier", invocation.TargetType.Name + "." + invocation.Method.Name);
message = message.Replace(":returnValue", invocation.ReturnValue.ToString());
return message;
}

private static string GetParamsMessageFor(IInvocation invocation)
{
var message = ":methodNameWithClassSpecifier method call. Parameters:";// :firstParam, :secondParam";
message= message.Replace(":methodNameWithClassSpecifier", invocation.TargetType.Name + "." + invocation.Method.Name);
if (invocation.Arguments.Length != 0)
{
message = AddInvocationArgumentsToMessage(message, invocation);
}
return message;
}

private static string AddInvocationArgumentsToMessage(string message, IInvocation invocation)
{
message += " " + invocation.Arguments[0];
foreach (var argument in invocation.Arguments.Skip(1))
{
message += ", " + argument;
}
return message;
}
}

Note that interceptor checks if called method has [LoggedMethod] attribute, else it would log any virtual method call (even one without this attribute).

Saturday, April 18, 2009

SPQueryBuilder - a handy class to build SP queries

Hey there again. As I'm getting bored with writing SPQuery's query all the time and I've got some better things to do in life, I've decided to create a handy class to do that work for me.
It allows you to use object model instead of writing queries in plain strings (like SP devs intent you to do).

String-coded queries tend to become a nightmare when you need to filter list using like 10 columns as a horde of xml nodes and attributes jumps on you from the corner. And of course you always tend forget about that closing tag here and there. Not to mention that readability of such code is below water line.

So instead you can now use SPQueryBuilder like that:

string queryString = new SPQueryBuilder()
                    .Eq(columnName1, columnValue1)
                    .Eq(columnName2, columnValue2)
                    .ToQuery();
SPQuery query = new SPQuery(){Query = queryString };
Console.WriteLine(queryString);

By default all expressions are joined by <And> tag, so code above will produce following output:
<Where><And>
<Eq><FieldRef Name=':ColumnName1'/><Value Type='Text'>:ColumnValue1</Value></Eq>
<Eq><FieldRef Name=':ColumnName2'/><Value Type='Text'>:ColumnValue2</Value></Eq>
</And></Where>

Note that you can join any number of expressions this way, say if you expressions ten times, all ten expressions will be joined.

To build <Or> tag you use .Or method of SPQueryBuilder (what a surprise!).
string queryString = new SPQueryBuilder()
.Or(Expressions.Eq(columnName1, columnValue1), Expressions.Eq(columnName2, columnValue2, column2Type))
.ToQuery();
SPQuery query = new SPQuery(){Query = queryString };
Console.WriteLine(queryString);

This call will produce the following output:
<Where><Or>
<Eq><FieldRef Name=':ColumnName1'/><Value Type='Text'>:ColumnValue1</Value></Eq>
<Eq><FieldRef Name=':ColumnName2'/><Value Type=':ColumnValueType2'>:ColumnValue2</Value></Eq>
</Or></Where>

Also note that default Value type is Text, is you want another type, use SPFieldType class.

So far those features are implemented:
  • Building expressions in chain calls style
  • Full support for Or and And expressions. You can build nested expressions of any complexity. Both Or and And expressions allow you to pass any number of expressions to as arguments. So you can check say 5 expressions in one Or call - Or(expr1, expr2, expr3, ...) and have them all  gathered under one big Or tag.
  • Eq expression (support for text and boolean fields so far, I'll include more field types soon, though it is very easy to extend types being supported, so you might as well add them on your own).
  • IsNull expression
  • IsNotNull expression

You can download code with tests here.

Lazy loading with Castle DynamicProxy library and it's comparison to other methods

Sometimes when you are working with domain objects you want to implement lazy loading for some class property or its collection. Lets say you have a Cat class which might have some kittens that are objects of Cat class as well. Kittens might have kittens as well etc. This might lead to chain loading half a database. To prevent this kind of troubles the easiest is to set inner field to null value and check for null in property getter like this:

    public class Cat
    {
        private IList _kittens = null;

        public string Name { get; set; }
        public IList Kittens
        {
            get
            {
                if (_kittens == null)
                {
                    _kittens = CatRepository.GetKittensFor(this);
                }
                return _kittens;
            }
        }
    }

    public class CatRepository
    {
        public static IList GetKittensFor(Cat cat)
        {
            IList kittens = new List();
            //Load kittens from DB for cat and return them
            return kittens;
        }

...

    }

This however leads to a problem. Now your domain object knows about persistance class CatRepository which in turn leads to Cat class being database dependent. That hurts your testing capabilities as you cannot call any test which involves Cat class a real Unit test as it becomes slow. 
One of the solutions would be to inject CatRepository into Cat class using interfaces. Code would look this way:

    public class Cat
    {
        private IList _kittens = null;
        private ICatRepository _catRepository;


        public void SetCatRepository(ICatRepository repository)
        {
            _catRepository = repository;
        }
        public  string Name { get; set; }
        public  IList Kittens
        {
            get
            {
                if (_kittens == null)
                {
                    _kittens = _catRepository.GetKittensFor(this);
                }
                return _kittens;
            }
        }
    }

    public interface ICatRepository
    {
        IList GetKittensFor(Cat cat);

...

    }

    public class CatRepository : ICatRepository
    {
        public IList GetKittensFor(Cat cat)
        {
            IList kittens = new List();
            //Load kittens from DB for cat and return them
            return kittens;
        }

...

    }


Note that CatRepository's method GetKittensFor isn't static anymore as a real instance of cat repository is used. Method SetCatRepository in Cat class allows you to inject any object into Cat object which is able to handle loading kittens from db. Thus you can use mock object in your unit tests to tear links to DB (other ways to inject CatRepository would be injecting in constructor, injecting in method getting kittens or using some IOC framework like Spring.NET to do it for you).

With dependency injection you still dont have clear POCO (Plain Old CLR Object) implementation of Cat class. POCO class doesn't have any knowledge on how it is saved, is it saved at all, neither do its children collections. POCO classes just have a number of properties and methods to manipulate it's state and send commands to other objects it knows about. This greatly simplifies the implementation of business logic in domain objects model.

Castle DynamicProxy allows you to implement lazy loading with object not even knowing any details of implementation. To do that you must define properties you are interested in as virtual so they can be be overridden by Castle framework. Lets make Cat a POCO class:

    public class Cat
    {
        private IList _kittens = new List();

        public Cat(string name)
        {
            Name = name;
        }

public int ID {get;set;}
        public string Name { get; set; }
        public virtual IList Kittens
        {
            get
            {
                return _kittens;
            }
        }
    }

Ok, that works fine with newly created Cat objects. However we cannot fill Kittens collection from our repository class unless we are working with class derived from Cat class.

Lets write GetCatById method of CatRepository which will return proxy of our Cat class so we can play with it further:

        public Cat GetCatById(int id)
        {
            var catName = "cat name from db";
            //Read catName from DataBase
            Thread.Sleep(1000);
            var proxyGenerator = new ProxyGenerator();
            var catProxy = (Cat)proxyGenerator.CreateClassProxy(typeof(Cat), null, catName);
            return catProxy;
        }

Lets see what's going on. We read catName from DB, emulating it with Thread.Sleep(1000). After that we are creating an instance of Castle's ProxyGenerator. To create a proxy of Cat class method CreateClassProxy is used which in our case takes 3 arguments: the type of class to be created, interceptors which we will use to implement lazy loading and finally params object[] with constructor arguments which is a catName in this case.

To check that this method is working correctly lets write some tests:
        [Test]
        public void CatRepository_can_get_cat_object_and_its_not_instance_of_cat_class()
        {
            Cat cat = new CatRepository().GetCatById(10);
            Assert.That(cat.GetType(), Is.Not.EqualTo(typeof(Cat)));
        }    
        [Test]
        public void CatRepository_can_get_cat_object_and_its_name_property_is_set_correctly()
        {
            Cat cat = new CatRepository().GetCatById(10);
            Assert.That(cat.Name, Is.EqualTo("cat name from db"));
        }

First test indicated that we are actually getting proxy, not Cat instance. Second one assures that Name property was correctly initialized from constructor.

Now lets proceed with intercepting getter of kittens to do lazy loading. CreateClassProxy accepts array of objects implementing IInterceptor interface. Interface consists of one method Intercept(IInvocation invocation). This method intercepts all calls to any virtual method or property. Param invocation has info on method being called so you can filter out calls you are actually interested in:

    public class CatLoaderInterceptor:IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            if (invocation.Method.Name == "get_Kittens")
            {
                Console.WriteLine("Get kittens was called!");
                var cat = (Cat) invocation.Proxy;
                var kittens = new CatRepository().GetKittensFor(cat);
                invocation.ReturnValue = kittens;
            }
        }
    }

We check that method that we intercepted is a getter for property Kittens. Then we load kittens from repository and return them as invocations result. So any time Kittens property is called we dig into database to fetch kittens out of it. Console.WriteLine helps to figure out when and how many times interceptor is being called in case you're using TestDriven.NET, Resharper test runner or such.
Now all we need to do is to attach interceptor to our proxy by passing it in CreateClassProxy call, so our GetCatById would look like this:

        public Cat GetCatById(int id)
        {
            var catName = "cat name from db";
            //Read catName from DataBase
            Thread.Sleep(1000);
            var proxyGenerator = new ProxyGenerator();
            var catProxy = (Cat)proxyGenerator.CreateClassProxy(typeof(Cat),new IInterceptor[]{ new CatLoaderInterceptor()}, catName);
            return catProxy;
        }

By changing GetKittensFor method we can test it abit:

        public IList GetKittensFor(Cat cat)
        {
            IList kittens = new List() {new Cat("kitty")};
            //Load kittens from DB for cat and return them
            Thread.Sleep(10000);
            return kittens;
        }

        [Test]
        public void CatLoaderInterceptor_correctly_intercepts_get_Kittens_method_call_and_proper_kitten_is_returned()
        {
            Cat cat = new CatRepository().GetCatById(10);
            Assert.That(cat.Kittens[0].Name, Is.EqualTo("kitty"));
        }

Ok, so lets have an overview what's happening. We get a proxy of Cat object out of repository. Then any time we get its kittens we get a 10 seconds hang up while reading them from db. So we should to ensure that kittens are initialized only once. Lets write a test to prove it works:

        [Test]
        public void CatLoaderInterceptor_initializes_kittens_only_once()
        {
            Cat cat = new CatRepository().GetCatById(10);
            cat.Kittens.Add(new Cat("Missy"));
            Assert.That(cat.Kittens.Count, Is.EqualTo(2));
        }

At the moment in this test interceptor reads Kittens collection from database two times and assertion doesn't pass so the test fails. 

We need some kind of flag to indicate if Kittens were already loaded for this object. Lets implement that flag in interceptor we're passing to proxy:

    public class CatLoaderInterceptor : IInterceptor
    {
        private bool AreKittensLoaded { get; set; }

        public void Intercept(IInvocation invocation)
        {
            if (invocation.Method.Name == "get_Kittens")
            {
                Console.WriteLine("Get kittens was called!");
                if (!AreKittensLoaded)
                {
                    var cat = (Cat)invocation.Proxy;
                    var kittens = new CatRepository().GetKittensFor(cat);
                    AreKittensLoaded = true;
                    cat.Kittens = kittens;
                }
                invocation.Proceed();
            }
        }
    }

Now when we are reading Kittens from DB for first time we do a couple of things. First we set flag that collection was loaded, second we init kittens collection of Cat class. Then we call invocation.Proceed() which just passes control to object being called in our case object of type Cat.
Note that this requires Cat class to expose set method for its Kittens collection, alternately you may as well just add kittens to existing empty collection.


Another test to prove that we got desired behaviour will test than second invocation of kittens ends up in less than one second will look like this:
         [Test]
        public void CatLoaderInterceptor_reads_kittens_collection_second_time_for_less_than_a_second()
        {
            Cat cat = new CatRepository().GetCatById(10);
            var readingKittens = cat.Kittens;
            var beforeReadingKittens2ndTime = DateTime.Now;
            var readingKittensAgain = cat.Kittens;
            var afterReadingKittens2ndTime = DateTime.Now;
            var timeToReadKittens2ndTime = afterReadingKittens2ndTime.Subtract(beforeReadingKittens2ndTime);
            var oneSecondTimeSpan = new TimeSpan(0, 0, 0, 1);
            Assert.That(timeToReadKittens2ndTime, Is.LessThan(oneSecondTimeSpan));
        }     


Alright, now everything works. To sum up what we have accomplished: now we got a POCO cat object that has its kitten collection lazy loaded with out it knowing anything about how it's actually done. Only price it has to pay for this feature is to declare Kittens property as virtual, not a big deal :) 

Thanks for reading, wonder if this was useful to you?

You can get solution here:

P.S. Please note that you don't have to implement lazy loading usually because ORM frameworks such as NHibernate can do that for you. Personally, I'm going to use it for my Repository classes using SharePoint as a datasource.

Friday, April 17, 2009

Renaming projects in Visual Studio

Its bit more tricky than just hitting right button on project and picking rename command:

1. Rename project by right clicking and chosing "Rename".
2. Rename assembly and set default namespace by right clicking it and chosing "Properties".
3. Rename assembly title and assembly product in AssemblyInfo.cs within Properties folder.
4. Exit visual studio and rename projects folder. After that load solution and skip warning concerning project not being found. Select greyed out project and pick new path in properties window.

Tuesday, April 14, 2009

How to upload file to user with ASP.NET

Following code snippet allows to write file to http responce stream thus allowing users to download files dynamically created by your web application. 


var filename = @"C:\temp\Report.xls";
Page.Response.ContentType = "application/vnd.ms-excel";
Page.Response.AddHeader("Content-Disposition", 
"attachment; filename= Report.xls");
            
byte[] bytes = File.ReadAllBytes(filename);
Page.Response.OutputStream.Write(bytes, 0, bytes.Length);
Page.Response.OutputStream.Flush();
Page.Response.End();

Note that filename in Page.Responce.AddHeader can be changed to the one you want user to see when his/her download window popups.

Saturday, April 4, 2009

AutoDiagrammer and Dependency Structure Matrix addins for Reflector


Reflector is a great tool for any .NET developer. However you can make it even better with addins. Today I got two of them for you. Without further delay our first reviewee is...



AutoDiagrammer














This plugin allows you to build class diagrams within your Reflection thus source code isn't necessary at all. Its has bunch of options like show/hide interfaces, supports zooming in and out, printing and saving in different image formats.

Lightweight and easy to use this tool might come in handy.



Dependency Structure Matrix plugin


Dependency Structure Matrix (DSM) allows you to get an insight about connections between your modules in way more scalable view rather than typical structure diagramm. This gives you opportunity to review whole project on one screen rather than scrolling through forest of classes with arrows connecting them.

On the screen below you can see DSM addin reviewing NUnit 2.4.8 dlls:














If you haven't yet got used to DSMs this little tool might open a new way for you to think about dependency analysis (if you're already using NDepend this addin won't do much for you, still it's lightweight and might find its uses). 

DSM consists of rows and columns. They indicate which namespaces use other ones to do their work:
  • Rows give you info what namespaces use particular namespace. For example namespace NUnit.Mocks on image above is being used by only namespace with number 340 - NUnit.Core. 
  • Likewise you can check which namespaces are being used with your module by looking at its column. NUnit.Mocks being represented by column with number 29 in header depends on NUnit.FrameWork.
DSM shows you circular dependencies. For example NUnit.Core and NUnit.Util are dependant on each other.

Typical DSM application allows you to dig deeper into modules for more information. You can do that as well with DSM plugin for Reflector.

In typical multilayered architecture where lower level layers aren't allowed to use higher leve
l functionality DSM will give you a picture of triangle - top right triangle wont have any numbers in it:











With even more strict rule where layer is allowed to use only its neighbour layer beneath it, the picture all numbers will be right under the diagonal line:











Plugin allows you to sort modules with partition command so you get a normalized view.

It takes some time to get used to DSM, but when mastered pattern matching mechanics of your brain will do a good job for you with help of this kind of utils. This little plugin will help you to make your first step in that direction.


For further reading on DSM check the following document:

Sunday, March 29, 2009

Hello and welcome

Hello there and welcome. This is my first blog ever, so it probably will take some time to set up. 

The main idea behind starting this type of activity (yeah, sitting in front of computer typing nonsences is an activity as well) was...well not so altruistic but rather somewhat selfish - to learn english, get somewhat famous and of course to get better self-awareness. Driving a blog is a good plan if you want to familiarize yourself with subject you describe in it. To be honest it was a long time I wanted to create some page like this but as usual didn't have time to start. I bet you know this kind of feeling. When something comes up to your mind, you're full of enthusiasm about your brilliant idea, you even start planning realization of it. But then, few days later the idea vapors out of your most brilliant head just to settle in someone's else chatbox I guess (lets hope that guy can make it up for you). So don't forget to act. The mere idea isn't enough; the action is what it makes material and thus useful.

Oh and by the way...this blog is going to be a fuse of programming techniques and mind works. I'm going to describe my thoughts about and experiences with computer programs I write, frameworks I use, in other words useful stuff. Plus I'm going to dig into methodology behind being a good programmer, a good team leader, a good manager and so on (in other words you'll find information on things that make up a bad system into a good one - humans and their interaction with world and each other).


The muse to start this blog that inspired me was an impressive piece of pragmatic library - Refactor your wetware. In this book, the author Andy Hunt is explaining how all-way-out-logical-thinking does cripple your abilities to program a good system. The main idea behind this book is to make you realize that your brain isn't just a linear system that process information the typical computer device you're reading this text from but rather is a complicated symbiosis of two great "CPUs" - one is responsible for logical way of thinking and another one is your search engine, that drives your intuition and stores virtually everything you experience. Yes, even things you don't even notice...do you remember your teeth brushing this morning? You do that every day and the logical part of your brain isn't very excited with a perspective to analyse what happens. But the thing is that this information still gets into your head without you realizing it. It sits there till your intuition needs some particular knowledge and scans through everything that's in your mind pot. 

I'll cover this book in more detail later, it's really worth it. Just try it and you'll see.