Using Castle’s Dynamic Proxy

17 Dec

As a user of Rhino Mocks, Ninject and certain parts of the Castle Project, I found myself wondering what the Castle Project’s dynamic proxy was. I have since learned and love the idea of, dynamic proxies.

What does a dynamic proxy do

A dynamic proxy is a way of generating a subclass from a class or interface of which is generally a model. That subclass overrides every method that it can (make your methods virtual to allow to do it). This provides the ability to intercept calls to all methods on your class/interface because the sub-classed methods route requests to an interface which dictates whether a call can proceed. You could implement that functionality yourself, however you would need to cater for all method calls. The dynamic proxy provides one interceptor handler for all methods, and you can have many interceptors on one class.

Cross cutting concerns

One of the major benefits of using proxy objects is the ability to separate cross cutting concerns such as logging. Take the following diagram as an example. It shows how the logging interceptor which takes care of the logging can log calls made to the person object without the person object having a reference or knowing about the logging interceptor. The person object also doesn’t know about the dynamic proxy library.

DynamicProxyDiagram

An argument for separating out logging from our classes could be that we might want to turn logging on or off, or that we want to replace our logging library at a later date. Both of those scenarios could be catered for by having a logging class which is directly called by our Person object. The advantage of doing that could be minor performance gains, and the disadvantage of not using a proxy is that the person object would be polluted with unnecessary code. Ideally a class would have a single purpose, and logging would not conform to the purpose of the person business object in my opinion because logging is an environmental aspect regarding person as opposed to actually defining what a person is. A strong example of this is using a dynamic proxy to add permission based access to calls on third party libraries without modifying the external library.

Interceptors

The following code shows how a logging interceptor might look. It logs the method name of the method that is currently being accessed, then it allows the method request to proceed. Without invocation.proceed, the call would not proceed to the person object in the previous example, and would instead be consumed.

    public class LoggingInterceptor : IInterceptor

    {

        public void Intercept(IInvocation invocation)

        {

            Console.Write("Log: Method Called: "+ invocation.Method.Name);

            invocation.Proceed();

        }

    }

 

Boxing and Un-boxing proxies

To create a proxy you can do the following:

ProxyGenerator generator = new ProxyGenerator();

Person person = generator.CreateClassProxy<Person>(new LoggingInterceptor());

 

If you are developing in a situation where you have a network boundary and you need to send your business objects across a network you will probably want to shed your proxies and possibly recreate the proxies on the other side of the network boundary.

var proxyTarget = personProxyObject as IProxyTargetAccessor

var person = proxyTarget.DynProxyGetTarget() as Person;

 

More Information

C# Actions part 2: Lazy evaluation

14 Jul

Lazy Evaluation example:

In a previous post I talked about C# Actions and how they are a useful feature that could provide new shorthand for lazy evaluation. I have since found an excellent article [1] which demonstrates lazy evaluation with LINQ. The advantages in that article show how LINQ queries can minimize memory usage by evaluating upon enumeration rather than just allocating memory for everything the query would return.

Func

Actions are delegates that have a void return type. This makes sense if you are using Actions as event handlers, but for other use cases you will want a return type. In these cases you will want to use Func. One issue I have seen with Func is when you want don’t know how many parameters your function is going to take. If the number is variable then you must implement up to the amount of parameters you want (if overloading). I noticed a few examples of that in the Ninject 1.x source code. To generalize Func and Actions you can use the ‘Delegate’ type (note: the captialization).

A real world use case

A reason for lazy evaluation could be that you want to perform a group of service calls at one time. The service calls could be a transaction style interaction which would want to be disposed afterwards and some of the service calls could be surplus to requirement. If I had a user interface which required a list of products to be loaded, then that screen may not need that data reloaded if it is moving from a screen which has that data loaded. That service call could be pre-evaluated (ie lazy evaluation) to check to see if it is necessary.

Observable Dictionary

13 Jul

