Apr 30 2010

Slides and code from my lightningtalk at NNUG

Category: C# | Presentation | Speakerfossmo @ 02:37

Yesterday I held a presentation at NNUG about NServicebus. The code and the slide were requested by some. Here you go:

NServicebus.pdf (754.20 kb) 

NServicebusExample.zip (5.28 mb)

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Jul 29 2009

How to set the windows position in WPF

Category: WPF | C#fossmo @ 17:18

To position a window manually on the screen in Window Presentation Foundation you can use these system properties Window.Left and Window.Top. To get the size of the screen you can use these system properties:

System.Windows.SystemParameters.PrimaryScreenWidth;
System.Windows.SystemParameters.PrimaryScreenHeight;

To set a window (the green one) position like the one shown at the image below, you can use this method:

private void SetWindowPosition()
{
    Left = SystemParameters.PrimaryScreenWidth - (double)GetValue(WidthProperty) - 30; ;
    Top = 150;
}

image

Tags:

Currently rated 4.5 by 2 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Mar 17 2009

How to create an attached property in WPF using a ComboBox

Category: WPF | C#fossmo @ 17:37

This is mostly a note to myself on how to create an attached property in WPF using a ComboBox.

public class SelectionBehavior
{
    public static DependencyProperty SelectionChangedProperty =
            DependencyProperty.RegisterAttached("SelectionChanged",
            typeof(ICommand),
            typeof(SelectionBehavior),
            new UIPropertyMetadata(SelectionBehavior.SelectedItemChanged));
    public static void SetSelectionChanged(DependencyObject target, ICommand value)
    {
        target.SetValue(SelectionBehavior.SelectionChangedProperty, value);
    }
    private static void SelectedItemChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        Selector element = target as Selector;
        if (element == null) throw new InvalidOperationException("This behavior can be attached to Selector item only.");
        if ((e.NewValue != null) && (e.OldValue == null))
        {
            element.SelectionChanged += SelectionChanged;
        }
        else if ((e.NewValue == null) && (e.OldValue != null))
        {
            element.SelectionChanged -= SelectionChanged;
        }
    }
    private static void SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        UIElement element = (UIElement)sender;
        ICommand command = (ICommand)element.GetValue(SelectionBehavior.SelectionChangedProperty);
        command.Execute(((Selector) sender).SelectedValue);
    }
}

And in the XAML file add

<ComboBox local:SelectionBehavior.SelectionChanged="{Binding MyCommand}"  
              ItemsSource="{Binding MySource}"
              Name="MyComboBox"/> 

 

MyCommand can be a DelegateCommand from CAG.

Tags:

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Jan 5 2009

Inversion of Control Containers

Category: C# | Patternsfossmo @ 05:35

Inversion of Control Container is easily put a hash table. A hash table that has a bunch of interfaces versus concrete types. There are a lot of these containers on the web. Some of the most used ones is Windsor, Autofac, Structuremap, Ninject and Unity. I will use Unity later in this post. To try to explain the concept of a IOC container, I will create a very simple one. The two main reasons I use IOC containers is to create loosely coupled applications and it helps me unit test my applications in an easy way. The core concept of dependency inversion principle, which a IOC container is based on, is that high level modules should not depend on the low level ones, but they should both depend on abstractions. The abstraction in these cases are interfaces or abstract-based classes. I recommend that you read my previous blog post about dependency injection if you don't know what dependency inversion principle is.

Let's create the IOC container.

  1:     public class MyIocContainer
  2:     {
  3:         private static readonly IDictionary<Type, object> objDictornary = new Dictionary<Type, object>();
  4: 
  5:         public static T Resolve<T>()
  6:         {
  7:             return (T)objDictornary[typeof(T)];
  8:         }
  9: 
 10:         public static void Register<T>(object objToRegister)
 11:         {
 12:             objDictornary.Add(typeof(T), objToRegister);
 13:         }
 14:     }

In 14 lines of code we have a very simple IOC container. If you want to start using a IOC container, but you can't add a third party library to your project, this could be an easy way to get some of the benefits a IOC container can give you. But, you are of course missing out on a lot of the features a "real" IOC container can provide. Some of the valuable features this container don't contain is allowing different styles of configuration (XML or annotations), lifetime management and autowiring. I will look into autowiring in a later post.

