C# Code Snippet for Unit Tests

After coding unit tests the whole day, I decided to create a nice Visual Studio snippet which helps me to write the test method quicker. I usually structure my unit tests like this:

public void Validate_ReturnsFalse_WhenStringIsTooLong()
	// Arrange
	var expectedResult = false;
	var watheverMock = new Mock<IWathever>();

	// Act
	var validator = new Validator(watheverMock.Object);
	var result = validator.Validate("test...");

	// Assert
	Assert.IsTrue(result == expectedResult, "Returned validation result: {0}. Expected validation result: {1}", result, expectedResult); 

The method name is separated in three parts: “FunctionUnderTest”_”ExpectedResult”_”UnderWhichCondition”. And the unit test logic is build based on the AAA (Arrange,Act,Assert) pattern.
So my snippet does the typing work for you. (You can download the snippet here)
You can import the snippet file through the “Code Snippet Manager” under “Tools”.
Here an example how you can use it:
VS Unit Test

Entity Framework and Expression Queries

In my current project I had to generate a Entity Framework query based on some search criterias defined in a dictionary.
The structure of the dictionary was similar to this example here:

var searchCriteria = new Dictionary<string, List<string>>() 
    { "FirstName", new List<string> { "Darko", "NoName" } },
    { "LastName", new List<string> { "Micic", "Müller", "Obama" } }

The key contained the property/column name and the value containted a list of search criterias for this column. So first I wanted to build the query the type-safe way:

var query = model.People.AsQueryable();

if (searchCriteria.ContainsKey("FirstName"))
    var firstNames = searchCriteria["FirstName"];
    query = query.Where(x => firstNames.Contains(x.FirstName));

var result = query.ToList();

But I didn’t like that approach, because I need to handle each possible property on its own.
Therefore I decided to generate the query based on expressions. This is not a type-safe solution, but the approach leads to less code :)

BinaryExpression condition = null;
var parameter = Expression.Parameter(typeof(Person), "p");

foreach (var criteria in searchCriteria)
    foreach (var comparisonValue in criteria.Value)
        var property = Expression.Property(parameter, criteria.Key);
        var equalityCheck = Expression.Equal(property, Expression.Constant(comparisonValue));
        condition = condition == null ? equalityCheck : Expression.Or(condition, equalityCheck);

The “condition” variable is an expression tree which contains “OR” combined comparison checks based on the search criteria. This expression can be used this way:

var query = model.People;
var predicate = Expression.Lambda<Func<Person, bool>>(condition, parameter);
var result = query.Where(predicate).ToList();

In debug mode we see how the comparison checks ar stitched together:
Ef Expression Condition
Entity Framework is able to convert this expression into a SQL “where” condition.

Nothing new… But I think this is not widely used.

Safe Index Property Accessor

Recently I had to build a very dynamic DataGrid in WPF, in which the columns were constructed dynamically. And some rows did not contain data for each generated column. I stored the dynamic values in a dictionary and bound the dynamic columns to the indexer property. The problem was that the dictionary throw an KeyNotFoundException when the UI binding tried to get a value for a key which does not exist in a certain model. To “suppress” the exception I wrote a dictionary which checks if the key/index exists. If not, the default value is returned.

Pretty easy code. The class is called IndexAccessorSafeDictionary

public class IndexAccessorSafeDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    public new TValue this[TKey key]
            if (!this.ContainsKey(key))
                return default(TValue);
            return base[key];

    public TValue this[int index]
            if (index >= this.Count)
                return default(TValue);
            return this.Skip(index).First().Value;

F# Journey: Course 3 – Functions

Back to: F# Journey: Course 2- Type Inference

The concept of a function exists is in F# too. However, it’s slightly different than in C#.

A F# function has a name, list of parameters and a return value. The function itself is assigned to a value with the “let” keyword. The parameter types are inferred by the compiler. But it’s possible to define the parameter type explicitly. The last statement in a function represents the return value.

Here is a “HelloWord” example. The code below defines a function with the name “hello” and one parameter “name”. The name paramter is of type string. (Inferred by compiler)
The function body is indented and has a value named “helloString” of type string which gets concatinated with the “name” parameter. The last statement “helloString + name” is the return value of the “hello” function. “helloExplicit” is the same function but with explicit type definition.

// Types inferred
let hello name =
    let helloString = "Hello "
    helloString + name