As a fan of ObservableCollections, I have created an observable dictionary. I have provided the code below. I have implemented interfaces that should allow for WPF databinding. The reason I needed such a class is because I needed an event to indicate when the dictionary was updated. I kept this class small (it is just a wrapper over a dictionary).

public class ObservableDictionary<TKey, TValue> :

        IDictionary<TKey, TValue>,

        INotifyCollectionChanged,

        INotifyPropertyChanged

{

    public event NotifyCollectionChangedEventHandler CollectionChanged;

    public event PropertyChangedEventHandler PropertyChanged;

 

    readonly IDictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();

 

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()

    {

        return _dictionary.GetEnumerator();

    }

 

    IEnumerator IEnumerable.GetEnumerator()

    {

        return GetEnumerator();

    }

 

    public void Add(KeyValuePair<TKey, TValue> item)

    {

        _dictionary.Add(item);

 

        if (CollectionChanged != null)

            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));

 

        if (PropertyChanged != null)

        {

            PropertyChanged(this, new PropertyChangedEventArgs("Keys"));

            PropertyChanged(this, new PropertyChangedEventArgs("Values"));

        }

    }

 

    public void Clear()

    {

        int keysCount = _dictionary.Keys.Count;

 

        _dictionary.Clear();

 

        if (keysCount == 0) return; //dont trigger changed event if there was no change.

 

        if (CollectionChanged != null)

            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

 

        if (PropertyChanged != null)

        {

            PropertyChanged(this, new PropertyChangedEventArgs("Keys"));

            PropertyChanged(this, new PropertyChangedEventArgs("Values"));

        }

    }

 

    public bool Contains(KeyValuePair<TKey, TValue> item)

    {

        return _dictionary.Contains(item);

    }

 

    public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)

    {

        _dictionary.CopyTo(array, arrayIndex);

    }

 

    public bool Remove(KeyValuePair<TKey, TValue> item)

    {

        bool remove = _dictionary.Remove(item);

 

        if (!remove) return false; //don’t trigger change events if there was no change.

 

        if (CollectionChanged != null)

            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove));

 

        if (PropertyChanged != null)

        {

            PropertyChanged(this, new PropertyChangedEventArgs("Keys"));

            PropertyChanged(this, new PropertyChangedEventArgs("Values"));

        }

 

        return true;

    }

 

    public int Count

    {

        get { return _dictionary.Count; }

    }

 

    public bool IsReadOnly

    {

        get { return _dictionary.IsReadOnly; }

    }

 

    public bool ContainsKey(TKey key)

    {

        return _dictionary.ContainsKey(key);

    }

 

    public void Add(TKey key, TValue value)

    {

        _dictionary.Add(key, value);

 

        if (CollectionChanged != null)

            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));

 

        if (PropertyChanged != null)

        {

            PropertyChanged(this, new PropertyChangedEventArgs("Keys"));

            PropertyChanged(this, new PropertyChangedEventArgs("Values"));

        }

    }

 

    public bool Remove(TKey key)

    {

        bool remove = _dictionary.Remove(key);

 

        if (!remove) return false;

 

        if (CollectionChanged != null)

            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove));

 

        if (PropertyChanged != null)

        {

            PropertyChanged(this, new PropertyChangedEventArgs("Keys"));

            PropertyChanged(this, new PropertyChangedEventArgs("Values"));

        }

 

        return true;

    }

 

    public bool TryGetValue(TKey key, out TValue value)

    {

        return _dictionary.TryGetValue(key, out value);

    }

 

    public TValue this[TKey key]

    {

        get { return _dictionary[key]; }

        set

        {

            bool changed = _dictionary[key].Equals(value);

 

            if (!changed) return; //if there are no changes then we don’t need to update the value or trigger changed events.

 

            _dictionary[key] = value;

 

            if (CollectionChanged != null)

                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace));

 

            if (PropertyChanged != null)

            {

                PropertyChanged(this, new PropertyChangedEventArgs("Keys"));

                PropertyChanged(this, new PropertyChangedEventArgs("Values"));

            }

        }

    }

 

    public ICollection<TKey> Keys

    {

        get { return _dictionary.Keys; }

    }

 

    public ICollection<TValue> Values

    {

        get { return _dictionary.Values; }

    }

}

 