In the first post about DI and IOC containers, I ended the post with doing a poor man's dependency injection (line 11 in the code example below). I think the technical term for this is constructor initialization. This is done if you only want to expose only one of the parameters to the user of your library.

  1:           public Butler(IWeapon weapon, ICommunicate communicate)
  2: 
  3:           {
  4: 
  5:               _weapon = weapon;
  6: 
  7:               _communicate = communicate;
  8: 
  9:           }
 10: 
 11:           public Butler(IWeapon weapon): this(weapon, new Communicate())
 12: 
 13:           {}

Poor man's dependency injection works great, but it will give me a tight coupling against the Communication class. How can we get rid of this tight coupling? We can do as the code example below shows. In stead of creating a object in the constructor initializer I input "objects" from MyiocContainer as parameters.

  1:         public Butler():this(MyIocContainer.Resolve<IWeapon>(), MyIocContainer.Resolve<ICommunicate>())
  2:         {}
  3: 
  4:         //public Butler(IWeapon weapon): this(weapon, new Communicate())
  5:         //{}

We need to create a interface for the communicate class, of course. This was done in the post about dependency injection, but I repeate it here for convinience.

  1:     public interface ICommunicate
  2:     {
  3:         void Speak(string phrase);
  4:     }

Now we have a interface for the communicate class. Let's see how we can use MyiocContainer in the program.

  1:        class Program
  2:        {
  3:            static void Main(string[] args)
  4:            {
  5:                MyIocContainer.Register<IWeapon>(new Poison());
  6:                MyIocContainer.Register<ICommunicate>(new Communicate());
  7:    
  8:               Butler butler = new Butler();
  9:               butler.Kill("The young man");
 10:               butler.Speak("Drink this if you dare, Sir!");
 11:               Console.ReadKey();
 12:           }
 13:       }

The output after running the code above, looks like this.

image

Cool. This is nice. I now have a application where the dependencies is mostly based on interfaces. I can insert a new communication class or a weapon class as long as they implement the interfaces ICommunication and IWeapon. But, now we have a coupling against the IOC container we created. I need to create a abstraction. Doing this I can choose another container later. If I want to use Unity, Structuremap or another IOC container, it won't be a problem.  Lets create the abstraction using the static gateway pattern.

  1:     public static class MyContainerAbstractor
  2:     {
  3:         private static IResolver _resolver;
  4:         public static T Resolve<T>()
  5:         {
  6:             return _resolver.Resolve<T>();
  7:         }
  8: 
  9:         public static void Init(IResolver resolver)
 10:         {
 11:             _resolver = resolver;
 12:         }
 13:     }
 14: 
 15:     public interface IResolver
 16:     {
 17:         T Resolve<T>();
 18:     }

In the Butler class's constructor I do these changes.

  1: public Butler():this(ContainerAbstractor.Resolve<IWeapon>(), ContainerAbstractor.Resolve<ICommunicate>())

Then I need to change MyiocContainer to implement the interface I created and remove the static keywords.

  1:     public class MyIocContainer:IResolver
  2:     {
  3:         private readonly IDictionary<Type, object> objDictonary = new Dictionary<Type, object>();
  4: 

  5:         public T Resolve<T>()
  6:         {
  7:             return (T)objDictonary[typeof(T)];
  8:         }
  9: 
 10:         public void Register<T>(T obj)
 11:         {
 12:             objDictonary.Add(typeof(T), obj);
 13:         }
 14:     }

The main method will look like this after we have done the changes.

  1:     class Program
  2:     {
  3:         static void Main(string[] args)
  4:         {
  5:             MyIocContainer container = new MyIocContainer();
  6:             container.Register<IWeapon>(new Poison());
  7: 
  8:             container.Register<ICommunicate>(new Communicate());
  9:             container.Register<IButler>(new Butler());
 10:             
 11:             ContainerAbstractor.Init(container);
 12: 
 13:             IButler butler = new Butler();
 14:             butler.Speak("Drink this if you dare, Sir!");
 15:             butler.Kill("The young man");
 16:             Console.ReadKey();
 17:         }
 18:     }

Now we are using a abstraction against the IOC container. It's easy to use an other container if we want to do that. Let's create a abstraction against Unity.

  1:     public class MyUnityContainer:IResolver
  2:     {
  3:         readonly IUnityContainer myContainer = new UnityContainer();
  4: 
  5:         public T Resolve<T>()
  6:         {
  7:             return myContainer.Resolve<T>();
  8:         }
  9: 
 10:         public void Register<T>(object obj)
 11:         {
 12:             myContainer.RegisterInstance<T>((T)obj);
 13:         }
 14:     }