// Explicit type definition
let helloExplicit (name : string) : string =
    let helloString : string = "Hello "
    helloString + name

printfn "%s" (hello "Darko")
printfn "%s" (helloExplicit "Darko")

A function always returns a value. The return value can be be ignored if it is not used by the caller.

hello "Darko" |> ignore

F# supports “partial application”. By supplying fewer arguments to a function than expected, F# creates a new one which expects the remaining arguments.
The following “sum” functions expects two arguments. The second functions “sumWithSummand2″ calls the “sum” function and passes the first argument “2″.

let sum summand1 summand2 = summand1 + summand2
let sumWithSummand2 = sum 2

printfn "%d" (sum 2 4)
printfn "%d" (sumWithSummand2 4)

Both functions are doing the same, but the signature is different:
val sum : summand1:int -> summand2:int -> int
val sumWithSummand2 : (int -> int)

The “sum” function is curried, which means that the argument list represents a list of single arguments, each returning a function with one less argument than the previous. The “sumWithSummand2″ expects one int parameter and a int return value.

To be continued…

F# Journey: Course 2 – Type Inference

Back to: F# Journey: Course 1 – Immutable Values

You probably know type inference already from C#. But in F# it’s like magic! You don’t have to define the type quite often. The compiler will automatically find out.

Let’s start with some examples:

let a = 1
// or
let plus a b = a + b

“a” is in that case of type “int”. The “plus” functions accepts 2 parameters (a,b) of type int and the return value is automatically treated as int. (I will cover functions in one of the next courses)

But if you want “double” instead of “int” then you can define the type explicitly.

let (a : double) = 4.0
// Or
let plus' (a : double) (b : double) = a + b

“a” and “b” and the function return value are of type double.

Now let’s output the values with the F# “printfn” function.

let a  = 4
printfn "Value of a: %A" a
printfn "Value of a: %d" a
printfn "Value of a: %s" a

The first and second printfn calls will work as expected. But the last one will not work. Your code will not compile at all!
The compiler brings this message: “This expression was expected to have type string
This because the printfn “%s” expects a value of type string. But in our case “a” is of type int.

No let’s have a look at our “plus” function.

let plus a b = a + b
printfn "Plus result: %A" (plus 1 2)
printfn "Plus result: %d" (plus 1 2)
printfn "Plus result: %s" (plus 1 2)

As you may guess, we get the same error again. But now let’s remove the first two printfn calls and try again.

let plus a b = a + b
printfn "Plus result: %s" (plus 1 2)

Yes.. it will still not work but this time we get a different error message: “The type ‘string’ does not match the type ‘int’
Because we want to output a string (%s) F# thinks that the return value of “plus” is of type string. The compiler changed the signature of the function from
int -> int -> int
int -> int -> string
Now we can even change the type of the parameters when calling the plus function to string -> string -> string

let plus a b = a + b
printfn "Plus result: %s" (plus "1" "2")

This compiles but the logic of this function doesn’t work as expected. The output is “Plus result: 12″ and not 3. We are just concatenating two strings.
This is the right way how to call the printfn when the types are not defined.

let plus a b = a + b
printfn "Plus result: %d" (plus 1 2)

Even for custom types/records (will be covered in next courses) F# offers some nice features.
The first line in the code below defines a record type and the second line instantiates an object. The type “person” is inferred based on the properties “id” and “name”.

type person = { id : int; name : string }
let personRecord = { id = 1; name = "Darko" }

Next: F# Journey: Course 3 – Functions

My F# Journey

After working 4-5 years mainly with object-oriented programming languages like C#, I thought it’s a good time to dive into other programming paradigms. For example: Functional programming -> F#!
Based on the “Indeed Trends” (see at the bottom of this post) we see that the market is still not seeking a lot F# or Scala developers. But I think this will change in the future.

As I progress on my F# “journey” I will write some series of posts here. I hope you’ll enjoy the trip. ;)


F# Journey: Course 1 – Immutable Values

F# Journey: Course 2 – Type Inference

F# Journey: Course 3 – Functions

Indeed Trends

F# Journey: Course 1 – Immutable Values

Back to: F# Journey

By default all variables in F# are immutable. Hence.. we can not call them “variables” anymore. The term “value” fits better.
Here is a simple example of an immutable value:

let val1 = 2
printfn "%d" val1