A link to another (Larger) implementation of an Observable Dictionary: http://www.drwpf.com/Blog/Default.aspx?tabid=36&EntryID=8

CC0
To the extent possible under law, Richard Wilburn has waived all copyright and related or neighboring rights to Observable Dictionary. This work is published from New Zealand.

C# Action’s

5 Jul

When playing around with UI events it is sometimes handy to use lambda notations of actions to do a tidy inline event-action handler definition such as:

Button1.Click += (sender, args) => Debug.WriteLine("Button Click");
 

If we delve a little deeper into Actions, we can use them to pass around code snippets/functions.

Action<String> action = (input) => Debug.WriteLine("Testing" + input); 
 

I have heard many arguments against functional features such as actions in C# however I do feel that they are very useful in edge cases. One such case could be the mass adding of items to a dictionary, such as:

var namesDictionary = new Dictionary<int, string>();
 
namesDictionary.Add(1,"One");
namesDictionary.Add(2,"Two");
namesDictionary.Add(3,"Three");
 

If we wanted to keep our code maintainable we might want to reduce our dependency to the Add method (especially if we had lots of dictionary add statements).

Action<int,string> addAction = (key,value) => namesDictionary.Add(key,value);
//Action<int,string> addAction = namesDictionary.Add; //short syntax

addAction(1, "One");  //etc
 

Note that this dictionary example is a bad example as the collection initialization could be used here which is likely the most optimal solution. The following shows how the collection initialization could have been used:

var namesDictionary = new Dictionary<int, string> {{1, "One"}, {2, "Two"}, {3, "Three"}};
 

This example also could have been solved more optimally using extension method(s), by extending the dictionary, dependency injection, lambda foreach statement, foreach loop etc. With that said, Actions are important in allowing for lazy evaluation/delayed invocation. I am not going to get into lazy evaluation in this post, but I recommend checking out the Haskell language community for lazy evaluation ideas. I highly recommend the following link for understanding how evaluation/manipulation of lambda expressions work.

http://msdn.microsoft.com/en-us/library/bb397951.aspx

Boosting Visual Studio Performance

6 Mar

Visual Studio has always worked fairly well for me at home, but at work where many of our projects/solutions are very large Visual Studio struggles. At home I still find that my Visual Studio is better than the one I use at work and I believe this is because at home I have my hard-drives in a performance RAID (Raid 0) and my OS is Vista x64 rather than XP x86.

Two things I suspect are:

Vista manages memory much better and doesn’t struggle with the out of memory exceptions that I frequently get at work. Note: Out of memory exceptions are actually to do with the .NET runtime not being able to garbage collect all of its generations properly. But the size of Visual Studio and the number of objects it is using is the cause of this.

Hard-drive speed affects Visual Studio more greatly than CPU and potentially even RAM. When I get out of memory exceptions at work (we all get this too btw) my PC is not using all of its 2 gigs of ram. Visual Studio is limited by default to 2 gigs, but this can be overcome.

Remedies:

 

Faster harddrives, lowerlatency hard drives:

On Vista with my RAID 0 my experience is better but is still latent. My IDE can load lots of data fast but often takes a while to do so. This means waits are still a small amount of time due to latency issues but large amounts of data are not really an issue.

I am starting to think that the ideal solution is a performance raid of Solid State Drives (SSD).  A link on performance improvements for a Java IDE are available here: http://jexp.de/blog/archives/18-On-Boosting-My-IDEA-Jetbrains-IntelliJ-IDEA-is-fast-again.html

