When you read a title like this, everything that makes you a developer should start worrying. Because nServiceBus is build on top of the concept of asynchronous messaging. Normally, it does not support the request/reply communication pattern as you would normally understand this pattern. You are able to send a reply message to the originator, the application that initially sent you the message. But this is inherently asynchronous.
However… With the company I work for, we’re investing a lot of time on messaging. One application needed to call a component that supported this asynchronous messaging. The application itself however is very linear and was very, very hard to interrupt, send a message and have a message handler wait for the result. This really required a Saga and this was too much work at the time. We already had plans for a refactoring where we’d introduce a Saga, but we needed the functionality that called out this other component now. So we created a small piece of code that actually waits for nServiceBus te receive the reply. After this the normal flow of the application can continue.
Again, I really need to clarify that this was a temporary solution and eventually we fixed this by refactoring the code and support a Saga, a long running process that was persisted while waiting for the response.
Here’s the code to do it though
DataResponseMessage response = null;
RequestDataMessage message = new RequestDataMessage() { DataId = g, SomeMessage = "Whatever" };
var synchronousHandle = Bus.Send(message)
.Register(asyncResult =>
{
NServiceBus.CompletionResult completionResult = asyncResult.AsyncState as NServiceBus.CompletionResult;
if (completionResult != null && completionResult.Messages.Length > 0)
{
// Always expecting one IMessage as reply
response = completionResult.Messages[0] as DataResponseMessage;
}
}
, null);
synchronousHandle.AsyncWaitHandle.WaitOne();
Console.WriteLine("Reply : {0}", response.ResponseMessage);
For completeness, I’ll include the message handler from the component the message was sent to. This is normal nServiceBus code.
public class RequestDataMessageHandler : IHandleMessages<RequestDataMessage>
{
public IBus Bus { get; set; }
public void Handle(RequestDataMessage message)
{
var response = Bus.CreateInstance<DataResponseMessage>(m =>
{
m.DataId = message.DataId;
m.ResponseMessage = "I got the message : " + message.SomeMessage;
});
Bus.Reply(response);
}
}
How do I test a method that returns void? For example a method like this.
public void Process(int leadId)
{
decimal price = _calculator.CalculateNormalLead(leadId);
Lead lead = new Lead(leadId, price);
_leadRepository.Save(lead);
}
How to test what the state of the lead object is? This is a question that comes up a lot of the time. It has many different answers. Some options:
- Return a type anyway, even though you don’t use it. Or expose a property with the result. This are design changes that are only neccesary for testing. I’m sure that’s not what we want.
- Check what the method changed, like records in the database. That’s a slow integration test.
-
Split the methods so that one portion of it returns something, and the second method just takes the result and uses it. This way however, you’ll have to make two calls to your class, which I think is even worse than the previous two options!
-
Expose internals by using the InternalsVisibleTo attribute. But now you have to make changes to the design of your class again, making private methods or properties internal.
-
Another option is to accept you can’t test everything. What you can however check is
-
Check if it throws exceptions
-
Check if it changes mutable objects you pass in as parameters
-
Do interaction based testing. Either write mocks or use a mocking framework to verify if calls were made to another method.
This last thing is something we can really use. Now this might not always work, but in our case it’s very usable. Imagine we have a repository that in production kind of works like this.
public class LeadRepository : ILeadRepository
{
public void Save(Lead lead)
{
throw new NotImplementedException("Sorry, this is for an integration test.");
}
}
Now I said kind of, because I don’t want to bother you with a lot of database and query stuff. But our lead enters this class and we’d really like to have this one! This repository implements an interface and the class is injected into the Invoicing class, where our Process method is. For the complete example, check the solution. But for now, check out this FakeRepository I created to use during testing.
public class FakeRepository : ILeadRepository
{
public Lead CreatedLead { get; private set; }
public void Save(Lead lead)
{
CreatedLead = lead;
}
}
The only thing this repository does, is put the lead it receives into a property of the FakeRepository class. Remember that the repository in production does not have this property, so normally it’s never exposed.
Now we can write a test that injects our own fake objects and when asserting, we use the property of our FakeRepository to check the state of our lead.
[TestMethod]
public void Does_MapPropertiesCorrectly_When_CalculatingALead()
{
// Arrange
int leadId = 1;
decimal leadPrice = 0.5m;
FakeRepository fakeRepository = new FakeRepository();
FakeCalculator calculator = new FakeCalculator(leadPrice);
// Act
Invoicing invoicing = new Invoicing(calculator, fakeRepository);
invoicing.Process(leadId);
// Assert
Lead result = fakeRepository.CreatedLead;
Assert.AreEqual(leadId, result.LeadId);
Assert.AreEqual(leadPrice, result.Price);
}
See how easy it sometimes is? Download the complete solution here.
I’ve written about transactions, the TransactionScope in .NET before.
Still I was recently surprised with the comment that I had to use the READPAST in my queries. So I started investigating and felt I had to blog about this. First of all, I’m not going to discuss every option here, just a few basics so you get what the differences are. If you want to know more, check out the BOL/MSDN documentation. Here’s a good starting point.
I’ve created a demo to show locking mechanisms. The database I used was the only one at hand at the time I wrote this, and it’s the Cookbook database from Dennis Doomen his Silverlight Cookbook example. It only has one table and a full select outputs the following result in my case.