Now when you try to change the value like in the code below (line 2) the compiler will bring this warning:
This expression should have type ‘unit’, but has type ‘bool’. Use ‘ignore’ to discard the result of the expression, or ‘let’ to bind the result to a name.

let val1 = 2
val1 = 4
printfn "%d" val1

The compiler does not even recognize this as an valid value assignment! “val1 = 4″ is a valid comparison, and the compiler says that you either have to save the result in a value with the ‘let’ function or to ignore it with ‘ignore’.

But how can I change the value? Mark the value as mutable and use the <- for the assignment.

let mutable val1 = 2
val1 <- 3
printfn "%d" val1

Going back to the compiler message: If you do an comparison as in the code above you can store the result in a value.

let val1 = 2
let comp = val1 = 4
printfn "%b" comp

The result will be "false". (Well at least the value comparison works the same way as in C#) :)

Functions in F# always have return values. F# will automatically determine the return value. In our case here "val1 = 4", the return value is of type 'bool'. If we don't need the return at all, then we can simply ignore it.

let val1 = 2
val1 = 4 |> ignore
printfn "%d" val1

Immutable values in functional programming have some advantages:
- Easier to share state. Locking not needed for immutable data.
- We have less side effects. Once the value is set it can't be changed during the program flow.
- As an developer, you are more aware of what your code is changing or not.
- The code is more clear. Let's take this C# code as an example:

var myContract = new InsuranceContract(startDate, endDate);

Now guess what the state of myContract object is... Does "Extend" change the endDate property? Or does it create a new InsuranceContract instance? We don't know.
In F# it's clear. Because we can't change the endDate value, the "Extend" function has to return a new InnsuranceContract instance.

Next: F# Journey: Course 2 - Type Inference

WPF MVVM Busy Message With Ambient Context

Every .NET developer has already used an Ambient Context without knowing it. A typical Ambient Context is:

using (var tx = new TransactionScope())

The pattern is not very well known. Here is one good description I found: The Wandering Glitch – Ambient Context

I found this pattern very useful for displaying progress/busy messages in WPF applications. The following example shows how to build a simple Ambient Context for it.
The usage of it is slightly different than in the example above with the TransactionScope. I explain later on why.
(The code is on GitHub)

Usage of the BusyContext in a WPF/MVVM application:
The follow code has two nested BusyContext objects. The creation of a context causes the UI to change the progress text. After disposing a context, the previous context message is displayed.



You see, the usage of the BusyContext is fairly easy. The CreateBusyContext is a helper method in my base viewmodel class.
Here you see that the BusyContext constructor takes three parameter. Context store, busy message and a Action which gets triggered after creating and disposing the context. (Why I’m using a context store is explained at the end of the blog post.)

protected BusyContext CreateBusyContext(string message)
	var context = new BusyContext(this.BusyContextStore, message, this.NotifyBusyChanged);
	return context;

I put the most important classes here. The whole code is on GitHub.

The ContextStore is responsible for storing the contexts. The Current property returns the “deepest” (in nested contexts) context data.

public class ContextStore<TData> : IContextStore<TData>
	private Stack<AmbientContext<TData>> _Store = new Stack<AmbientContext<TData>>();

	public TData Current
			if (_Store.Any())
				return _Store.Peek().Data;
			return default(TData);

	public void Add(AmbientContext<TData> context)

	public void Remove()

The AmbientContext is the base class for the BusyContext:

public abstract class AmbientContext<TData> : IDisposable
    private IStoreWriter<TData> _Store;

    private Action _OnDispose;

    public TData Data { get; private set; }

    public AmbientContext(IStoreWriter<TData> store, TData data, Action onContextChange = null)
        this.Data = data;
        _Store = store;
        this._OnDispose = onContextChange;


    private void NotifyChange()
        if (this._OnDispose != null)

    public virtual void Dispose()

My BusyContext looks quite simple.

public class BusyContext : AmbientContext<string>
	public BusyContext(IStoreWriter<string> store, string busyMessage, Action onContextChange = null)
		: base(store, busyMessage, onContextChange)
	{ }

Reason why the usage of my BusyContext is slightly different compared to other contexts:
- Undefined storage scope:
I don’t want to restrict the context data to a specific scope. Restricting the context to the current Thread [ThreadStatic] (for example) would mean that I could display only one busy message. This is a huge restrication in a non-single window application like MDI/TDI. So therefore, you have to define a storage. This gives a lot of flexibility. For example: You could show multiple busy messages from same ViewModel in same time by defining two different stores.
- No static classes/properties for getting the current busy message:
Static properties like Thread.CurrentPrincipal return the data of the current Ambient Context. In one way, this is very helpful. But it has some drawbacks when it comes to the unit testing. In my example the data of the current Ambient Context can be retrieved from the store object. The store object is a simple class an can be mocked in unit tests.

First Time WCF Client Contracts = Nightmare!

In one of my projects (WPF, WCF) we are working with server and client side entities. Although the entities look very similar, we had some reasons to separate them:
- Client side entities require more logic
-> Implementation of INotifyPropertyChanged
-> Implementation of IEditableObject
-> Restore handling (When user cancels edit)
All these functionalities were implemented in a base class in the client. When working with WCF and WPF I always prefer the share the service contract interfaces rather than creating client proxies. (The code is cleaner and it gives us more flexibility.) But in this project, we couldn’t share the contracts, because the WCF contract interfaces always references the service side entities.
To solve the problem I came up with different approaches:

Sharing the service contracts between server and client (or creating a client proxy) and using a mapper mapper framework (AutoMapper) to map the entities into our client entities.
Adding the service contracts as “linked” files in the client and working with compilation conditions to “swap” the server side contract/entity namespaces. (Or using the same server entity namespace in the client).
Generating with a script the server contracts + entities in the client. Exchanging the base class of the entities. Deserializing the retrieved data directly into client entities.

I decided to implement the third approach because:
- We don’t need and extract step for mapping between server and client entities.
- Having full control over the contracts and entities. (In case of linked files we still have some restrictions)
- “Real” client entities with client specific base class.

For the implementation of these I decided to use T4. My T4 script runs through my server contracts + entities and generates in the client the “duplicate” code. All generated interfaces classes are partial. So we still can add some additional code. And because the DataContractSerializer relies on the contract namespace and NOT on the CLR namespace, we can use client specific namespace for the generated files. To make sure that all server/client contract interfaces and entities are using the same data contract namespace, I added the ContractNamespace attribute in both assemblies.

// Client assembly
[assembly: ContractNamespace("http://blog.micic.ch/contractexample", ClrNamespace = "ContractExampleClient")]

// Server assembly
[assembly: ContractNamespace("http://blog.micic.ch/contractexample", ClrNamespace = "ContractExampleService")]

So, and here is some very important information!

The DataContractSerializer creates instances of the client entities without calling the constructor. (System.Runtime.Serialization.FormatterServices.GetUninitializedObject) Initialization code must be placed in a [OnDeserializing] or [OnDeserialized] method.
The order of the entity properties (DataMembers) must be the same as on the server. By default, the serializes orders the properties alphabetical. BUT if you have a base class, the serializer orders first the properties of your base class alphabetical and then the properties of the child class. (It’s possible to explicitly define the order -> [DataMember(Order=...)] But that’s too much work for an lazy developer :)

Unfortunately… the WCF error messages aren’t very helpful when your client contracts are wrong. In worst case, you don’t get any exception. I lost at the end 6 hours until I found out that:
- My client entities weren’t initialized correctly because the constructor wasn’t called.
- Not all properties were initialized because the order was wrong. My client entity base class has less properties than the server entity base class. And that screwed up the ordering of the properties “in some” of the entities.

So in short. Make sure that:
- The server and client contract namespaces are the same.
- You are using [OnDeserializing] or [OnDeserialized] methods to initialize your client entity.
- The ordering of the base/child entity classes is correct.

At the end, I was very happy with the solution. The DataContractSerializer is very flexible! In our client entities we have for example ObservableCollection<> properties which are mapping to IEnumerable<> server entities. And the handling with different base interfaces, classes and generics is very good!

The first time you will struggle a little bit. But afterwards you will love to work with server and client side WCF contracts.

Here is an simplified example of your server and client code:

/////// SERVER
namespace ContractExampleService
    public interface IPersonService
        Person[] Get();

    public abstract class EntityBase
        [DataMember] public TKey Id { get; set; }
        [DataMember] public DateTime CreatedAt { get; set; }

    public class Person : EntityBase
        [DataMember] public string Firstname { get; set; }
        [DataMember] public string Lastname { get; set; }
        [DataMember] public IEnumerable
Addresses { get; set; } } public class Address : EntityBase { public string Street { get; set; } } } /////// CLIENT namespace ContractExampleClient { [ServiceContract] public interface IPersonService { [OperationContract] Person[] Get(); } [DataContract] public abstract class EditableEntity : IEditableObject { public enum EState { NotChanged = 0, Created = 1, Changed = 2, Deleted = 3 } [DataMember] public TKey Id { get; set; } [DataMember] public DateTime CreatedAt { get; set; } public EState State { get; set; } public void BeginEdit() { } public void CancelEdit() { } public void EndEdit() { } } [DataContract] public class Person : EditableEntity { [DataMember] public string Firstname { get; set; } [DataMember] public string Lastname { get; set; } [DataMember] public ObservableCollection
Addresses { get; set; } } [DataContract] public class Address : EditableEntity { [DataMember] public string Street { get; set; } } }