To run the program with the Unity container we can just replace one line of code in the main method. Replace

  1: MyIocContainer container = new MyIocContainer();

with

  1: MyUnityContainer container = new MyUnityContainer();

and we will get the same output as before

image

That's it for now. I recommend you to look into IOC containers if you already haven't done so.
In the next post I will show how to create a very simple autowiring mechanism in my home made IOC container.

Tags: , , ,

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Dec 23 2008

Murder mysteries and Dependency Injection

Category: C# | Patternsfossmo @ 07:50

 

imageTo try to explain Dependency Injection and Inversion of Control Containers, I'm going to get inspiration from some old detective novels. When I say old, I think of novels like the ones Agatha Christie wrote. This first post will explain Dependency Injection, and the second one will explain Inversion of Control Containers. To start our story we need some characters.

Please welcome:
The Colonel - This is the old guy with the white mustache and monocle.
The young man - He is in love with the woman, and is always trying to show his interest for her.
The woman - She is a countess and have a very rich father (probably the reason the young man got into her in the first place).
The butler - He is always the killer, likewise in this story. 
The detective - Always traveling around running into mysteries to solve.

We should probably have at least ten characters more, but this will do for our examples. They are all invited to a big mansion to spend the weekend there. 

To get our story going, we need a weapon. Let's create one.

  1:     public class Gun
  2:     {
  3:         public void UseWeaponOn(string target)
  4:         {
  5:             Console.WriteLine(string.Format("{0} is shot dead!", target));
  6:         }
  7:     }

In most of the "Agatha Christie-like" detective novels, the butler is the villain. In this story he is the villain to. Let's create a butler so he can start committing crimes (read: killing ;-) ).

  1:     public class Butler
  2:     {
  3:         private Gun _gun;
  4: 
  5:         public Butler()
  6:         {
  7:             _gun = new Gun();
  8:         }
  9: 
 10:         public void Kill(string target)
 11:         {
 12:             _gun.UseWeaponOn(target);
 13:         }
 14:     }

The butlers first target is the colonel:

  1:     class Program
  2:     {
  3:         static void Main(string[] args)
  4:         {
  5:             Butler butler = new Butler();
  6:             butler.Kill("The Colonel");
  7:             Console.ReadKey();
  8:         }
  9:     }

This is what happens after the code is run:

image

The butler has killed his first victim. But, he has a problem. After killing the colonel, he have to find a new weapon for his next kill, because the detective is snooping around the mansion and he has found the murder weapon. This also gives us a problem. Since the gun is created inside the butler class's constructor, we have to modify the implementation of the class in order to make this change.

Coupling or dependency is the degree to which each program module (class) relies on each one of the other modules (classes). The butler class is tightly coupled to the gun class. When modules are tightly coupled, they cannot be replaced without altering their implementation. In order to avoid tightly coupled classes, we can use interfaces to provide a level of abstraction. Let's create an interface to represent a weapon.

  1:     public interface IWeapon
  2:     {
  3:         void UseWeaponOn(string target);   
  4:     }

Then we can implement the interface in the gun class.

  1:     public class Gun:IWeapon
  2:     {
  3:         public void UseWeaponOn(string target)
  4:         {
  5:             Console.WriteLine(string.Format("{0} is shot dead!", target));
  6:         }
  7:     }

And now we can change the butler class.

  1:     public class Butler
  2:     {
  3:         private IWeapon _weapon;
  4: 
  5:         public Butler()
  6:         {
  7:             _weapon = new Gun();
  8:         }
  9: 
 10:         public void Kill(string target)
 11:         {
 12:             _weapon.UseWeaponOn(target);
 13:         }
 14:     }

There is still a small problem with the coupling. The gun class is still created inside the butler class. How can we change this? Well, here is the solution:

  1:     public class Butler
  2:     {
  3:         private IWeapon _weapon;
  4: 
  5:         public Butler(IWeapon weapon)
  6:         {
  7:             _weapon = weapon;
  8:         }
  9: 
 10:         public void Kill(string target)
 11:         {
 12:             _weapon.UseWeaponOn(target);
 13:         }
 14:     }

We inject the weapon through the butler's constructor and create the gun object outside the butler class.

  1:     class Program
  2:     {
  3:         static void Main(string[] args)
  4:         {
  5:             IWeapon weapon = new Gun();
  6:             Butler butler = new Butler(weapon);
  7:             butler.Kill("The Colonel");
  8:             Console.ReadKey();
  9:         }
 10:     }