Shared Locks
First I want to tell about Shared Locks. Normally when you start a transaction like the code below, you place a shared lock until the transactions is over. A shared lock means someone else is still able to read the data you’ve locked, they just now allowed to update it. Because you want to be sure that the data you read, is still the same at the time you commit a transaction (to update data, for example).
SqlCommand cmd = new SqlCommand();
cmd.Connection = GetConnection();
cmd.CommandText = "select * from Recipes with (readpast)";
var reader = cmd.ExecuteReader();
The GetConnection() method initiates and opens a connection to my database.
ReadCommitted transaction
A regular transaction is done with isolation level ‘ReadCommitted’. This means that you cannot read data that has an exclusive lock on it. This is achieved when you update a row and another transaction tries to read it while you still have your transaction open. Here’s the update code.
TransactionOptions transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted;
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew,transactionOptions))
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "update Recipes set Description = 'ChangedDescription' where Id = 1";
cmd.ExecuteNonQuery();
}
And here’s the code in another transaction that tries to read it.
SqlCommand cmd = new SqlCommand();
cmd.Connection = GetConnection();
cmd.CommandText = "select * from Recipes";
var reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("Description : {0}", reader["Description"].ToString());
}
The second method should not be able to retrieve data from the table until the transactions is closed. The original transaction can place multiple kinds of locks, including a lock that concerns the entire table. The select query I wrote just simply retrieves everything, and as the first row (at least) is locked, it’s not able to retrieve anything. If you add a where clause to filter out just the second row, it should be able to load the data anyway.
NOLOCK hint
So with the NOLOCK / READUNCOMMITTED hint/isolation-level, you tell your transaction (or query) that you want to read dirty data. Even though the transaction hasn’t been committed yet, you still want to read its data. A problem can occur that when the other transaction is rolled back, you’ve loaded data that isn’t there anymore. Worse yet, when SQL Server decides to shift data between different pages, you might simply loose a lot of data because it’s not there!
SqlCommand cmd = new SqlCommand();
cmd.Connection = GetConnection();
cmd.CommandText = "select * from Recipes with (nolock)";
var reader = cmd.ExecuteReader();
The result is that you get the change from the update statement. But because we never commit anything, everything is rolled back and we’ve read a dirty state.
Description : ChangedDescription
Description : Description2
Description : Description3
Description : Description4
READPAST hint
Now with the READPAST hint you’re telling SQL Server you do NOT want to read dirty data. Instead, it skips the rows that are locked.
SqlCommand cmd = new SqlCommand();
cmd.Connection = GetConnection();
cmd.CommandText = "select * from Recipes with (readpast)";
var reader = cmd.ExecuteReader();
Result is first row not being shown at all! So when we change the update query to ‘where Id = 1 or Id = 2’ we get one row less in the other select query.
Description : Description2
Description : Description3
Description : Description4
Conclusion
Be very, very aware of the problems you might introduce when using these table hints!
Download the demo solution here.
There are probably uncountable amount of articles, posts and arguments on to why Unit Testing is so valuable. I just found a nice example that would’ve (or at least should’ve) been caught using Unit Tests. The following code was a bit adjusted to the need of this post, but has a mistake. See if you can spot it.
public class Discount
{
public Discount(decimal percentage, DateTime startDate, DateTime endDate)
{
endDate.Add(new TimeSpan(23,59,59));
Percentage = percentage;
StartDate = startDate;
EndDate = endDate;
}
public decimal Percentage { get; private set; }
public DateTime StartDate { get; private set; }
public DateTime EndDate { get; private set; }
}
If you haven’t spotted it, I’d advise you to write a unit test to show that it’s failing. Here’s mine.
I’ve used FluentAssertions by the way, a library I love that helps me assert my code more easily.
[TestMethod]
public void Does_MapPropertiesCorrectly_When_CreatingNormalDiscount()
{
// Act
Discount discount = new Discount(5, new DateTime(2001, 9, 11), new DateTime(2011, 9, 11));
// Assert
discount.EndDate.Should().Be(new DateTime(2011, 9, 11, 23, 59, 59));
}
What is says is that it’s still 2011/9/11 00:00:00 instead of at the last second of that day. The problem here is that the endDate.Add method adheres to the framework guidelines. That is that you can’t edit an object you get passed by external source, only return new values. So the Add method returns a new DateTime object. We can make the test working with the following adjustment.
public class Discount
{
public Discount(decimal percentage, DateTime startDate, DateTime endDate)
{
endDate = endDate.Add(new TimeSpan(23,59,59));
Percentage = percentage;
StartDate = startDate;
EndDate = endDate;
}
public decimal Percentage { get; private set; }
public DateTime StartDate { get; private set; }
public DateTime EndDate { get; private set; }
}
The only change I made was on line 5.
In July a new update was provided to the Scrum Guide by Jeff Sutherland and Ken Schwaber. There are a few adjustments that are really nice, for example project grooming was added.
One quote from the guide
The Scrum framework consists of Scrum Teams and their associated roles, events, artifacts, and rules. Each component within the framework serves a specific purpose and is essential to
Scrum’s success and usage.
Language was added to emphasize that Scrum is an all or nothing proposition. You either do all the practices, or you’re not doing Scrum. I have to agree on it, after visiting a Scrum training by Jeff Sutherland. Before the training it was my believe that with knowledge from the past and by trial and error the framework was build. Instead due to a lot of studies, whitepapers and other resources it was how the framework was initially introduced at OOPSLA’95. During the two day course, Jeff Sutherland took little over half a day to emphasize this. Also by providing lots of examples on how Scrum succeeded and how we should implement and use Scrum.
I’m a believer and want and will to advocate Scrum wherever I come and to whomever may ask. 
When starting to dig into nServiceBus, you’ll notice almost every single example is executed via the NServiceBus.Host.exe instead of doing it in-process. In my opinion this might be more likely on the receiving side (the subscriber) that just does some stuff in the background. But on the sending side (the publisher) this is mostly triggered by an interactive process, like a website or application where a user triggers the publishing of the message.
My problem was that I had an interactive process triggering the message and the receiving side was a Windows application. So not much use for the nServiceBus host here. Now there’s a lot of documentation and videos on why someone would want to use nServiceBus and how to use its principles. There’s also quite some documentation on different options, but binding them together in a tutorial so you can really get a grasp on what’s happening and why this is happing is something I really missed. And as I like explaining stuff, here’s my version.
Intoduction
In this tutorial we’ll create 3 projects in a single solution.
- One class library (a .dll) that will contain the message.
- One console application for the publisher.
- One console application for a subscriber.
The publisher will send messages without knowing if none, one or multiple subscribers are interested in that message. The pub/sub sample that comes with nServiceBus shows you how you can subscribe via configuration and code and how different subscribers can process a ‘single’ message differently. This is also explained in the two online videos at the official site or download the videos.
Creating the message
The smartest thing you can do, when defining event messages with nServiceBus, is use interfaces, which is explained in the mentioned videos. As an example we’ll create a message for the event when an order is processed. First create a class library named “PubSubTutorialMessages” and add a single class called IOrderProcessed. Remember that this is an interface.
public interface IOrderProcessed : IMessage
{
int OrderId { get; set; }
int CustomerId { get; set; }
}
I like to put in as little information as possible, but that’s a personal preference and also with the thought that you should not put information in messages that can change. Of course if the other system has no knowledge of your original database, it can’t query this information. An idea is to have a webservice provide this information, instead of putting every bit of information in the message. But it always depends and I make decisions on this with every single message I need to send/publish.
Creating the publisher
This is all we need for our first solution. Now we’ll build the publisher. First we need a new project, create a console application this time with the name “Publisher”. Add some references first
- NServiceBus.dll
- NServiceBus.Core.dll
- log4net.dll
- PubSubTutorialMessages (our own project)
Now we’re set up and we’ll start writing code to host nServiceBus ourselves. If you run into problems at the beginning, there are two things you should check.
- Did you add a using statement for NServiceBus?
If not, the extension methods for DefaultBuilder, XmlSerializer, etc. won’t be visible
- Make sure your console application does not use the .NET Framework 4 client profile.
Right-click the project, select properties and check the target framework on the Application tab.
using NServiceBus;
using PubSubTutorialMessages;
IBus bus = NServiceBus.Configure.With()
.DefaultBuilder()
.XmlSerializer()
.MsmqTransport()
.IsTransactional(true)
.UnicastBus()
.MsmqSubscriptionStorage()
.CreateBus()
.Start();
Here you can see how I configured my bus in code. There’s not much to say about this, it’s really basic. Xml serialization, Msmq, Unicast (the only available option), we use MsqmSubscriptionStorage for registering who subscribes to what and we’re telling the IoC to create the bus. Additionally you can add .Log4Net() to enable logging. By default the console window will be filled with debug messages that might help out. Check out the documentation for more info.
This needs some configuration, which we’ll add next in our app.config
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core"/>
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core"/>
<section name="Logging" type="NServiceBus.Config.Logging, NServiceBus.Core" />
</configSections>
<MsmqTransportConfig
InputQueue="PublisherQueue"
ErrorQueue="error"
NumberOfWorkerThreads="1"
MaxRetries="5"/>
<Logging Threshold="WARN" />
</configuration>
The config sections are default .NET behavior. What we see is the MsmqTransportConfig configuration.
- InputQueue is the queue where our publisher will be accepting subscription requests on. Our subscriber will post an initial message here.
- ErrorQueue is simply the queue where errors will appear in. This can be locally or a remote machine.
On the official website you can find more information on msmq settings and on how to handle the error queue.
Now we need to send the message. We’re working with an interface for our messages and we can’t instantiate these. nServiceBus can do this for us however.
var message = bus.CreateInstance<IOrderProcessed>();
message.CustomerId = 10;
message.OrderId = 15;
bus.Publish(message);
This is all you need to do now to publish messages. When you publish them, they’ll disappear into thin air, because no one is listening currently. We need a subscriber for that.
Creating the subscriber
Create another console application called “Subscriber” and add the 4 references to it as with the publisher. After that we have to configure the bus in code first, but this time it needs a one additional line.
IBus bus = NServiceBus.Configure.With()
.Log4Net()
.DefaultBuilder()
.XmlSerializer()
.MsmqTransport()
.IsTransactional(true)
.UnicastBus()
.LoadMessageHandlers()
.MsmqSubscriptionStorage()
.CreateBus()
.Start();
Console.WriteLine("Press any key to quit...");
Console.ReadLine();
You can see I added a call to the LoadMessageHandlers() method. This is because the subscriber must process the messages sent and with this line, nServiceBus will iterate over all assemblies and classes to find out which ones implement the IHandleMessages<T> interface. So what we should do is implement this interface first. On a side, as you can see that I simply wait for a keypress in this demo, as the class the will implement the IHandleMessages<T> interface will handle the messages async.
public class TutorialMessageHander : IHandleMessages<IOrderProcessed>
{
public IBus Bus { get; set; }
public void Handle(IOrderProcessed message)
{
Console.WriteLine(String.Format("Processed order {0} for customer {1}", message.OrderId, message.CustomerId));
}
}
We implement the interface and specify T as IOrderProcessed, because that’s the message the publisher will send. Put the cursor over the IHandleMessages<IOrderProcessed> and press CTRL + . and you’ll get a widget in Visual Studio 2010 with the option to implement the interface, like the image below.

