- Posted by Peter Himschoot on August 9, 2010
Duik erin met MSDN.
Microsoft Belgie heeft een aantal zelf-trainingen staan om je up-to-speed te krijgen met:
- Silverlight 4
- Visual Studio 2010
- Windows Phone 7
- Windows Azure
De laatste komt binnenkort online.
- Posted by Peter Himschoot on July 11, 2010
Visual Studio 2010 now comes packed with too many assemblies. The list of assemblies to pick from in the Add Reference dialog is now a little too large for my taste. Today, while browsing around in the Visual Studio 2010 Extension Manager, I found the Search References extension:
After installing it my Add Reference dialog now looks like this:
And typing in the search box instantly filters the list of assemblies. Nice. Microsoft should have provided this out of the box! It is also a nice sample of how extensible Visual Studio is.
- Posted by Peter Himschoot on June 14, 2010
INotifyPropertyChanged is an interface which is very important to do proper databinding and is heavily used in the MVVM pattern.
However, to implement it you have to raise the PropertyChanged event whenever a data-bound property changes value, and you have to pass the name of the property to it. This results in string based programming and this generally is not good for maintenance. Some people create a RaisePropertyChanged method in the base class and then invoke this method in each property setter. Again this is not ideal because you cannot always derive from this base class, especially if you already have a base class. In this post I want to show you an alternative way of implementing INotifyPropertyChanged that doesn’t require a base class (you simple implement the INotifyPropertyChanged on each class) with a nice, string-less way of raising the PropertyChanged event. For example, look at this class:
1: public class Customer : INotifyPropertyChanged
2: {
3: private string firstName;
4:
5: public string FirstName
6: {
7: get { return firstName; }
8: set
9: {
10: if (!object.Equals(value, firstName))
11: {
12: firstName = value;
13: PropertyChanged.Raise(this, o => o.FirstName);
14: }
15: }
16: }
17: }
As you can see, the PropertyChanged.Raise does all the work, and you pass in the sender and the property using a Lambda expression. Simple and no strings. To make things even simpler, I use a code snippet that implements the property directly for me:
1: <?xml version="1.0" encoding="utf-8" ?>
2: <CodeSnippet Format="1.0.0"
3: xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
4: <Header>
5: <Title>NPC</Title>
6: <Author>Peter</Author>
7: <Shortcut>npc</Shortcut>
8: <Description>NotifyPropertyChangedProperty</Description>
9: <SnippetTypes>
10: <SnippetType>SurroundsWith</SnippetType>
11: <SnippetType>Expansion</SnippetType>
12: </SnippetTypes>
13: </Header>
14: <Snippet>
15: <Declarations>
16: <Literal>
17: <ID>type</ID>
18: <Default>int</Default>
19: </Literal>
20: <Literal>
21: <ID>field</ID>
22: <Default>prop</Default>
23: </Literal>
24: <Literal>
25: <ID>name</ID>
26: <Default>Prop</Default>
27: </Literal>
28: </Declarations>
29: <Code Language="CSharp">
30: <![CDATA[
31: [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
32: private $type$ $field$;
33:
34: public $type$ $name$ {
35: get { return $field$; }
36: set {
37: if( ! object.Equals( value, $field$ ) )
38: {
39: $field$ = value;
40: PropertyChanged.Raise( this, o => o.$name$ );
41: }
42: }
43: }
44: ]]>
45: </Code>
46: </Snippet>
47: </CodeSnippet>
So how does it work? Here is the definition of the Raise Extension method:
1: public static void Raise<T, P>(
2: this PropertyChangedEventHandler pc
3: , T source
4: , Expression<Func<T, P>> pe)
5: {
6: if (pc != null)
7: {
8: pc.Invoke(source,
9: new PropertyChangedEventArgs(((MemberExpression)pe.Body).Member.Name));
10: }
11: }
This extension method has three arguments, the first two should be clear. The last is a LINQ expression.
When you invoke it the compiler converts this into a tree of objects, which represents the lambda expression o => o.FirstName, and passes it as an argument. This tree of objects is then traversed to find the MemberExpression which contains the name of the property. So the overhead is the creation and traversal of this small tree of objects. So it is a little less fast then passing a string, but the code is compile-time safe and supported by Visual Studio refactoring. This technique is generally known as static reflection.
- Posted by Peter Himschoot on June 9, 2010
Today, at 18h30, my father-in-law Gaston Dhaese passed away after a 9 year battle against cancer.
I’ve been told he didn’t suffer any pain, and I am glad he could die in piece with his loving family close by.
Dear father, you have always been good and fair to me, my wife Isabelle and our children Liesbeth, Wouter and Edward. Words fall short to express my gratitude for all you’ve done…
You will never be forgotten. Don’t worry, we’ll take care of mother Lieve and daughter Siegrid.
- Posted by Peter Himschoot on May 11, 2010
This week I got a question whether it is still possible to keep some file checked-out during a check-in. This is something you can do with Source Safe for example. To be honest I had no idea if this is possible, so I decided to have a look. So the answer is yes (although in general I think this is dangerous because this way people tend to check out files for long periods…).
Simply go to options and check the fourth check-box from the top.

- Posted by Peter Himschoot on May 3, 2010
Sorry, just lo-ove this dilbert cartoon!
- Posted by Peter Himschoot on April 15, 2010
Great read: http://www.slate.com/id/2250993/
If Microsoft ever wanted to do something like this … what would happen do you think? How is it Apple can?
- Posted by Peter Himschoot on April 9, 2010
I’m currently experimenting with Pex, Moles and Code Contracts, and I wondered what effect code contracts have on Pex tests. So I build this simple piece of code:
1: public class Demo
2: {
3: public int Foo(int a, int b)
4: {
5: if (a < 0)
6: return a;
7: else if (a > 0)
8: return b;
9: else
10: return a + b;
11: }
12: }
Then I make Pex generate its Parameterized Unit Tests (PUTs). This generates the following test:
1: [PexClass(typeof(Demo))]
2: [PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
3: [PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
4: [TestClass]
5: public partial class DemoTests
6: {
7: /// <summary>Test stub for Foo(Int32, Int32)</summary>
8: [PexMethod]
9: public int Foo(
10: [PexAssumeUnderTest]Demo target,
11: int a,
12: int b
13: )
14: {
15: int result = target.Foo(a, b);
16: return result;
17: // TODO: add assertions to method DemoTests.Foo(Demo, Int32, Int32)
18: }
19: }
I just leave the code, right-click on The Foo method of the DemoTests class, choose “Run Pex explorations” and I get this:
As you can see the exploration calls my code with negative, zero and positive values. What happens when I add a contract stating that a should be positive?
1: public class Demo
2: {
3: public int Foo(int a, int b)
4: {
5: Contract.Requires(a > 0);
6: if (a < 0)
7: return a;
8: else if (a > 0)
9: return b;
10: else
11: return a + b;
12: }
13: }
Only line 5 was added, but if I run the pex explorations again I get:
The effect is that Pex now doesn’t explore negative numbers, because it can deduce from the contract not to even try.
What if I use a contract to state that b should be negative?
1: Contract.Requires(b < 0);
Again Pex sees this and explores my code with negative b:
One more. When I change my code to do a little more with b, like this:
1: public int Foo(int a, int b)
2: {
3: Contract.Requires(a > 0);
4: Contract.Requires(b < 0 || b > 10);
5: if (a < 0)
6: return a;
7: else if (a > 0)
8: {
9: if (b > a)
10: return a;
11: else
12: return b;
13: }
14: else
15: return a + b;
16: }
and when I run the explorations again:
So, you can guide Pex by supplying contracts on the arguments of your methods.
- Posted by Peter Himschoot on April 8, 2010
Co and contra-variance were introduced to VB.NET and C# to make working with certain classes more natural (“because it should work”). But beware, I was experimenting a bit with this and found following possible breaking change. I started with these two classes:
C#
1: public class Person
2: {
3: // ...
4: }
5:
6: public class Vip : Person
7: {
8: // ...
9: }
VB.NET
1: Public Class Person
2: '
3: End Class
4:
5: Public Class Vip
6: Inherits Person
7: '
8: End Class
Then I added a collection of people:
C#
1: public class PersonList
2: {
3: public void Add(object obj) {
4: // ...
5: }
6:
7: public void Add(Person p)
8: {
9: // ...
10: }
11:
12: public void Add(IEnumerable<Person> people)
13: {
14: foreach (Person p in people)
15: {
16: // ...
17: }
18: }
19: }
VB.NET
1: Public Class PersonList
2: Public Sub Add(ByVal obj As Object)
3: '
4: End Sub
5:
6: Public Sub Add(ByVal person As Person)
7: '
8: End Sub
9:
10: Public Sub Add(ByVal list As IEnumerable(Of Person))
11: '
12: End Sub
13: End Class
Next I create a PersonList collection and then add a list of Vip’s:
C#
1: class Program
2: {
3: static void Main(string[] args)
4: {
5: PersonList people = new PersonList();
6:
7: List<Vip> others = new List<Vip> {
8: new Vip(), new Vip()
9: };
10:
11: people.Add(others);
12: }
13: }
VB.NET
1: Sub Main()
2: Dim people As New PersonList
3: Dim others As New List(Of Vip)(New Vip() {New Vip(), New Vip()})
4: people.Add(others)
5: End Sub
When I compile this in Visual Studio 2008 the first Add method, taking the object argument, gets called.
But with Visual Studio 2010 (using the .NET 4 target) the third Add method gets called. This is because now IEnumerable<T> is co-variant and will now convert the List<Vip> to an IEnumerable<Person>.
Ok, granted. This is NOT something you will see every day, but if you ever encounter it, this might be very confusing.
This kind of problem can also occur with extension methods and user-defined conversions…
- Posted by Peter Himschoot on March 29, 2010
This blog post accompanies my session on Workflow Foundation 4 programming during the Belgian Tech Days (actually developers and IT-pro days :)). During this session I built a WCF service using Workflow Foundation 4, and I want to show you how to do this on your own…
In the first part you’ll learn how to create a simple FlowChart workflow and test it, and then in the second part you’ll learn how to setup correlation so multiple players can play the game…
Preparing the lab
This lab starts with a new project, so start Visual Studio 2010 and create a new workflow service project (call it NumberGuessingGame):
This creates a new solution with a workflow project.
Remove Service1.xamlx, we’re going to add a new service with a better name.
Right-click the project and add a new item. Select the WCF Workflow Service template and name it GuessIt.xamlx.
Creating the initial FlowChart
This adds a workflow service with a sequential activity containing a Receive and Send activity. Delete the sequential activity leaving the workflow empty. Open the toolbox and drag a FlowChart activity onto the workflow designer. This should look like this now:
Next drag a Receive activity onto the designer, below Start. Name it Start A New Game. Select the receive activity and enter following the OperationName, ServiceContractName and CanCreateInstance properties in the properties window:
Next right-click on the receive activity and select the Create SendReply option from the drop-down menu. This add a Send activity to the workflow. The Send is coupled to the receive activity through its Request property:
Now connect the activities:
Adding variables
Now, in the workflow designer open the variables window and add a new variable called player of type String. This will hold the player name received through the “Start A New Game” Receive activity. You will also see a variable of type CorrelationHandle. This is used to connect several receive and send activities through correlation. Rename this to gameHandle.We’ll use this handle later to setup content-based correlation.
Now add two new variables theNumber and guess, both of type Int32. The first is the number the user needs to guess, to you need to initialize it to a random number between 0 and 100. Use the Random type to do this:
Go back to the first receive activity. Click on the content property. This opens the Content Definition window. Select the player as the message data (and set the Message type to String):
Do the same for the send activity, but now use following expression (of type String):
1: player + " guess the number between 0 and 100"
You might also get validation errors because you renamed the correlation handle to gameHandle. Change the CorrelationInitilizers property to use gameHandle (click on the … button).
Testing the service
Press F5 in Visual Studio. The WCF Test Client will start and automatically fetch meta-data from the service. Double click the Begin method. This opens a new tab allowing you to invoke the Begin operation on the service. Enter your name and click Invoke. In the bottom area you should see the result of invoking the begin method.
This concludes the first step.
Adding the data contracts
Let’s add a couple of data contracts to the project, one for a game and another for a guess. Note that both contain the player name, this way our service will be able to distinguish between multiple games, as long as each player uses a unique player name:
1: [DataContract]
2:
3: public class Game
4:
5: {
6:
7: [DataMember]
8:
9: public string PlayerName { get; set; }
10:
11: [DataMember]
12:
13: public string Message { get; set; }
14:
15: }
16:
17: [DataContract]
18:
19: public class Guess
20:
21: {
22:
23: [DataMember(IsRequired = true)]
24:
25: public string PlayerName { get; set; }
26:
27: [DataMember(IsRequired = true)]
28:
29: public int Try { get; set; }
30:
31: }
Make the “Send Game Started” send activity use a Game instance as the result. To do this you will need to add another variable of type Game, and initialize it to a new instance:
Now add to assign activities after the Begin receive activity, and assign appropriate values to the game:
Adding the guessing logic
Add another variable, calling it guess of type Guess. Then add another receive activity after the send activity, but now with an operation name called Guess, taking guess variable as its content. Check if the guess was right using a decision shape. If so, congratulate the user. If not, decide whether the guess was too small or large. Confirm this back to the user using three SendReply activities (create each one by right-clicking the Guess receive activity and select Create SendReply).
Here is an example of the result:
Adding Content-based Correlation
Of course we want to make a single player play the same game, but what if multiple players are playing on the same server? We need correlation. In this part we’re going to correlate the guess activity to the Begin activity using the player’s name. That is why our data contract both contain the player’s name (by coincidence the properties have the same name, but this is not required).
To do correlation we need a correlation handle. This handle will act like a key to a workflow. If a request comes in, we’re going to find this key through part of the message, in our case the player’s name. So, if you haven’t done so, add a new variable to the workflow called gameHandle of type CorrelationHandle. The make sure that all the first sendReply activity is set to initialize this handle by ensuring the CorrelationInitializer is set like this:
When the workflow sends this message, we’re saying that the key of the gameHandle is the player’s name. So when another message arrives, the workflow runtime can then see is the message contains a valid key (again the player’s name), use this key to find the right workflow instance, and then send the message to it. So next step is to set the Guess receive activity’s Correlates On like this:
Now you should be able to play a game, making sure that the first and following messages all have the same player name. You can also start two or more games, each with their own player name!