Creating a WCF duplex service

Note: The demo project is downloadable here.

!You may need to start the bank service with admin rights to run the demo!

Knowing how to create a duplex service allows your WCF service to send messages to its clients. This way, instead of calling service methods returning a result and blocking the client thread, you can make a “fire and forget” one way call and let the service call back the client when it’s finished. Even more, you can call back other clients, too! For example, a bank manages several accounts using a bank service. The bank accounts act as clients and can transfer money to other accounts. Now the bank service needs to inform both concerned account clients about their new balance after the money transfer is done. Account clients not related by the money transfer shall be ignored.

Our demo application is doing exactly this. Have a look at this screenshot:

Bank server workflow

On the left, we see a WPF application hosting the bank service. On the right we see three bank account clients. They communicate with the bank service using an AccountService implemented by the bank service. This enables the account clients to 1) create an account and to 2) transfer money to another account client. After the money transfer on the bank service is finished, the bank service informs each concernced account client about its updated balance. In this example, an amount of 5 units is transfered from account client 1 to account client 3. Account client 2 exists but does not receive a callback message, because it is not concerned by the money transfer.

To enable the bank service to call back an account client, the account client it-self needs to host a service being called by the bank service. This allows a duplex call.

A duplex call is created by linking the call back service to the main service in the main service declaration this way:

namespace BankServices.ServiceInterfaces
{

    [ServiceContract(SessionMode=SessionMode.Required, CallbackContract=typeof(IAccountServiceCallback))]
    public interface IAccountService
    {
        [OperationContract(IsOneWay = false)]
        Account AddAccount(int accountNumber);

        [OperationContract(IsOneWay = true)]
        void TransferMoney(int debitAccountumber, int creditAccountNumber, double amount);

    }
}

It is important to set the “IsOneWay”-attribute to true for the service method making use of the callback service.

The IAccountServiceCallback looks like this:

namespace BankServices.ServiceInterfaces
{
    public interface IAccountServiceCallback
    {
        [OperationContract(IsOneWay = true)]
        void UpdateBalance(double newBalance);
    }
}

Additionally, to enable the banking service to call back the account client, the banking service needs to grab the callback channel of the account client. This is done during a call from the account client. In this demo, I grab the callback channel when the account client calls the AddAccount-method of the AccountService:

/// <summary>
/// Adds new account and registers the callback for the new account
/// </summary>
public Account AddAccount(int accountNumber)
{
	if (Bank.Accounts.Any((a) => a.Number.Equals(accountNumber)))
	{
		throw new FaultException("Account number " + accountNumber + " already exists!");
	}

	if (Bank.AccountServiceCallbacks.Any((kvp) => kvp.Key.Equals(accountNumber)))
	{
		throw new FaultException("Callback for account number " + accountNumber + " is already registered!");
	}

	Account newAccount = new Account() { Number = accountNumber };
	Bank.Accounts.Add(newAccount);

	try
	{
		IAccountServiceCallback accountServiceCallback
			= OperationContext.Current.GetCallbackChannel<IAccountServiceCallback>();

		Bank.AccountServiceCallbacks.Add(accountNumber, accountServiceCallback);
	}
	catch (Exception ex)
	{
		Bank.Accounts.Remove(newAccount);
		throw ex; //ToDo: Errorhandling if adding new account fails
	}

	return newAccount;
}

The grabbing of the callback channel takes place between the try-catch. Because many account clients communicate with the bank, we need to relate each channel to its account. This is done by adding the channel and its account number to this dictionary:

/// <summary>
/// Dictionary of accountnumber and callback
/// </summary>
public static Dictionary<int,IAccountServiceCallback> AccountServiceCallbacks { get; private set; }

Whenever an account client calls the TransferMoney-method, the bank service calls back the two related account clients by calling the UpdateBalance method of the callback service:

public void TransferMoney(int debitAccountumber, int creditAccountNumber, double amount)
{
	Account debitAccount = Bank.Accounts.SingleOrDefault((a) => a.Number.Equals(debitAccountumber));
	if (debitAccount == null)
	{ throw new FaultException("Debit account number unknown to bank!"); }

	Account creditAccount = Bank.Accounts.SingleOrDefault((a) => a.Number.Equals(creditAccountNumber));
	if (creditAccount == null)
	{ throw new FaultException("Credit account number unknown to bank!"); }

	debitAccount.Balance -= amount;
	creditAccount.Balance += amount;

	// Inform credit and debit accounts about new balance
	IAccountServiceCallback iAccountServiceCallback = null;

	iAccountServiceCallback = Bank.AccountServiceCallbacks.Single((kvp) => kvp.Key.Equals(debitAccount.Number)).Value;
	iAccountServiceCallback.UpdateBalance(debitAccount.Balance);

	iAccountServiceCallback = Bank.AccountServiceCallbacks.Single((kvp) => kvp.Key.Equals(creditAccount.Number)).Value;
	iAccountServiceCallback.UpdateBalance(creditAccount.Balance);
}