Now we have a butler class that is loose coupled to the gun class. It is now easy for us to create a new weapon when the butler starts killing people again. In every old detective novel there need to be a murder committed using poison. Arsenic, of course. We then need to create a new weapon class:

  1:     public class Poison:IWeapon
  2:     {
  3:         public void UseWeaponOn(string target)
  4:         {
  5:             Console.WriteLine(string.Format("{0} is killed by poisoning.", target));
  6:         }
  7:     }

To convince his victim to drink the poison, the butler needs to persuade the poor person to drink it. We need to create a communication class.

  1:     public class Communicate
  2:     {
  3:         public void Speak(string phrase)
  4:         {
  5:             Console.WriteLine(phrase);
  6:         }
  7:     }

To make this loose coupled, we create a interface for the communication class too.

  1:     public interface ICommunicate
  2:     {
  3:         void Speak(string phrase);
  4:     }

This means that we need to change the butler class to also inject the communication class.

  1:     public class Butler
  2:     {
  3:         private IWeapon _weapon;
  4:         private ICommunicate _communicate;
  5: 
  6:         public Butler(IWeapon weapon, ICommunicate communicate)
  7:         {
  8:             _weapon = weapon;
  9:             _communicate = communicate;
 10:         }
 11: 
 12:         public void Kill(string target)
 13:         {
 14:             _weapon.UseWeaponOn(target);
 15:         }
 16: 
 17:         public void Speak(string phrase)
 18:         {
 19:             _communicate.Speak(phrase);
 20:         }
 21:     }

The butler has found a new victim; the young man.

  1:     class Program
  2:     {
  3:         static void Main(string[] args)
  4:         {
  5:             IWeapon weapon = new Poison();
  6:             ICommunicate communicate = new Communicate();
  7:             Butler butler = new Butler(weapon, communicate);
  8:             butler.Speak("Please drink this, Sir!");
  9:             butler.Kill("The young man");
 10:             Console.ReadKey();
 11:         }
 12:     }

The output we get is this:

image 

After a few days the detective gathers all the people living, and working, in the mansion in the big living room. He then starts to explain who the killer is. The colonel was killed by a mistake. The real target was the young man.  It turns out that the butler is secretly in love with the woman, and wanted to get rid of all men interested in her. He killed the young man because he saw the woman get a bit intimate with him.

If the butler hadn't been stopped, he would continue to kill people that were interested in the woman. He would probably use a different weapon next time. A weapon that maybe didn't require him to speak. Instead of us creating a communication object and input a null value, we can do a Poor man's dependency injection. That means overloading the constructor this way:

  1:         public Butler(IWeapon weapon): this(weapon, new Communicate())
  2:         {}

Doing this, the communication object will be created automatically.

A nice quote that fit into this context is:

"It's OK to figure out murder mysteries, but you shouldn't need to figure out code. You should be able to read it."
- Steve McConnell (Code Complete)

In the next part I will try to explain what IoC containers are.

Tags:

Currently rated 5.0 by 5 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Sep 10 2008

Running partcover in your MSbuild script

Category: C# | Software | Testingfossmo @ 16:53

Ncover is no longer free, and if you want to use code coverage in your build scripts, without paying for it, you need to find another solutions. In my case, this solution is partcover. It works pretty much like Ncover do (did) and you can include it in your MSbuild scripts to cover unit tests. Partcover uses some COM stuff and needs to be registered (you can of course install the msi on every computer you run partcover on and the problem is solved). I prefer that all the tools I use together with my build scripts, work without me installing anything. Adding the target shown below to your MSbuild script will make it possible to use partcover without installing it.

image

What it does is to register the PartCover.CorDriver.dll before partcover is run, and unregister it after partcover is run.

To run this script you need to run under administrator privileges.

Tags:

Currently rated 4.3 by 3 people

  • Currently 4.333333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

May 4 2008

How lambda expressions can replace anonymous methods

Category: C#fossmo @ 23:45

In this blog post I will introduced the syntax of a lambda expression and how it can replace anonymous methods. I will not go into what expression trees are, though it has some very cool features.

So what is a lambda expression?
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

Lambda expression comes from the world of the lambda calculus:
In mathematical logic and computer science, lambda calculus, is a formal system designed to investigate function definition, function application and recursion. (source: Wikipedia)

A lambda operator is used in a lambda expression.
It is written like "=>" and is read as "goes to". It should not be confused with comparison operators such as <= and >=.
The left side of the lambda operator specifies the input parameter and the right side holds the expression of statement block.