Partial Validation With Data Annotations

Data Annotations provide a very nice way to validate the entities. But under some circumstances, you may don’t want to validate all properties. For example, a property like “createddate” we don’t want to validate in the client layer, because the field is not set at this point. In this situation it would be good to skip the validation for “createddate”.
I wrote a Nuget packages which allows you exclude specific validations.

NugGet https://www.nuget.org/packages/DataAnnotations.PartialValidation
GitHub https://github.com/dmicic/Dmicic.DataAnnotations.PartialValidation

Here is a simple demo. Let’s say, we have an application structured in 3 layers.
Partial Validation - Demo
The Person entity has following property definitions. (See code block)
I prefer the define the “technology neutral” validation attributes in the Business layer. And all other attributes (MVC attributes, EF attributes) I place in the appropriate layer.

public class Person : EntityBase
    public string Firstname { get; set; }

    public string Lastname { get; set; }

    public string EMail { get; set; }

    public string CreditCardNumber { get; set; }

public abstract class EntityBase
    public Guid Id { get; set; }

    public string CreatedBy { get; set; }

    public DateTime? CreatedDate { get; set; }

    public string ModifiedBy { get; set; }

    public DateTime ModifiedDate { get; set; }

Now when I create a new object of type Person in my UI layer and try to validate it, I will always get validation errors because fields like Id, CreatedBy, CreatedDate are not set. In the UI layer, I only want to validate the properties which can be mutated by the user.
Now I can use the “Partial Validation” framework and define layer specific validation requirements.