After you did this, you can write the code to handle the message. In my case, I simply write it to the console. The funny thing is, because everything happens asynchronously, you have no idea when this will be outputted. This normally isn’t a problem at all, except for when logging is turned on. Because logging and our own Console.WriteLine will happen asynchronously, our own line will be somewhere inside the nServiceBus messages. You can turn of logging by removing the .Log4Net() line or setting the log level way lower, as you can read in the documentation (bottom of the page).
Now all we need is to configure our subscriber.
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core"/>
<section name="Logging" type="NServiceBus.Config.Logging, NServiceBus.Core" />
</configSections>
<MsmqTransportConfig
InputQueue="SubscriberQueue"
ErrorQueue="error"
NumberOfWorkerThreads="1"
MaxRetries="5"
/>
<Logging Threshold="WARN" />
<UnicastBusConfig>
<MessageEndpointMappings>
<add Messages="PubSubTutorialMessages" Endpoint="PublisherQueue"/>
</MessageEndpointMappings>
</UnicastBusConfig>
</configuration>
Let’s go over this a bit.
- The MsmqTransportConfig is about the same, except for the InputQueue. This states the queue in which we want to receive messages that concern us! So the publisher will put messages it publishes, in this queue, after we subscribed ourselves.
- Logging is turned down and only shows warning messages.
- The UnicastBusConfig configuration has two important options.
- Messages is set to PubSubTutorialMessages.
This tells nServiceBus that all messages in the PubSubTutorialMessages.dll assembly should be routed to this subscriber.
- Endpoint is set to PublisherQueue.
This is the endpoint the publisher is using to listen to new subscriptions.
If the publisher is on ServerA, we should set UnicastBusConfig’s Endpoint to PublisherQueue@ServerA. If you want another subscriber, copy the subscriber project and change the InputQueue. That’s all.
Now you should be able to run the application and have it send messages. Here’s the solution so you can test it out for yourself.
Some time ago now I wrote about doing manual ClickOnce deployment using the command line and FinalBuilder. One of my readers posted a reaction about the following error.
The customHostSpecified attribute is not supported for Windows Forms applications.
I did not have that specific error at the time, and the reader didn’t follow up on my reactions. But now I had the problem myself. Luckily I found the answer pretty fast. I used the old version of mage.exe from the .NET Framework 2.0 SDK. I needed to use the .NET Framework 4.0 SDK mage and my problem was solved. You can find that version right here:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\mage.exe
Some time ago I went to a great presentation, organized by DotNed, held at Vicrea and given by Dennis Vroegop and Thomas Huijer. At some point Dennis Vroegop mentioned that he saw a lot of old Windows Forms developers, create WPF applications like they were still developing Windows Forms applications. What Dennis meant was that these developers were handling click events the same way they did before. At first I thought that he was talking about boring line of business (LOB) applications with just textboxes and buttons in them, without a cool design or something different in user experience (UX). In a series of posts I’ll see if I can lighten up both of our points. So this is not really a one versus the other, but more on showing you how Silverlight can help you create a better user interface and have more powerful databinding.
First I’m going to explain what I meant by creating a normal ListBox with layout that’s extremely hard to accomplish in Windows Forms. We’ll keep it extremely simple. After that I’ll show how you can do this with Master-Detail as well, very easily. And later I’ll show you how to do this with an MVVM implementation.
1. Creating a class and repository
We need some data and we normally get this from a database using webservices. In this example I’ll create a repository class, as I said I’m going to keep it extremely simple. Building webservices via WCF is discussed extensively throughout this weblog elsewhere.
We’ll take on of my favorite subjects, games. Let’s create a class that contains our data.
public class Game
{
public string Name { get; set; }
public int YearOfRelease { get; set; }
public string Developer { get; set; }
public string ImageUrl { get; set; }
}
Now let’s create our repository.
public class Repository
{
public static ObservableCollection<Game> GetAllGames()
{
return new ObservableCollection<Game>()
{
new Game() { Name = "Assassin's Creed : Brotherhood", Developer = "Ubisoft", YearOfRelease = 2010, ImageUrl = @"http://upload.wikimedia.org/wikipedia/en/2/2a/Assassins_Creed_brotherhood_cover.jpg" },
new Game() { Name = "Call of Duty: Modern Warfare 2", Developer = "Infinity Ward", YearOfRelease = 2009, ImageUrl = @"http://upload.wikimedia.org/wikipedia/en/d/db/Modern_Warfare_2_cover.PNG" },
new Game() { Name = "FIFA 11", Developer="Electronic Arts", YearOfRelease = 2010, ImageUrl = @"http://upload.wikimedia.org/wikipedia/en/9/97/Fifa11_keyart_uk-492x600.jpg" },
new Game() { Name = "Quake", Developer = "id Software", YearOfRelease = 1996, ImageUrl = @"http://upload.wikimedia.org/wikipedia/en/4/4c/Quake1cover.jpg" },
new Game() { Name = "Half-Life", Developer = "Valve", YearOfRelease = 1998, ImageUrl = @"http://upload.wikimedia.org/wikipedia/en/f/fa/Half-Life_Cover_Art.jpg" }
};
}
}
I’ve put these two classes inside the Silverlight Application I’ve created. Now that we’ve got our data, let’s first create some layout that can present our games.
<UserControl x:Class="BindingExample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="10">
<ListBox x:Name="gamesListBox" ItemsSource="{Binding}" Width="300" Height="300">
</ListBox>
</StackPanel>
</UserControl>
This is very basic and it doesn’t even show the right results as you can see in the first image below. Let’s change the XAML so that it’ll show the results we’d normally expect.