A look at this should give you a better picture of the underlying architecture:

Bank server workflow

Note, that separation of concerns allows us to easily host the banking service in different ways. In this demo, I implemented a WPF and a console host.

The demo still lacks thorough error handling, but should give you a sound understanding of what’s going on. Enjoy!

Async Await – error handling got better?

In my last post I looked if I see any benefits in the code structure using the async await pattern. To do so, I compared the async await implementation with implementations using based on

  • a BackgroundWorker
  • a plain Task object without async await

Now I want to have a look at the differences in exception handling by throwing an exception based on the downloadable sample code of my last post.

Backgroundworker first:

class UseBackgroundWorker
{
	public void Start()
	{
		Debug.Print(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Starting background method.");

		var bw = new BackgroundWorker();

		bw.DoWork += DoWork;
		bw.RunWorkerCompleted += OnDoWorkCompleted;
		bw.RunWorkerAsync();

		Debug.Print(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Started background method.");
	}

	// Background main method
	private void DoWork(object sender, DoWorkEventArgs e)
	{
		throw new TestException("Test is a test exception");

		e.Result = "Finished!";
	}

	// Background result method
	private void OnDoWorkCompleted(object sender, RunWorkerCompletedEventArgs e)
	{
		if (e.Error != null)
		{
			Debug.Print(string.Format(Program.MessageBase, Thread.CurrentThread.IsBackground
				, Thread.CurrentThread.ManagedThreadId
				, "An exception occured in the background thread. Exception message: " + e.Error.Message));
		}
		else
		{
			Debug.Print(string.Format(Program.MessageBase, Thread.CurrentThread.IsBackground
				, Thread.CurrentThread.ManagedThreadId, "Background method completed. Result: " + e.Result.ToString()));
		}
	}
}

Exception handling is done in the background result method by querying the error property of the RunWorkerCompletedEventArgs. If the Error property of the RunWorkerCompletedEventArg holds an error and you try to access the result property of the RunWorkerCompletedEventArgs, a System.Reflection.TargetInvocationException exception is thrown. Thus, the if statement was needed. This kind of “exception management” differs from the regular try-catch-pattern.

Next comes an exception inside a plain Task object without async await:

class UseTask
{
	public void StartTask()
	{
		Debug.Print(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Starting background method.");

		var task = new Task<string>(DoWork);
		task.ContinueWith(OnWorkDone); // Configure method call after task is finished
		task.Start();
		Thread.Sleep(100);

		// Runs in foreground thread
		Debug.Print(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Started background method.");
	}

	// Background main method
	private string DoWork()
	{
		throw new TestException("Test is a test exception");

		return "Finished!";
	}

	// Background result method
	private void OnWorkDone(Task<string> executedTask)
	{
		if (executedTask.IsFaulted)
		{
			foreach (Exception ex in executedTask.Exception.InnerExceptions)
			{
				Debug.Print(string.Format(Program.MessageBase, Thread.CurrentThread.IsBackground
					, Thread.CurrentThread.ManagedThreadId
					, "An exception occured in the background thread. Exception message: " + ex.Message));
			}
		}
		else
		{
			Debug.Print(string.Format(Program.MessageBase, Thread.CurrentThread.IsBackground
				, Thread.CurrentThread.ManagedThreadId
				, "Background method completed. Result: " + executedTask.Result));
		}
	}
}

We basically see the same “unorthodox” exception handling mechanism as before using the Background worker. Only difference: instead of the event arg, the error property now belongs to the task and holds a special type of exception called AggregateException, which can contain more than one exception in its inner exceptions collection.

What’s about async await?

class UseAsyncAwait
{
	public async void StartAsync()
	{
		Debug.Print(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Starting background method.");

		var task = new Task<string>(DoWork);
		task.Start();

		Thread.Sleep(100);

		Debug.Print(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Started background method.");

		string result;

		try
		{
			result=  await task;
		}
		catch (Exception ex)
		{
			Debug.Print(string.Format(Program.MessageBase, Thread.CurrentThread.IsBackground
				, Thread.CurrentThread.ManagedThreadId
				, "An exception occured in the background thread. Exception message: " + ex.Message));

			return;
		}
		
		// Runs in same background thread as Task
		Debug.Print(string.Format(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Background method completed. Result: " + result));
	}

	// Background main method
	private string DoWork()
	{
		throw new TestException("Test is a test exception");
		return "Finished!";
	}
}

Spotted the difference? Now we make use of a regular try-catch for error handling. Additionally to the “loss” of the background result method, this makes our async code even more similar to regular syncroneous code, which is a good thing.

Async Await – is this I was waiting for?

The sample project can be downloaded here.

According to MSFT, Async Await is the way to go for multithreaded programming starting from .Net 4.5. Of course, they said the same for older .Net versions starting with the asynchronous Programming Model to the task parallel library.

Right now, if there is something to do in the background, I use the background woker if the background thread yields a result or a simple thread if it’s just fire and forget.

I felt happy, until I was playing around a little bit with mobile Windows Phone development. In mobile development, lot of methods only run in async mode to avoid blocking the UI and the method descriptions explicitly state to use the async await pattern. Being told to do us, I decided that it was time to check if this pattern simplifies my life.

To do so, I created a simple background scenario and implemented it using my old approach with the background worker. Then, I implemented the same scenario using the task parallel library and finally using the async await pattern to see, if something changed for the better regarding the structure of the code.

This is our starting point. A method starting a background thread entering a loop and finally returning a result string:


// Somewhere globally accessible
const string MessageBase = "Is backtround thread: '{0}'. Thread id: '{1}' Description: '{2}'";

class UseBackgroundWorker
{
	public void Start()
	{
		Debug.Print(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Starting background method.");

		var bw = new BackgroundWorker();

		bw.DoWork += DoWork;
		bw.RunWorkerCompleted += OnDoWorkCompleted;
		bw.RunWorkerAsync();

		Debug.Print(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Started background method.");
	}

        // Background main method
	private void DoWork(object sender, DoWorkEventArgs e)
	{
		for (int i = 0; i < 5; i++)
		{
			Debug.Print(string.Format(Program.MessageBase, Thread.CurrentThread.IsBackground
				   , Thread.CurrentThread.ManagedThreadId, "Executing work in background ."));
			Thread.Sleep(100);
		}

		e.Result = "Finished!";
	}

        // Background result method
	private void OnDoWorkCompleted(object sender, RunWorkerCompletedEventArgs e)
	{
		Debug.Print(string.Format(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Background method completed. Result: " + e.Result.ToString()));
	}
}

According to MSFT, this code is annoying, because you are forced to split the code running in the background task into two methods. One method for the main background task (DoWork) and the second to run after the main background task is finished (OnDoWorkCompleted). For me, to be honest, I have no problems with this, but MSFT says, there is a better way. Let’s go for a walk.

First we replace the Backgroundworker by using a Task object being part of the task parallel library:

class UseTask
{
	public void StartTask()
	{
		Debug.Print(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Starting background method.");

		var task = new Task<string>(DoWork);
		task.ContinueWith(OnWorkDone); // Configure method call after task is finished
		task.Start();
		Thread.Sleep(100);

		// Runs in foreground thread
		Debug.Print(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Started background method.");
	}

        // Background main method
	private string DoWork()
	{
		for (int i = 0; i < 5; i++)
		{
			Debug.Print(string.Format(Program.MessageBase, Thread.CurrentThread.IsBackground
				, Thread.CurrentThread.ManagedThreadId, "Executing work in background ."));
			Thread.Sleep(100);
		}

		return "Finished!";
	}

        // Background result method
	private void OnWorkDone(Task<string> executedTask)
	{
		Debug.Print(string.Format(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Background method completed. Result: " + executedTask.Result));
	}
}

Have we gained something regarding the code structure? Answer: no. Our background code is still split into two methods. Only the signature of the result method and the background configuration changed.

Maybe our code looks better using async await?

class UseAsyncAwait
{
	public async void StartAsync()
	{
		Debug.Print(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Starting background method.");

		var task = new Task<string>(DoWork);
		task.Start();
		Thread.Sleep(100);

		Debug.Print(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Started background method.");

		string result=  await task;
		
		// This code was in the background result method before
		Debug.Print(string.Format(Program.MessageBase, Thread.CurrentThread.IsBackground
			, Thread.CurrentThread.ManagedThreadId, "Background method completed. Result: " + result));
	}

        // Background main method
	private string DoWork()
	{
		for (int i = 0; i < 5; i++)
		{
			Debug.Print(string.Format(Program.MessageBase, Thread.CurrentThread.IsBackground
				, Thread.CurrentThread.ManagedThreadId, "Executing work in background ."));
			Thread.Sleep(100);
		}

		return "Finished!";
	}
}

Look! Where is our background result method gone? Answer: it is part of the StartAsync method. The compiler now creates the background result method on our behalf. The code behind the await statement is still executed in the background thread after the background main method finished. This is really something new and the code now looks similar to syncronous code.

Conclusion: It’s nice – but I am not that excited either. To me, async await addressed an issue I don’r really care about, because async programming has always meant another code structure and I simply got used to it. It’s the same as the impedance mismatch between the object oriented and the relational database world. Many articles and libraries have been written to a bridge I gap I never really felt. On the other hand, it’s nice to see that MSFT tries to make developers life more simple, although I doubt that releasing a new approach for the same thing to solve every release cycle of a new framework makes average developer’s life easier.

My favorite subversion command line scripts

Subversion and it’s client tools Tortoise for the file system and AnkhSVN for Visual Studio are a great combination for source control.

Most of the time, you just press either the ‘commit’ or the ‘get latest’ button. Things get more complicated, when you are working with branches. Now two more actions are required.

  • Update your branch with changes from the trunk. By doing so, you may integrate the latest bug fixes or progress of your colleague being to lazy to make a branch on his own ;)
  • Integrate your branch back into the trunk after you are done with your branch development

These two actions are somewhat cumbersome to do using Tortoise or AnkhSvn, because they require some more clicks and a wrong click could cause some headache.

Because of this, I consulted the Svn docs and wrote two small batch scripts using the Svn command line client. When I work on a new project, I copy these two batch files into my general project folder, adjust the directories and execute each batch file when needed.

Batch file 1: Update your branch with changes from the trunk. To execute each morning :)

:: Sync local branch with changes in trunk 
@echo on

set workingPath=C:\Users\...\Documents\Visual Studio 2012\Projects\YourProject 
set repository=https://your_repository

cd %workingPath%

svn merge %repository%

pause

Batch file 2: Update your branch with changes from the trunk. To execute when you’re done with your branch

:: Copy changes from branch working copy into trunk working copy
:: Working directory is trunk
@echo off

:: the working copy to update with the repository
set workingPath=C:\Users\...\Documents\Visual Studio 2012\Projects\YourProject

:: the repository used to update the working copy
set repository=https://your_repository

cd %workingPath%

svn merge --reintegrate %repository%

pause

WinPhone 8.0 development – the good, the bad & the ugly

Owning a lumia 920, one of the things I find annoying is the inability to create custom playlists. The existing sound management is centered around artists and albums. There is no way – at least I haven’t found – to simply select the songs I want and to create a playlist with these.

Fortunately, I was already curious enough to check out WinPhone development and only needed a reason to do so. My goal was to create a playlist app as fast as possible, and here are my – preliminary(?) – conclusions:

The good:

Starting from zero, I searched a good tutorial. Althoug MSDN’s original documentation is good, it is often difficult to find all the pieces you need to get started. Luckily, I found a tutorial which is really great:

SortedObservableCollection

It consists of 35 parts and really helped to get me started. After the first dozen episodes I wanted to give WindowsPhone development a try myself.
That’s good!

After watching some episodes, I realized that I profit greatly from my WPF skills. In fact, WindowPhone development is based on Xaml and the prefered design pattern is MVVM.
That’s good!

Next task was to get ready for development. I downloaded Visual Studio 2012 for Windows Phone development and registered my phone as developer device. Then I was ready to start coding. I tell you, that the Windows Phone emulator works great! When debugging, I have the choice between using the emulator or my own phone. For sure, the Express Edition is not for professional usage. For example, you can not add plug-ins and you are limited to the WindowsPhone project types. But this edition enables a fast and free starting point.
That’s good!

The bad:

Starting with the pre-installed templates Visual Studio gave me, I was surprised to see how much code behind existed and how event-driven and cluttered the sample code was.
That’s bad!

I wanted to give my playlist editor to different pages and thus needed navigation. Surprise, when I saw, that navigation uses URI-path including the passed parameters inside the string. I hoped, the days of string parsing are over. But obviously, I was wrong.
That’s bad!

Trying to get rid of the parameter strings, I simply used the global accessible main viemodel and wanted to read the selected item I needed for the second viewmodel directly from there. It did not work, because to determine SelectedItem I used a property of the same name which is buggy in a sense, that is not defined as dependency property. The community already knows and inherits from the LongListSelector control to implements it’s own SelectedItem property – argh! WindowsPhone only introduced a handfull of new controls. It should have possible to implement the defined properties correctly.
That’s bad!

The ugly:

No showstopper so far. I created a modest UI, started to code, got the songs selectable to be passed to a collection. The result that far was promising.

SortedObservableCollection

I wanted to use to create the playlist and … noticed that the MediaPlayer does not accept an enumerable of songs, but a SongCollection instead. What is that? It’s a none accessible (internal) class using other internal classes and forces the developer to obey to the same limitations as the end user. In other words, you get a SongCollection based on genre and artists, but not based on the songs you want. Asking doctor Google, I found that I am not the first person runinng against this limitation. Concerning media, the API seems to be really limited. This doesn’t seem to be a techical constraint but a management decision, which makes things even worse for me.
That’s ugly!

In fact, I am afraid my playlist editor will never reach the app store and I need to find another way to get rich. If I reach this objective with another WinPhone app, I doubt. But I certainly continue to have a look at WinPhone development and will give it a second try when I find a new exciting idea.

Stay tuned!

Simple sorted ObservableCollection

In WPF, it’s always a good idea to get things done before interacting with the WPF layer using Xaml or code. Same remains true for sorting. It’s easier to bind to a sorted collection than making the sort in Xaml. Unfortunately, there’s no sorted observable collection ready for use. So, you have to implement your own.

Before coding, we identify which members to override. We do this to guarantee that the sorting doesn’t screw up when our collection gets manipulated in an unexpected way. Spying the ObservableCollection of T and its base class Collection of T, we see that the public methods manipulating a collection do not manipulate the collection themselves. Instead they call a smaller set of methods doing the real work. These are the candidate methods to override.

SortedObservableCollection

As you may have noticed, the are declared virtual – meaning ready to override. That’s a nice indication that we are on the right track. The methods dealing with items removal can be ignored, because removing an item can not screw up the sort order. This means, we have to override only two methods:

  • InsertItem
  • SetItem

Now, there are some more design decisions to make, which are determined by us:

  • Our item of T needs to implement IComparable<T> to use the sorted list. As an alternative, we could pass a comparer into the constructor or do other stuff.
  • Calling methods incompatible with sorting raise a not supported exception (e.g. move item). As an alternative, we could simply ignore the method call.
  • Shall updates of the item keep the sort order? If so, we can force the items to implement the INotifyPropertyChanged interface. I don’t do this in this version of the sorted ObersvableCollection.

Maybe the hardest thing is the sort algorithm. Especially if we do it ourselves. The algorithm determines the sort performance of our collection and how many items we can handle before the gui starts stuttering. I am not a crack in these things, and it took me more than some minutes, but finally I came up with something using interval halving and simple iteration from start to end when the interval the searched item resides got small enough. Easier and more efficient would have been to make use of some .Net implementation using a private sorted list or someting like that. But they all make use of key/value pairs introducing new complexity.

Unit testing the performance, it is no suprise, that our sorted collection scales badly compared to… let’s say a SortedSet. Here are some numbers:

SortedObservableCollection

I didn’t made any real performance tests using WPF controls, but I don’t expect noticable slow down of the gui if the collection handles less than 20.000 items. At least for my use cases so far, that’s ok.

And now the most interesing part: the code. Copy-paste proven ;)

using System;
using System.Collections.ObjectModel;
using System.Linq;

namespace CustomCollections
{
    public class SortedObservableCollection<T>
        : ObservableCollection<T> where T : IComparable<T>
    {
        protected override void InsertItem(int index, T item)
        {
            if (this.Count == 0)
            {
                base.InsertItem(0, item);
                return;
            }

            index = Compare(item, 0, this.Count - 1);

            base.InsertItem(index, item);
        }

        private int Compare(T item, int lowIndex, int highIndex)
        {
            int compareIndex = (lowIndex + highIndex) / 2;

            if (compareIndex == 0)
            {
                return SearchIndexByIteration(lowIndex, highIndex, item);
            }

            int result = item.CompareTo(this[compareIndex]);

            if (result < 0)
            {   //item precedes indexed obj in the sort order

                if ((lowIndex + compareIndex) < 100 || compareIndex == (lowIndex + compareIndex) / 2)
                {
                    return SearchIndexByIteration(lowIndex, compareIndex, item);
                }

                return Compare(item, lowIndex, compareIndex);
            }

            if (result > 0)
            {   //item follows indexed obj in the sort order

                if ((compareIndex + highIndex) < 100 || compareIndex == (compareIndex + highIndex) / 2)
                {
                    return SearchIndexByIteration(compareIndex, highIndex, item);
                }

                return Compare(item, compareIndex, highIndex);
            }

            return compareIndex;
        }

        /// <summary>
        /// Iterates through sequence of the collection from low to high index
        /// and returns the index where to insert the new item
        /// </summary>
        private int SearchIndexByIteration(int lowIndex, int highIndex, T item)
        {
            for (int i = lowIndex; i <= highIndex; i++)
            {
                if (item.CompareTo(this[i]) < 0)
                {
                    return i;
                }
            }
            return this.Count;
        }

        /// <summary>
        /// Adds the item to collection by ignoring the index
        /// </summary>
        protected override void SetItem(int index, T item)
        {
            this.InsertItem(index, item);
        }

        private const string _InsertErrorMessage
           = "Inserting and moving an item using an explicit index are not support by sorted observable collection";

        /// <summary>
        /// Throws an error because inserting an item using an explicit index
        /// is not support by sorted observable collection
        /// </summary>
        [Obsolete(_InsertErrorMessage)]
        public new void Insert(int index, T item)
        {
            throw new NotSupportedException(_InsertErrorMessage);
        }

        /// <summary>
        /// Throws an error because moving an item using explicit indexes
        /// is not support by sorted observable collection
        /// </summary>
        [Obsolete(_InsertErrorMessage)]
        public new void Move(int oldIndex, int newIndex)
        {
            throw new NotSupportedException(_InsertErrorMessage);
        }
    }
}

Finding conflicts when referencing same assembly in different projects

I just encountered this error for the first time of my life:

Found conflicts between different versions of the same dependent assembly

The error popped up, after I referenced a new dll-assembly created by myself to the project. I was sure that the build options of the projects where the same. Missing any real idea, I double clicked on the error message in the error window:

ErrorMessage

Visual Studio asked my this:

Question

Hm, why not? I pressed ‘Ja’ == ‘Yes’ and looked into the app config to check the new entry:

AppConfig

That made sense! The newly referenced assembly used NUnit for unit testing like the referencing assembly did. But they used a different version. Knowing this, I just made sure that both projects use the most recent version and the error was gone without any changes in the app config.

And my lesson learned: double click the error message if you have no clue what it is about :)

Display Log4Net entries in WPF datagrid in real time

Log4Net uses so called appenders defining where the logging goes. Instead of using pre-defined appenders, you can also define your own appender. Doing so allows you to add custom code into the Log4Net logic to server your own purposes.

For example, I wanted the user to see new Log4Net entries appearing life as logging goes on in a standard datagrid.

Here is how logging in the downloadable demo project looks like.

In WPF:

Log4Net

Using the logviewer Trace32.exe:

Log4Net

Both, the WPF datagrid and the logviewer update whenever a new logentry is written.

Here is how the Log4Net configuration in the app.config looks like:

<log4net>
	<appender name="RollingFileAppenderAll" type="log4net.Appender.RollingFileAppender">
	  <file value="C:\Users\...\WpfLog.log"/><!--1. Set path where to log here -->
	  <appendToFile value="true"/>
	  <rollingStyle value="Size"/>
	  <maxSizeRollBackups value="5"/>
	  <maximumFileSize value="1MB"/>
	  <staticLogFileName value="true"/>
	  <layout type="log4net.Layout.PatternLayout">
		<conversionPattern value="%date [%thread] %level %logger - %message%newline"/>
	  </layout>
	  <filter type="log4net.Filter.LevelRangeFilter">
		<levelMin value="INFO" />
		<levelMax value="FATAL" />
	  </filter>	
	</appender>

	<appender name="WpfAppender" type="Log4NetInDataGrid.Logging.WpfAppender, Log4NetInDataGrid" />

	<root>
	  <level value="DEBUG"/>
	  <appender-ref ref="RollingFileAppenderAll"/><!--2. Uncomment rolling file appender here -->
	  <appender-ref ref="WpfAppender"/>
	</root>
</log4net>

You can see two appenders. A predefined rolling file appender and a custom appender created in the demo project named WpfAppender.

To create a new appender, you derive from a log4Net class called AppenderSkeleton:

    Public Class WpfAppender
        Inherits AppenderSkeleton

        ''' <summary>
        ''' Log target
        ''' </summary>
        Public Property LoggingWindow As LoggingWindow

        ''' <summary>
        ''' Addes a log entry to the Execution Control's LogEntries property
        ''' </summary>
        ''' <remarks>
        ''' Appender does not log debug messages
        ''' </remarks>
        Protected Overloads Overrides Sub Append(loggingEvent As log4net.Core.LoggingEvent)

            If loggingEvent.MessageObject.GetType.IsAssignableFrom(GetType(LogEntry)) Then
                Dim logEntry = DirectCast(loggingEvent.MessageObject, LogEntry)

                If Me.LoggingWindow.LogEntries.Count = 0 Then
                    Me.LoggingWindow.LogEntries.Add(logEntry)
                Else
                    Me.LoggingWindow.LogEntries.Insert(0, logEntry)
                End If
            Else
                Throw New Exception(String.Format("The logging window received a log message of type '{0}' which was not convertable to an LogEntry", loggingEvent.MessageObject.GetType.Name))
            End If
        End Sub

    End Class

Whenever you log something, you call a log-method taking a messageobject of type object. The WpfAppender assumes that you pass a messageobject of type LogEntry. LogEntry is a self declared type. The WPF window displaying the log messages has a collection of LogEntries. Whenever a a Log4Net entry is done, the WpfAppender’s append method is called and the new LogEntry is added to the collection of the Wpf Window, to which the datagrid is bound. Doing so, all Log4Net entries are displayed immediately.

The LogEntry class is very simple:

Public Class LogEntry
	Public Property Message As String
	Public Property Level As State

	''' <summary>
	''' ToString output is used by Log4Net as default
	''' </summary>
	Public Overrides Function ToString() As String
		Return Me.Message
	End Function
End Class

The ToString-method is used to write standard Log4Net log entries as the rolling file appender does. In contrast, the WPF datagrid binds its columns to the properties of the log entry:

<DataGrid AutoGenerateColumns="False" 
                  ItemsSource="{Binding Path=LogEntries
		, RelativeSource={RelativeSource FindAncestor
		, AncestorType=me:LoggingWindow, AncestorLevel=1}}">
	<DataGrid.Columns>
		<DataGridTemplateColumn MinWidth="30" Header="Log status">
			<DataGridTemplateColumn.CellTemplate>
				<DataTemplate>
					<Image Width="16"
					   Height="16"
					   Source="{Binding Path=Level,
						UpdateSourceTrigger=PropertyChanged,
						Converter={conv:StateToImageConverter}}" />
				</DataTemplate>
			</DataGridTemplateColumn.CellTemplate>
		</DataGridTemplateColumn>
		<DataGridTextColumn Binding="{Binding Path=Message}" 
                                      Header="Log message" />
	</DataGrid.Columns>
</DataGrid>

Of course, there are some more things going on in detail, but the parts presented above represent the basic structure of how to implement a real time log4Net viewer in WPF. Feel free to download the demo project and check-out logging in real!

DevExpress grid control and item synchronization

WPFLast week I was going to replace the MSFT datagrid with the DevExpress gridcontrol. After the first of about 40 replacements, I wondered why the syncronization of the selected item does not work anymore as it did using the MSFT datagrid, although I explicitly set the IsSynchronizedWithCurrentItem property in the related TableView to true.

The DevExpress support confirmed my appreshension that “The IsSynchronizedWithCurrentItem property has an effect only with sources implementing the ICollectonView interface” and the proposed solution was to “Inherit the ViewModel from the DependencyObject, and implement the CurrentRow dependency property“.

Adding a new layer to the existing viewmodels containing a dependency property and ICommand implementations seemed to much work. Searching for an alternative, I simply created a converter, whose job is to convert an Enumerable to a CollectionView. This means, I can keep my viewmodels unchanged and only have to add the converter to the existing bindings.

Before (synchronization is not working anymore because “Items” collection does not implement ICollectonView):

<dxg:GridControl
	 ItemsSource="{Binding Path=Items}">

After (using the converter makes synchronization work again):

<dxg:GridControl  
	 ItemsSource="{Binding Path=Items,
	   Converter={StaticResource EnumerableToCollectionViewConverter}}">

As you might guess, the converter accepts an Enumerable and returns its default collection view.

What, if you don’t want the default collection view, but a new one instead? No problem, use the converter parameter and pass in the desired implementation of the ICollectonView to return like this:

<dxg:GridControl  
     ItemsSource="{Binding Path=Items,
	   Converter={StaticResource EnumerableToCollectionViewConverter},
	   ConverterParameter={x:Type vw:ListCollectionView}}">

“vw” points to the namespace “xmlns:vw=”clr-namespace:System.Windows.Data;assembly=PresentationFramework” declaring the ListCollectionView.

And here is the converter class it-self:

using System;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
using System.ComponentModel;

namespace Converter
{

    public class EnumerableToCollectionViewConverter : IValueConverter
    {
        /// <summary>
        /// Converts an enumerable to a collection view
        /// </summary>
        /// <remarks>
        /// By default, the default view of the enumerable is returned. To return a new view, set the parameter to the type 
        /// of view to return (ListCollectionView, BindingListCollectionView, CollectionView, etc.)
        /// </remarks>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (!typeof(System.Collections.IEnumerable).IsAssignableFrom(value.GetType()))
            {
                throw new System.ArgumentException("The " + this.GetType().Name + " converter needs an enumerable to convert it into a collection view.");
            }

            bool createDefaultView = true;

            if (parameter != null)
                if (!typeof(Type).IsAssignableFrom(parameter.GetType()))
                {
                    throw new ArgumentException("The " + this.GetType().Name + " converter needs parameter of type 'Type' if a parameter is used.");
                }

            if (typeof(ICollectionView).IsAssignableFrom((Type)parameter))
            {
                createDefaultView = false;
            }

            if (createDefaultView)
            {
                return CollectionViewSource.GetDefaultView(value);
            }
            else
            {
                try
                {
                    return Activator.CreateInstance((Type)parameter, value);
                }
                catch (Exception ex)
                {
                    throw new Exception("The " + this.GetType().Name + " converter is unable to create the requested view as defined by the parameter." + 
                    "Make sure that the enumeration supports the required view. Requested view:" + ((Type)parameter).Name + "; Underlying enumeration: " +
                    value.GetType().Name, ex);
                }
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new System.NotSupportedException("The " + this.GetType().Name + " converter can only convert Enumerables to collection views, not the other way around.");
        }

    }
}

To simplify the usage of the converter (first: resource declaration, second: usage in binding) even further, I wrote a little markup extension exposing the converter to XAML without need to declare the converter as a resource anymore.

The binding now looks like this:

<dxg:GridControl
	 ItemsSource="{Binding Path=Items,
	   Converter={cv:EnumerableToCollectionViewConverterMarkup}}">

And here is the markup extension:

namespace Converter
{
    /// <summary>
    /// Exposes the EnumerableToCollectionViewConverte to XAML 
    /// without any need to declare the converter as a resource
    /// </summary>
    public class EnumerableToCollectionViewConverterMarkup
        : MarkupExtension
    {
        private static EnumerableToCollectionViewConverter _Converter;

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (_Converter == null)
            {_Converter = new EnumerableToCollectionViewConverter();}

            return _Converter;
        }
    }
}

In fact, some clever people declare converter and markup extension in the same class and use all of their converters this way. Have a look at this to see how it looks like.

Having done this, replacing the MSFT datagrid should become much easier for the remaining 39 datagrids in my current project ;).

Configure WCF tracing for each dev

Wcf tracing is a great thing.It helps you to detect WCF related errors otherwise not being visible, because the thrown exception does not contain the WCF related issue it-self. At least, this is what I encountered, when an object become to large for serialization. I needed to turn on WCF tracing to get the error message, telling me that the “MaxItemsInObjectGraph” limit was reached.

Here is how the log looks like:

WcfTrace

Unfortunately, WCF trace configuration – contrary to WPF tracing – can only be done in an app.config file. At least, I did not find a way to do this programmatically at runtime, making it difficult to allow each dev team member to have his own WCF tracing configuratution. Finally, I found a way working for us, allowing each dev member to specify:

  • The trace level, eg. “Off” or “Error”
  • The path of where to write the trace to

Important: this solution only works, if you define your WCF endpoints in code. Otherwise, you most probably won’t be able to set a static property before the endpoints are created.

Because I was not able to get rid of the app.config, I had to write custom trace related classes used in the app.config. Here is how the app.config looks like:

<?xml version="1.0"?>
<configuration>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/>
  </startup>

  <system.diagnostics>
    <trace autoflush="true"/>

    <sources>
      <!-- 
      This is the user unspecific wcf config defining a wcf logging whose wcf logging path and wcf logging
      level are defined in the user specifi config file
      -->
      <source name="System.ServiceModel"
              switchType="Util.WcfSourceSwitch, server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
              propagateActivity="true">
        <listeners>
          <remove name="Default"/>
          <add name="traceListener"/>
        </listeners>
      </source>
    </sources>
    
    <sharedListeners>
      <add name="traceListener"
              type="Util.WcfWriterTraceListener, server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
              initializeData= "The Wcf log path will be read from the user config and this value will be ignored" />
    </sharedListeners>
  
  </system.diagnostics>
  
</configuration>

The WcfSourceSwitch class exposes the log level directly as “Level”-property as SourceLevel enum type. The class has a static SourceLevel property which must be set before any WCF endpoint is created.

Note: Both classes reside in namespace “Util”.

    /// <summary>
    /// Turns Wcf logging on server on/off by reading the WcfLogSourceLevel as defined in the user config
    /// </summary>
    /// <remarks>
    /// Based on: http://wcfpro.wordpress.com/2010/11/21/how-to-add-wcf-traces-programmatically/
    /// </remarks>
    public class WcfSourceSwitch 
        : SourceSwitch
    {
        public WcfSourceSwitch(string name)
            : base(name)
        {
            if (WcfSourceSwitch.SourceLevel == SourceLevels.Off)
            {
                this.Level = WcfSourceSwitch.SourceLevel;
            }
            else
            {
                this.Level = WcfSourceSwitch.SourceLevel | SourceLevels.ActivityTracing;
            }
        }

        /// <summary>
        /// The source level the wcf source switch to create will use.
        /// Must be set before the creation of the first wcf source switch instance
        /// </summary>
        public static SourceLevels SourceLevel { get; set; }
    }

The WcfWriterTraceListener class defines the path where to log. Normally, the constructor passes in a string defining the full path where to log. Doing a little hack, this passed in string is ignored. Instead the private “fileName” field defining the log path is set using reflection. This means you can define the log path setting any value you want, eg. from a database or a dev specifig config file.

    /// <summary>
    /// A trace listener reading the logging path from the user specific config file 
    /// instead of the app.config
    /// </summary>
    public class WcfWriterTraceListener
        : XmlWriterTraceListener
    {
        /// <summary>
        /// Creates a new trace listener
        /// </summary>
        /// <param name="filename">The passed in file name as defined in the app.config is ignored</param>
        public WcfWriterTraceListener(string filename)
		     :  base(string.Empty)
        {             
            FieldInfo field = typeof(TextWriterTraceListener).GetField("fileName", BindingFlags.NonPublic | BindingFlags.Instance);
            field.SetValue(this, --> YOUR PATH WHERE TO LOG <--);
        }
    }

Hope this helps. For us it did!