Lambda expressions was introduced to the .NET community in .NET 3.5.

Two different lambda expressions
There are two kinds of lambda expressions. A lambda expression with an expression on the right side is called an expression lambda.
The second kind is a statement lambda, which looks similar to an expression lambda except that its right part consists of any number of statements enclosed in curly braces. 

Expression lambda
Expression lambda can be written as follows:

x => x + 1

It is read as "x goes to x plus 1".

Statement lambda
A statement lambda resembles an expression lambda except that the statement is enclosed in braces.

() => { statement };

Example code using statement lambda:

    class Program
    {
        delegate void WriteText();
        static void Main(string[] args)
        {
            WriteText wt = () => { Console.WriteLine("Text inside a statement lambda!"); };
            wt.Invoke();
            Console.ReadKey();
        }
    }


It is also possible to include multiple statements inside a statement block.

Many functional programming languages such as Lisp use lambda notations to define functions. In addition to allowing the expression of LINQ queries,
the introduction of lambda expressions into C# and VB.NET can be seen as a step toward functional languages.

Following are code examples of how you can use lambda expressions:

"The old way"
What this snippet does, is to output the first number bigger than three. It uses a named method called "FindNumberBiggerThanThree" to sort the numbers.

    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
            int result = numbers.Find(FindNumberBiggerThanThree);
            Console.WriteLine(result.ToString());
            Console.ReadKey();
        }
        static bool FindNumberBiggerThanThree(int x)
        {
            return x > 3;
        }
    }


Using Anonymous methods

.NET 2.0 introduced a new construct; anonymous methods.
Instead of declaring a named method in your class and then referencing the method by name you can do this by creating a delegate:

    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
            int result = numbers.Find(delegate(int x) { return x > 3; });
            Console.WriteLine(result.ToString());
            Console.ReadKey();    
        }
    }


The advantage of using anonymous methods, over named methods, is that you can reference local variables in the "outer" method from within the anonymous method.
You don't have to clutter up your class with private methods that are only used once in order to pass some custom code to a method.

Using lambda expressions
The previous example with anonymous methods, is easy to read and understand, but it can be done better:

    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
            int result = numbers.Find(x => x > 3);
            Console.WriteLine(result.ToString());
            Console.ReadKey();
        }
    }


In this example lambda expression is used. Compared to the example using the delegate keyword, lambda expressions simplifies the code a bit.

When to use lambda expressions
Whenever you need to pass some custom code to a method, lambda expressions are very useful.
The easy and readable syntax of lambda expressions also encourages the use of them.

I was introduced to lambda expressions thru mock-you (Moq is cool!) mocking framework and LINQ. I really like the syntax, and call on others to take a better look at what Lambda can do for them.

Tags:

Currently rated 4.0 by 2 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Apr 3 2008

Very good article of how to create loosely coupled applications

Category: C# | Patterns | Thoughtsfossmo @ 14:10

I just read a very good article about how to create a loosely coupled application.
It's written by James Kovacs for MSDN magazine.
It's named "Tame Your Software Dependencies for More Flexible Apps".

tame

Link to the article is found here: http://msdn2.microsoft.com/en-us/magazine/cc337885.aspx

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Apr 1 2008

A problem I had with a new mocking framework.

Category: C# | Testing | Mockingfossmo @ 15:21
It took me some time to figure this out, but I finally got it.
If you in RhinoMocks want to create a mock based on a interface, the syntax is like this:

IMyInterface myObject = mock.CreateMock<IMyInterface>();

myObject is now a mock object.

When using Moq (mock-you) mocking framework, you have to add .Object to the mock to get the object.
This syntax I don't find very intuitive.Below is a example of a test using Moq (without Expectations):

[TestFixture]
public class MyTestClass
{
   [Test]
   public void MyTest()
   {
      var mockedTestInterface = new Mock<IMyInterface >();
      MyClass myTest = new MyClass (mockedTestInterface.Object);
   }
}

I guess it will take a little time to get used to the syntax. But, that said,
I really like this framework.

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Mar 27 2008

Recommended podcast

Category: C# | Podcast | Recommendationsfossmo @ 15:29

I have earlier posted about podcast's I listen to. In that post I forgot to mention an other good podcast. The name of the podcast is Polymorphic podcast by Craig Shoemaker.

Link to the site: http://www.polymorphicpodcast.com

ppodcast

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5