<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="10">
<ListBox x:Name="gamesListBox" ItemsSource="{Binding}" DisplayMemberPath="Name" Width="300" Height="300">
</ListBox>
</StackPanel>
As you can see, the only thing changed is the added DisplayMemberPath attribute. But we can do this in Windows Forms as well. Let’s do some magic.
<ListBox x:Name="gamesListBox" ItemsSource="{Binding}" Width="300" Height="300">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Grid.Column="1" Margin="3,0,0,0">
<TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Margin="0" Padding="0"/>
<StackPanel Orientation="Horizontal" Margin="3,0,0,0">
<TextBlock Text="Released" Width="80" />
<TextBlock Text=": " />
<TextBlock Text="{Binding Path=YearOfRelease}" Width="50" Margin="0" Padding="0"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="3,0,0,0">
<TextBlock Text="Developer" Width="80" />
<TextBlock Text=": " />
<TextBlock Text="{Binding Path=Developer}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Now this is nice. What’s happening here?
- We removed the DisplayMemberPath attribute, as we are going to very specifically define how we want to see the data.
- We’ve added a DataTemplate, which describes the visual structure of a data object, according to MSDN :-)
- Next we’ve defined some StackPanels and TextBlocks to define where and how to show the data.
We’ve used more than one property from our Game class, some bold text and margins to make it more attractive.
I think this is very user friendly. Imagine a lot of customers in your database, some of them with names very alike or with offices in different locations. Instead of just seeing the name of the customer, you also get presented the location, etc. Now as these are games, there’s probably a little box art available somewhere on the web. Let’s show this as well. Imagine that instead of box art, you present photos of your customers their faces! ;-)
<ListBox x:Name="gamesListBox" ItemsSource="{Binding}" Width="300" Height="300">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Image Source="{Binding Path=ImageUrl}" Width="50" Stretch="UniformToFill" Grid.Column="0" />
<StackPanel Grid.Column="1" Margin="3,0,0,0">
<TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Margin="0" Padding="0"/>
<StackPanel Orientation="Horizontal" Margin="3,0,0,0">
<TextBlock Text="Released" Width="80" />
<TextBlock Text=": " />
<TextBlock Text="{Binding Path=YearOfRelease}" Width="50" Margin="0" Padding="0"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="3,0,0,0">
<TextBlock Text="Developer" Width="80" />
<TextBlock Text=": " />
<TextBlock Text="{Binding Path=Developer}" />
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And this results in a very simple but very nice ListBox with very usable items. And the best part is that you can still use gamesListBox.SelectedItem to get the complete Game object, as you’d expect.
Of course it’s even better to add the DataTemplate to a resource, which will result in the following XAML.
<UserControl.Resources>
<DataTemplate x:Key="gameDataTemplate">
<Grid>
...
</Grid>
</DataTemplate>
</UserControl.Resources>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="10">
<ListBox x:Name="gamesListBox" ItemsSource="{Binding}" Width="300" Height="300"
ItemTemplate="{StaticResource gameDataTemplate}" />
</StackPanel>
I hope this clarifies my point on how you can enhance your boring Line of Business (LOB) application with better usability for your end users.
We have a public website running that we needed to take offline for maintenance. So we created an app_offline.htm file to put on the website. The result is, as we all (should) know, the website goes completely offline immediately. Every webpage and every file cannot be accessed from the web any longer.
The problem with this is that images also aren’t accessible anymore. One option is to place the images you need on another domain and link to those. I don’t like this solution to begin with, but our problem was that our website runs under SSL. You get an https:// url with that, resulting in the fact that if you try to access images from any other domain than the original site, you’ll get warnings in the browser. Something not preferred. End users might think the site isn’t secure or anything.
You have the option however, to embed images into your HTML as Base64 encoded images. This looks like this:
<img src="data:image/gif;base64,R0lGODlC9AIcAAAAAAAAAMwAAZgAAmQAAzA..." />
Of course I kept the Base64 image very short, because they can result in insane long strings. Question however is, how do you get the Base64 encoded string? Here to the rescue, the C# code. :-)
class Program
{
static void Main(string[] args)
{
Image image = Image.FromFile(@"C:\temp\logo.gif");
string result = ImageToBase64(image, ImageFormat.Gif);
Console.WriteLine(result);
}
/// <summary>
/// Images to base64.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="format">The format.</param>
/// <returns></returns>
private static string ImageToBase64(Image image, ImageFormat format)
{
using (var ms = new MemoryStream())
{
image.Save(ms, format);
var imageBytes = ms.ToArray();
var base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
Have fun!
I was just watching Bytes by MSDN where Billy Hollis interviews Ron Jacobs, Sr. Technical Evangelist for the Microsoft Server AppFabric platform. Billy Hollis asked him if it’s a big cliff to start using this awesome power that is AppFabric. Here’s what Ron said:
It’s not a big cliff. It’s similar to what you do now. I would say, the biggest thing is, first of all, you’ve got to get workflow. I know a lot of people look and they are like : “Workflow?” Trust me, it’s great! And once you get your grip on workflow, if you can write apps that work on Windows Workflow, on a local machine, you can throw that thing in the cloud, it will desume.
I have no idea what ‘desume’ is, but I guess it means ‘it will rock’ or something like that! And I agree!
But I don’t really have a clue to why you’d have to throw it in the cloud. I understand that Microsoft is betting big on the cloud and want all their evangelists to push the cloud into our brains. But what Ron Jacobs is talking about isn’t possible in the cloud right now, or at least not with AppFabric. Windows Server AppFabric and Windows Azure AppFabric might be more aligned in the future, but right now they’re definitely not.

I think we’ve got some great new opportunities when using Windows Server AppFabric for hosting our applications. In the past I had some major issues with WF3 while I did not even know the technology that well. My concerns were
- Hosting your workflows
- Monitoring your workflows
- Persisting your workflows
These three have all been solved by AppFabric. But how about that massively scalability that Ron Jacobs is talking about? When I first tried to look up what it took to get a cluster of AppFabric servers up and running, I could not find a lot of information on what to do. Until I discovered I actually did not have to do anything! Just make sure every single server is pointing towards the same database, has the same version of the workflows and you’re done!
So as the title says, it doesn’t take a genius to build a massively scalable system. Doesn’t mean you can brainlessly start building workflows and expect AppFabric to solve it all. You just don’t have to be a genius anymore.
It’s been six weeks since my last blogpost. And although people could’ve kept up with the current situation via my Twitter account, I’ve decided to make one more post on what happened in the previous weeks, since people asked for it in comments and via other channels.
The past weeks have been very, very hard. The fact that my wife could die (which was enough stressful on its own), organizing a lot of help, talking to hundreds of people over the past few weeks, dealing with a lot of kind people offering help but also a lot of idiots, etc, demanded a lot of me. This resulted in that I did not have a single moment for myself to take my mind off of what was happening. My children were also very upset about what happened and tested me way beyond my limits. Which is very understandable, but doesn’t mean it was fun. I found out what it was to have your body and mind running on adrenaline and having the adrenaline run out. But so far about me…
Last Monday it was exactly 6 weeks ago and this Tuesday my wife was formally discharged from the rehabilitation center. She won’t receive any outpatient treatment either. The part of her skull which they removed still has to be put back, but that’s about it. In 4 weeks we’ll have an appointment with the rehabilitation specialist about how things are going and to see if we think we still need some help. How about that?
And to think that the hospital asked me to bring a photo-camera on the Wednesday after it happened; they brought our daughter to her mother and advised me to take pictures of them both. So that when my wife would never wake up again, our daughter would have pictures of herself and her mother for when she was grown up. Believe me, that message wasn’t received well by me. And the pictures aren’t nice either, because my wife was still in induced coma and got mechanical ventilation. Afterwards I heard they gave her a 5% change of ever waking up and some doctors were certain it would never happen at all. They came very close to not operating her at all, because of the prognosis.
Before the first week was over they removed the mechanical ventilation. When I came onto intensive care that they, she immediately spoke to me and asked where I had been. I can tell you, that was about the happiest event ever for me. After that she pushed herself really, really hard to get out of bed and do things herself. Before 4 weeks were over, she had already taken a shower and dressed herself before the nurses came in to help her.
She was on the waiting list to get into Rijndam for (inpatient) rehabilitation, but we asked if she could stay at home while waiting for her rehabilitation. When she got into Rijndam almost everyone asked themselves why she was there, that’s how good she was doing. So after a few days and some observation the rehabilitation specialist asked us if we were okay with the fact that she actually didn’t need any help at all anymore. There’s no physical loss in any way and also cognitive there seems to be nothing wrong.
So now she’s at home and we’re trying to pick up life again where we left it, almost as if nothing has happened. Of course it’s nothing short of a miracle. The neurologist and nurses who are working for dozens of years on neurology haven’t seen anything that comes close to what happened to my wife. They can’t explain how it could’ve happened that she recovered so well, especially with the severity of the two intracranial hemorrhages she had. All I can say is that a lot of people prayed for her and that I’m more certain of it than anything else in life that He has listened. He showed us that miracles still do happen.

Today was most definitely the worst day of my life. I’ve decided to not use my weblog for personal matters, but this is an exception. Partly because I’ve talked on Twitter and MSN with a lot of folks about the pregnancy lately and partly because I need to spill my guts out on what happened. And maybe keep this for personal records so I can look up what happened in the future.
Last week, on Tuesday, my wife was taken to the hospital because of some stuff that doesn’t need to be mentioned here. It was because of high blood pressure. They kept her from Tuesday until Thursday and monitored her occasionally if everything was alright again. The send her home with an appointment for Monday morning to recheck if everything was alright.
This night, from Sunday to Monday, my wife felt a little pressure on her chest. We went to bed and a little later, around 12:00am she woke up because of the pain in her chest. She was really, really worried and told me I had to call the hospital. She had trouble breathing also. The hospital confirmed we should come.
So some time before 01:00am we arrived at the hospital and things started getting worse very rapidly. See hard major pain in the chest, constant pressure and had a hard time breathing. At some point the nurses were away, organizing stuff and I had the idea she fainted repeatedly. So I went to search for a nurse and a few minutes later four nurses gathered around my wife.
They then transported her to the delivery room because they have equipment there to monitor her and the baby. They gave her an intravenous for her high blood pressure. But the pain and breathing problems got worse and worse. They gave her an injection for the pain at around 02:00am for the pain, which seemed to really start kicking in around 02:30am. But instead of just removing the pain, it looked like she was seriously drugged. She spoke everything double (doublespeak) and didn’t respond very well to inquiries from either me nor the nurses.
At around 06:00am or so she had slept for almost the entire time. Occasionally she puked and spoke with doublespeak but almost immediately fell asleep afterwards. But at this time, the heartbeat of the baby started to faint. So the gynecologist was called and he arrived 15 minutes later or so. He felt the baby was asleep because of the drugs (the injection for the pain) and tried to wake it up. The heartbeat rose again, but he decided ten minutes later they’d do a Caesarean section after all.
They prepared her, moved her away to surgery and I had to put on some clothes so I could be with her. When I came in, no communication was possible with my wife at all. The baby was delivered and while I was with the baby, someone came in mentioning they noticed something and would put her to sleep. Also because she might choke in her own vomit if so would throw up again.
I went with the baby to the maternity ward where after a short time, the doctor came in mentioning my wife was put to sleep because she had a Intracranial hemorrhage.
I can tell you, my life came almost to a full stop at that moment.
I was later informed that she had two major intracranial hemorrhages and they needed to transfer her to Erasmus MC, a specialized hospital in Rotterdam. Multiple doctors went with the ambulance and the ambulance itself got police support to get there as quick as possible.
I’m now at home, ready to see my other three children who are at my brother-in-law. I went to Erasmus MC myself to check on my wife. She was in a three hour surgery where they removed a part of her skull and fixed one intracranial hemorrhage. The other was too deep into her brain to reach. The operation was successful, if you can call it that.
I’m going to the hospital tomorrow to check on my wife. She’s kept asleep right now with medication. They’ll stop the medication tomorrow and then we’ll have to wait and see if she’ll ever gain consciousness again. And if she does, in what state that will be.
Still in the first hospital is my new born daughter Marith, who might never know her mother. I’m seriously constantly praying if she will be alright, as He is the only one who can help her now.
This topic is covered in multiple posts
The previous post was the most simple example of creating a WCF service and calling it from a client application. In this post you can read how you can achieve the exact same behavior, but now manually adding every bit of configuration. So we’ll basically override the default endpoints, configure our won, resulting in exactly the same behavior.
The idea behind this is that you understand what WCF does and that you can do it yourself. Besides that, the previous .NET Framework versions don’t support the default endpoints, meaning that the solution at the end of this article also works in Visual Studio 2008.
What will we do?
- Add BasicHttpBinding endpoint
- Add MEX endpoint
- Add Metadata behavior
Metadata behavior
We’ll start with bullet three, simply because almost everything is already in place. The solution from the previous weblog post ended with this in the application configuration from the ConsoleHost application.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
The service behavior has no name, making it the default for all services in WCF4. All we have to do is give it a name. Change line 6 into the following.
<behavior name="MyBehavior">
Adding BasicHttpBinding endpoint
We’ll now add the first endpoint using the BasicHttpBinding. Right under <system.serviceModel> we’ll add the <services /> tag and add our service. Completely empty this will result in the following.
<services>
<service name="">
<endpoint
address=""
binding=""
contract="" />
</service>
</services>
Now we have to fill in the blanks. More information can be found in the articles about the WCF ABC and hosting the service.
- Name
This is a bit misleading, as you can’t just enter any name, it’s actually the type of the service.
This must be the fully qualified name of the implementation of our service. This means not the interface, but the class. Its name is EmailValidator but its full name includes the namespace, resulting in EmailService.EmailValidator.
- Address
The address we don’t have to fill in, because the base address in our code already defines it. You can also define this in configuration as you can read in the post Address.
- Binding
The binding is simply basicHttpBinding. Note the camelCasing.
- Contract
Here we should enter the contract, which is our interface. As with the name attribute, we need to enter the fully qualified name, resulting in EmailService.IEmailValidator.
You can view the end result at the end of this article and in the download, also at the end of this article.
Adding MEX endpoint
The MEX endpoint needs the metadata behavior configured, but we’ll get back to that. First we need to add the endpoint. Again the WCF ABC, an address, binding and contract.
- Address
Because we cannot have this endpoint at the same address as the BasicHttpBinding endpoint, we need to enter “mex” here.
- Binding
This is simple, it’s just mexHttpBinding
- Contract
This is simple as well, although a bit weird, it HAS to be IMetadataExchange. Not the fully qualified name or anything, it has to be just this.
Enabling the metadata behavior
Now all we have to do is add the metadata behavior. This is done at the root of the service, where we first entered the name. There’s another attribute there called behaviorConfiguration. We have to enter the name of our behavior configuration there, which is MyBehavior.
End result
This results in the following configuration.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="EmailService.EmailValidator" behaviorConfiguration="MyBehavior">
<endpoint
address=""
binding="basicHttpBinding"
contract="EmailService.IEmailValidator" />
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyBehavior">
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
You can download the Visual Studio 2010 and the Visual Studio 2008 solution right here.
This topic is covered in multiple posts
It’s been a long, long time since I wrote the original WCF Simple Example post. It was even before Visual Studio 2008 and since then, a lot of things changed. As still a lot of folks place comments and questions to that post, let’s have a look at what we currently have to do to get a service up and running and consume it in a client.
This time we’ll start with a class library assembly (a .dll) and we’ll host the service inside a console application. The client will use a Windows Forms application again. Although we do everything in Visual Studio 2010, most will be usable in VS2008. I will mention it when it isn’t and provide an alternative. I’ll be a bit more descriptive about what we have to do, so this post is a little longer than the original.
Create Project
First create a new "class library", this will become the implementation of our service. Choose New Project and select the Class Library as project template. At the bottom, set as name for the project “EmailService” and the solution name “WCFSimpleExample2010”. If you can’t set the solution name, check the Create directory for solution box.
Create the contract
We’ll first create the contract with only one method; or operation as they are called in WCF. The "class library" should have added a class called "Class1", you should rename it to IEmailValidator.cs and make it an interface with the same name.
Now add a single method signature called ValidateAddress that takes one string argument called emailAddress and returns a boolean. This is a normal interface, nothing fancy and the end result is as follows:
public interface IEmailValidator
{
bool ValidateAddress(string emailAddress);
}
Now we need to tell WCF that this is our contract. We do that by adding attributes, but first we need to add a reference to System.ServiceModel. Right-click the project and select Add reference and select System.ServiceModel from the list. I’m using the Visual Studio 2010 Pro Power Tools so my screen might look different from yours, but the idea is the same.
Now you can add the attributes to your interface. On top of the interface place the ServiceContract attribute and on the operation place the OperationContract attribute. Add the using System.ServiceModel at the top of your codefile, or let Visual Studio do it for you by having your cursor in on of the attribute names. When you typed it in correctly and case sensitive, you can press CTRL + . and a context menu should appear to let you add the using automatically. Your interface should finally look like this:*
[ServiceContract]
public interface IEmailValidator
{
[OperationContract]
bool ValidateAddress(string emailAddress);
}
Create the service implementation
Now that we’ve created the contract we need to write code for the service to actually do what we want it to do. Create a new class and make it implement the interface. After that, use a regular expression to verify the email address and return true value if it’s correct. You should have something like the following code, or make up your own. :-)
public class EmailValidator : IEmailValidator
{
public bool ValidateAddress(string emailAddress)
{
Console.WriteLine("Validating: {0}", emailAddress);
string pattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$";
return Regex.IsMatch(emailAddress, pattern);
}
}
Now you have the two most important classes for your service. You don’t actually have to use an interface, but it’s a best practice. That way you can inherit multiple interfaces for or do versioning with different interfaces.
Creating the host
As said, for our host we’ll initially use a console application. Choose to add a new project and now have a Console Application as project template. Name it “ConsoleHost”.
Add the reference to System.ServiceModel again and also to your EmailService project. In your Main method, create a ServiceHost object and give it the correct arguments in the constructor, as shown below.
Type serviceType = typeof(EmailValidator);
Uri serviceUri = new Uri("http://localhost:8080/");
ServiceHost host = new ServiceHost(serviceType, serviceUri);
host.Open();
On line 4 is the creation of the ServiceHost object. As first argument it receives the implementation of our service as a type. And a base address as second argument. Read more about base addresses here and more about hosting here. The type is defined on line 1 and the base address on line 2. Finally on line 5 our host is started.
WCF4 : Default endpoints
Now here’s a difference in .NET Framework 4.0 because this is not possible in previous version of .NET. Currently the default endpoints are used, which is a new feature to make configuration of your services less of a hassle. I like to explicitly define everything in detail so everyone knows what happens. But for our example, this works quite well. If you’re not using .NET 4.0 you might want to continue to part 2 of this weblog post, which will be posted later.
You could add the default endpoints yourself by adding host.AddDefaultEndpoints(); to the code, right before the host.Open(); statement.
How can we see what endpoints are configured by default? I have a little script from way back that displays everything currently running. I won’t go into details, just paste the following after the host.Open(); part.
#region Output dispatchers listening
foreach (Uri uri in host.BaseAddresses)
{
Console.WriteLine("\t{0}", uri.ToString());
}
Console.WriteLine();
Console.WriteLine("Number of dispatchers listening : {0}", host.ChannelDispatchers.Count);
foreach (System.ServiceModel.Dispatcher.ChannelDispatcher dispatcher in host.ChannelDispatchers)
{
Console.WriteLine("\t{0}, {1}", dispatcher.Listener.Uri.ToString(), dispatcher.BindingName);
}
Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate Host");
Console.ReadLine();
#endregion
Now you should be able to see the endpoints like in the first following screenshot. You can use a browser like Internet Explorer to go to the service uri and look at the default MEX endpoint.
As you can see it’ll tell you that a MEX endpoint (aka metadata) isn’t configured yet. Now an easy way would be to do this via the new default endpoints. My first impression was that this would work.
Type serviceType = typeof(EmailValidator);
Uri serviceUri = new Uri("http://localhost:8080/");
ServiceHost host = new ServiceHost(serviceType, serviceUri);
host.AddDefaultEndpoints();
// This actually doesn't just simply work.
host.AddServiceEndpoint(new ServiceMetadataEndpoint());
On line 5 you can see that we add the default endpoints and line 7 adds the ServiceMetadataEndpoint, or the MEX endpoint. Unfortunately it cannot add the Metadata behavior itself, so you still have to do this yourself. The other way it to specify in configuration that you want metadata enabled. Also new in WCF4 is that you can inherit configuration. You can specify in either the machine.config or in your local configuration what should be enabled by default for WCF services. I recommend you don’t do this in machine.config, but that’s just my opinion. Here’s how I enabled it in my project configuration, the app.config of our console host. Remember that in the follow up post to this, we’ll do this the old fashioned way, which will work in Visual Studio 2008 and has my preference.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
As you can see, I have not specified a name for the behavior so in WCF4 this means it’ll be used by all services. This also means that every service needs a base address for http endpoints.
For reference, here’s the code for our console host:
static void Main(string[] args)
{
Type serviceType = typeof(EmailValidator);
Uri serviceUri = new Uri("http://localhost:8080/");
ServiceHost host = new ServiceHost(serviceType, serviceUri);
host.Open();
#region Output dispatchers listening
foreach (Uri uri in host.BaseAddresses)
{
Console.WriteLine("\t{0}", uri.ToString());
}
Console.WriteLine();
Console.WriteLine("Number of dispatchers listening : {0}", host.ChannelDispatchers.Count);
foreach (System.ServiceModel.Dispatcher.ChannelDispatcher dispatcher in host.ChannelDispatchers)
{
Console.WriteLine("\t{0}, {1}", dispatcher.Listener.Uri.ToString(), dispatcher.BindingName);
}
Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate Host");
Console.ReadLine();
#endregion
}
Accessing the metadata
Because we now have enabled our service and our metadata endpoint, the MEX endpoint, we can view it through Internet Explorer or another browser. Execute the console host (it has to be alive or the endpoints won’t be accessible) and browse to the URI of your service : http://localhost:8080/
If this shows a nice screen with a link to the WSDL you’re very likely done with the service.
Create client application
We’ll now add another project that will consume the service and will be able to verify if entered email addresses are valid, or at least according to our regular expression.
Add a new console application like before and this time call it ConsoleClient. Make sure your service (the host) is running, but don’t have it running in debug mode. Easiest way is to set the ConsoleHost project as startup project en press CTRL + F5 to run it without debugging turned on.
We now need a proxy class that sits between our client and service. There are two ways to create a proxy for our service. I have a preference for doing it manually, so you know what exactly is happening. I’ll show that first.
Manually create proxy
First start up a Visual Studio 2010 (or Visual Studio 2008) Command Prompt and move to the location of the ConsoleClient. Because it’s a Visual Studio command prompt you should have access to the proxy generator svcutil.exe. Input the following commandline
svcutil http://localhost:8080/ /o:ServiceProxy.cs /config:App.Config /n:*,ConsoleClient
This should generated two files, the service proxy and an application configuration file. Go back to Visual Studio and in your ConsoleClient application make all files visible through the icon at the top of the Solution Explorer, as seen in the right screenshot. The App.Config and ServiceProxy.cs should become available and you can include these.
Update : The console window screenshot shows ConsoleHost as namespace, this is incorrect and should be ConsoleClient as the full commandline statement above states.
When we ran svcutil.exe the first argument was the location of our service as specified in the host. This is the base address. The second argument is what the tool should output, our proxy. The third argument is that we also want it to update our application configuration and if it’s not available, create it. The last argument is the namespace our proxy should be placed in (or should have), which should now be the same as our application itself.
Call the service
Now we can finally start consuming the service. When you go to your Main method in your Program class again, you can access the proxy class, which is the name of your service with Client suffixed. So ours is EmailValidatorClient.
EmailValidatorClient svc = new EmailValidatorClient();
bool result = svc.ValidateAddress("dennis@bloggingabout.net");
In line 1 you can see the proxy being initialized. Does doesn’t mean the connection is set up, this is done on first call. Line 2 shows the calling of the service and getting the result back.
This is our entire method Main which will continue to ask for email addresses until you enter none.
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Enter an email address or press [ENTER] to quit...");
string emailAddress = Console.ReadLine();
if (string.IsNullOrEmpty(emailAddress))
return;
EmailValidatorClient svc = new EmailValidatorClient();
bool result = svc.ValidateAddress(emailAddress);
Console.WriteLine("Email address is valid : {0}", result);
}
}
Creating proxy through Visual Studio, the easy way.
Instead of creating the service proxy manually, via svcutil.exe, you can also let Visual Studio create it for you. Just right-click the project and select ‘Add Service Reference...’ You’ll get a dialog window where you enter the address of your service and the namespace.