If you have an infinite money pool, a RAID card would be recommended too. These can have RAM on them to cache disk access which would further reduce latency.

Upgrade OS:

Upgrade to Vista and make sure you upgrade to the 64 bit version. It is silly not to take advantage of your CPU being x64.

Myths:

 

Resharper:

Myth: Reshaper significantly degrades performance, and causes out of memory exceptions.

Interestingly resharper shows the out of memory exceptions (which can be a pain) where as Visual Studio virtually hides it from the user. Resharper is not causing these issues, and from what I have seen there is no significant performance difference apart from when the project is being loaded. That is because resharper loads its cache then by analysing assemblies.

RAM:

Myth: Increasing RAM will increase Visual Studio’s performance

I think that if Visual Studio is running out of memory then a RAM increase will help, but for us at work our RAM is not being fully utilized so on XP increasing our RAM won’t help us as the OS will not use it. On Vista however the OS endeavours to use as much free RAM as it can to cache and pre-allocate so it is possible this will help a little bit. I think the biggest myth about personal computing is that upgarding CPU and RAM makes the biggest difference. My computer at home is 4 years old and my computer at work is 6 months old. My computer at home that is 4 years old is faster in practical usage. If it came down to a number crunching war then the new computer would win but there is virtually no use case for that in personal computing.

Updating an item in a list without a reference with lambdas

15 Feb

I have to confess I am enjoying lambdas a bit much. I am making this post to show a cool way of avoiding code loops (there are still loops in CLR of course).

private void UpdatePerson(Person updatedPersonObject)
{
    var outOfDatePerson = _people
            .First(person => person.Id == updatedPersonObject.Id);
    int index = _people.IndexOf(outOfDatePersonObject);
    _people[index] = updatedPersonObject;
}

private void UpdatePerson_OldCSharp(Person updatedPersonObject)
{
    int outOfDatePersonIndex = 0;
    for (int i = 0; i < _people.Count ; i++ )
    {
        if (_people[i].Id == updatedPersonObject.Id)
        {
            outOfDatePersonIndex = i;
            break;
        }
    }
    _people[outOfDatePersonIndex] = updatedPersonObject;
}

From the two code samples it is worth noticing the difference in the number of lines and in the hierarchical nature of the code. The traditional C# for loop approach (the second method) leads me to cringe from a maintenance point of view. Each line of code is highly contextual and relies heavily on multiple levels of language constructs.

The first method (the lambda way) to me is much more readable and also maintainable. There is a flat hierarchy which is much easier to read as it doesn’t involve following the loop through code. I argue it is easier to maintain as the lines can change order more and will still be doing the same thing. It is also easier to update as there is less code.

Databinding to Collections

15 Feb

If you use WPF then you will be using databinding extensively. This post looks at databinding with respect to collections.

Databinding basics (Background Info):

To databind in .NET currently you are required to provide notification of when the variables you databind to change. This can be done by implementing the INotifyPropertyChanged interface or by implementing the property as a dependency property. For more information on databinding basics, see here.

Collections are slightly different

In the case of collections it is often not important when a collection object changes but rather when the items within that collection change. With that said you will likely need both approaches implemented because if an entire collection is reassigned the binding to the observable collection will be lost as it has been replaced with a new observable collection. It is also possible that others in your team will re-assign the list at some point, so that is why I like to plan for that situation.

private ObservableCollection<String> _names;
internal ObservableCollection<String> Names
{
    get { return _names; }
    set
    {
        _names = value;
        PropertyChanged(this, new PropertyChangedEventArgs("Names"));
    }
}

 

ObservableCollection<T> notifies bindings an item has changed from its CollectionChanged event. The previous code sample shows the INotifyPropertyChanged interface implementation which is required to see if the ObservableCollection assigned to “Names” has been changed. 

In conclusion all Lists that are going to be used for databinding should be ObservableCollections. All properties that are databinded to should implement the INotifyPropertyChanged interface or be dependency properties.