var p1 = new Person();
p1.CreditCardNumber = "23434";
p1.EMail = "wrong mail address";

                .Property(p => p.CreatedBy).ExcludeAll() // Exclude all validations for CreatedBy
                .Property(p => p.CreatedDate).ExcludeAll() // Exclude all validations for CreatedDate
                .Property(p => p.EMail).Include(new EmailAttribute()) // Include the Email validation for EMail
                .Property(p => p.CreditCardNumber).Exclude<CreditCardNumberAttribute>(); // Exclude the credit card validation for CreditCardNumber

                .Property(p => p.CreatedBy).ExcludeAll() // Exclude all validations for CreatedBy
                .Property(p => p.CreatedDate).ExcludeAll(); // Exclude all validations fro CreatedDate

            .Property(p => p.CreditCardNumber).ExcludeAllBut<RequiredAttribute>(); // Exclude all except the required validation

var UiResult = PartialValidator.Validate(p1, "UI");
var BusinessResult = PartialValidator.Validate(p1, "Business");
var DataAccessResult = PartialValidator.Validate(p1, "DataAccess");

Here are the result of these layer specific validations.
Partial Validation - Validation Result

This is it! ;)

Here is an example which covers all Partial Validation functions:

        .Exclude<MyFirstValidationAttribute>()                  // Exclutions for all entities in this environment
        .Configure<EntityOne>()                                 // Specification for "EntityOne"
            .Property(p => p.Property1)
                .ExcludeAll()                                   // Exlcude all validations for "Property1"
                .Include(new MyFirstValidationAttribute())      // Include specific validation attribute
        .Configure<EntityTwo>()                                 // Specification for "EntityTwo"
            .Property(p => p.Property1)                         // Exclude Required and StringLength validation attribute for "Property1"
        .Configure<EntityThree>()                               // Specification for "EntityThree"
            .Property(p => p.Property1)                         // Exclude all except "Required" for "Property1"