Now we entered ConsoleClient as namespace, but it concatenates this to the already existing namespace. So now you can access the EmailValidatorClient via ConsoleClient.ConsoleClient.EmailValidatorClient. One of the reasons I don’t like to use this automatically generated proxy class. You should now not forget to add a using statement to this namespace at the top of your class. Probably a better solution is to set the namespace to Proxies or something, in the dialog, so the complete namespace makes more sense.
Run the client
While the service is still running (of not, restart it) you can right-click your ConsoleClient and select Debug and Start new instance and you’re done.
What next?
Next we’ll extend this blogpost with at least two more, step-by-step blogposts explaining how to manually add endpoints and how to host your service in IIS. You can read more about it here.
Download
Here's the download for VIsual Studio 2010. In the follow up article a Visual Studio 2008 solution is available.
For those using Windows Workflow Foundation 4 (WF4) this might be a very interesting tool. I was messing a bit with creating a Tracking Profile for my WF4 workflows, but wasn’t succeeding very much. Until the Workflow Tracking Profile Editor was mentioned on the AppFabric forums.
This tool makes it dead easy to create a tracking profile. It allows you to load up a WF4 XAMLX file. It then shows the editor and you’re allowed to browse through all (composite) activities. After right-clicking an activity (with a blue circle on it) you can specify what you exactly want to track. It even knows everything about arguments and (scoped) variables so you can use checkboxes to turn them on or off.
This way you can track what arguments go in, come out, what the value of variables was before and after you executed the activity. Very handy and probably a lot of work if you had to enter all the details by hand.
Download the tool here.
More Posts
Next page »