Blog comments edit

My Colleague Matt Davies has done a blog post a couple of years ago about Unit testing MVC3/MVC4 Model Binders. This is a nice post but as you know Web Api Side of ASP.Net is usually using a different set of object model therefore the setting up the BindingContext would be different than what we have in MVC. I also searched and did not find a good blog post about how to unit test ModelBinders in ASP.NEt Web Api project, so I decided to put together this post.

Let’s assume we have following implementation of model binder which bind a sort expression like FirstName desc or LastName to a simple class structure which has FieldName and Ascending as boolean to indicate sorting direction. Following is the code for ModelBinder:

We want to write a few unit test to make sure logic of this ModelBinder is working and in each different test case we want to provide different value and check the result. In order to be able to call .BindModel we need two parameters HttpActionContext and ModelBindingContext. HttpActionContext can be completely mocked. We are using NSubstitute as mocking framework. ModelBindingContext has a property called ValueProvider which obviously provide value of the model. So we create a ModelBindingContext and set the ValueProvider to a mocked version and keep the reference to be able to change value for each test.

Following is the complete code for setting up the model binder and testing that.

In each unit test we set up the _valueProvider mock to return expected sortExpression and then call the method and assert on expected values.

Simple!

Uncategorized comments edit

I have been in IT industry for fifteen years and for last three and half years I been in consulting firm. I really like the type of work I usually do as a consultant. Issues that we have to deal with are usually different and more challenging. Systems we have to build requires more focus and special architecture and extra care. In this industry I do meet new people and a really like to pair with others, teach and of-course learn new things.

Last week, I started working for a new company called Readify. Programmers in Australia, specially Microsoft stack programmers, would probably know Readify. But for those who don’t know, Readify is the best Microsoft Consulting company in Australia which has offices across major states in Australia (NSW, VIC, QLD, Perth and SA). I’ve been interested to work for Reaidfy since I came to Australia. But it happened for me after four and half years. Many thanks to my good friend Hadi Eskandari who mentored me during last year when I was studying so hard to get through.

Anyway, If you want a challenging workplace, pairing with smart and knowledgeable developers and using bleeding edge technologies, probably Readify is one of places you might want to consider to work in Australia. During past few years great developers have been working for Readify. To name a couple of them, Damien Edwards who is currently program manager at Microsoft at ASP.net team and Paul Stovell creator of famous deployment tool called Octopus Deploy. And many others who still work for Readify.

Its an opportunity to work in challenging environment with high quality expectation. When a client choose Readify, most likely there is a challenging issue or project. I as a consultant have the opportunity to work with highly skilled and smart people in different project.

Now, let me tell you about first impressions I’ve got since I’ve started with them. I signed the contract nearly six weeks ago and immediately a couple of days after, I got access to my corporate email and other documents so I got myself familiarized with the processes and introduced myself to the team before actually starting new job. Everything was surprisingly well organised and open.

I got my allowance to buy gears and get ready for my new position at Readify. The allowance is enough to buy a decent ultrabook or mac book pro which gets renewed every two years. I decided to buy a Surface pro 3 which I will blog about that later. Anyway, I had a chance to get everything ready before the very first day.

Day one when I went to Readify’s nice office in the city everybody were welcoming to me and helping me to get started. There is is buddy system at Readify which helps new Readifarian get through all induction stuff faster. My buddy Jorge helped me to get through all the stuff quickly. I had a chance to have a chat with one of the principal consultants (Richard Banks). Although principal consultants are busy but they are available to help developers and other consultants. Basically we can reach them quite easily. During past week I had a change to meet other principal consultants and senior consultant and catch up with them.

At Readify everybody gets number of days annually to work on professional development, we can self study new technologies, prepare for exam, write an article or get ready for presentation. First few days I had a chance to look at new interesting changes in mobile area with Xamarin products. Xamarin has gained a lot of attention recently especially in enterprise. I will write more about them later.

So far it has been great experience working at Readify and I have just started my first gig this week which is going to be awesome.

Stay tuned I’ll blog more to share technical and non-technical stuff.

Blog comments edit

AutoMapper is a great library helps developer to almost get rid of left hand right hand assignment between different types. In real world C# .net applications there are lots of scenarios developer wants to map different types of objects to each other. Normally it happens in system boundaries, like between UI and services or between ViewModel and Model. Without AutoMapper you have to do it for all properties every time you want to map to objects. This task is cumbersome, hard to test and bug prone. Automapper with does this for you with minimum cost. It has its own conventiones to facilitate type mapping. On top of built in defaults you as developer can teach Automapper new tricks.

You can find lots of blogs and articles of how to use AutoMapper. In fact this, this and this can help you.

Following is also an example of rather complex mapping between Source and Destination types.

In this example I’ve used xUnit to test and AutoFixture to generate random data. Then in constructor of test class I have created mapping by using static method Mapper.CreateMap. this creates mapping at application domain context and you just need to set this up once and will be available across your application. After that in our test we created a source type and then mapped that to destination type finally checked the destination properties.

This post is not about normal scenario of using Automapper. When you are working with database you’d normally use repositories (arguably you might not need repository). in simple case of repository you would have following code

This is a simple interface for repository. Implementation of this doesn’t even need mapping (you might do the mapping in other layers, though). However if we want to separate domain model from persistence model we could introduce another interface like following:

In this interface we have to generic types TI and TO. TI is our domain model and TO is our persistence model. For example we pass Source object to Add method but repository implementation would save that in Destination model (See bellow example as Add implementation)

This is possible if we map Source object to Destination object. Automapper does that for us.

Now, the real issue is when we want to implement Find method which accepts Expression<Func<Source, bool. Mapping an expression of func of type source to expression of func of type destination is more difficult as Jimmy Bogard main author of Automapper stated in this mailing list. Anyway, with a quick search I’ve found this question where somebody asked in stackoverflow about AutoMapper for Func’s between selector types. Person how answered this question updated the answer later with answer to Expression mapping with Automapper. The first class which does this magic is an implementation of ExpressionVisitor. This class can traverese an expression tree and replace a single parameter with an arbitrary expression

The second piece that comes into play is an extension method for Expression<Func<Z,Y>> called “Compose”  and it returns a new Expression<Func<X, Y>>.

With this extension method and ExpressionVisitor Class I can complete the repository class for. This repository class is implementing SQL Serve implementation. Later on we will implement another repository class for MongoDB as well.

This is the Entity Framework implementation of our repository. Interesting point is “Find” Method which is taking advantage of Mapper.Engine.CreateMapExpression and Compose extension method. CreateMapExpression in AutoMapper creates an expression for mapping between Source to Destination. In the next line we use the mapper expression and pass this to Compose extension method to build a new expression. And finally we call Where method on Users DBSet and it returns IQueriable of type Destination. I have written a Unit Test to test this.

This test successfully passes. As you see I used Source type to add records and query the records. The repository maps the add part to destination and also map predicates expression.

When I debug the code I can see entity framework successfully constructed the query. This is using Destination type.

Well this is really good, although there is a down side to this approach. This is good and pretty mych abstracted the Destination class and I just work with Source type. However, if I want to join results of two different IQueriables I have to mention the property name of the Model.

Anyway it worked reasonably good with SQL server and EntityFramework. Let see if it works with MongoDB. In order to connect to MongoDB I use mongo csharp driver and on top of that I’m using MongoRepository. Now let see if the same scenario works for Repository Implemented for MongoDb.

In following code I have implemented the IRepository for MongoDB.

The target is to test Find(Expression<Func<Source, bool>> predicate) and see if it works, however, I have added another Find with Find(Expression<Func<Destination, bool>> predicate) signature and I will describe why I added that method.

Now the unit test to test this implementation.

This test fails!. This complains about full name not having serialization information

Additional information: Unable to determine the serialization information for the expression: <MemberInitExpression>.FullName.

This approach doesn’t work for MongoDB (probably Mongo CSharp driver could not handle that). I have written another method that accepts Expression<Func<Destination, bool>> predicate, If you uncomment this method call and comment the other in unit test it’ll work.

Having looked at transformed expression shows that this approach does not completely re-write the expression.

This is just wrapper around another lambda that does the mapping. Interestingly EntityFramework handles that very well but MongoDB CSharp Driver not.

On option it to find a way to rewrite the whole expression based on the mapping configuration. But as Jimmy mentioned it could be quite hard to implement.

You can find the full implementation and tests here

Blog comments edit

I think developers are a bit confused about the concept of ValueTypes and Reference Type. Often I hear that all primitive data types and value types are in stack. First of all it is thread’s stack and it is not a single stack for application. Secondly, when we say value types are in stack it doesn’t include field members of the class. Only method parameters and local variable which are value type will be in the thread’s stat. Field members, even if they are value type, will be in heap. Consider following example:


using System;

namespace ClassLibrary
{
    public class Foo
    {
	public int number = 0;
        public int Bar(int x, int y)
        {
         	int sum = x + y + number
	 	return sum;
        }
    }
}

In this example, only x, y, sum and return value are in thread’s stack and number variable will be held in heap as part of object instance and is accessible using this keyword (which compiler let you omit that). In other word when we say object instance is created in the heap, what does really stored there? Field members are object state that needs to be stored in object instance.

Blog comments edit

In .net world you can choose your language and write your application with best language which matches your requirements. Different languages has different paradigm. For example C# started with static/strongly type paragoge  but over years it has been evolved and now it does support functional programming as well as dynamic. There are many other languages like F#, Visual Basic and fortran.

It is compiler responsibility to generate assembly with proper intermediate language so that CLR (Common Language Runtime) would be able to generate native code (using JIT) and run at run time. Each compilers support subset if intermediate language and provide its flavour using syntactic sugars in the language.

.Net Languages

CLR allows language integration as long as written code comply with Common Language Specification. It means because of differences between languages, if you want to use types generated by other languages, you need to use certain feature of language that are guaranteed to be available in other languages. CLS is the lowest common denominator of language features provided by Microsoft.

However, today I don’t want to highlight CLS, instead I want to mentions that Intermediate Language in some cases has more features which languages like C# didn’t bother to implement.

For example we all know about access modifiers in C#. There is public, private, internal and protected

Access Modifiers Description
public *public access is the most permissive access level. There is no restrictions on accessing public members*
private *private access is the least permissive access level, private members are accessible only within the body of the class or the struct in which they are declared*
internal *internal types or members are accessible only within files in the same assembly*
protected *A protected member is accessible within its class and by derived class instances*
protected internal visible to derived classes and those of the same assembly

 

OK, now lets have a look on access modifiers in IL

IL Access Modifier Description C# equivalent
Private The member is accessible only by other members in the same class or struct private
Family The member is accessible by derived types. protected
famandassem The member is accessible by derived types, but only if the derived type is defined in the same assembly. N/A
Assembly The member is accessible by any code in the same assembly internal
famorassem The member is accessible by derived types in any assembly and also by any types within same assembly protected internal
Public The member is accessible by any code in any assembly public

 

As you might have noticed there is no C# equivalent for family or assembly although IL has this keyword. there is not such a thing in VB.Net as well. Now lets have a closer look on a simple sample and generated IL code.

Assume we have two simple project in a solution. A Console Application and a Class Library which console application referenced that. In the Class Library we have a simple class called Super and in console application, beside Program class we have a class derived from Super class called Sub. Lets have a look on their codes.

 

Super class source code


using System;

namespace ClassLibrary
{
    public class Super
    {
        protected internal void Foo()
        {
            Console.WriteLine("Foo");
        }

        internal void Method()
        {
            
        }
    }
}

Other class in ClassLibrary Project


namespace ClassLibrary
{
    public class Other
    {
        public void Test()
        {
            var super = new Super();
            super.Foo();
        }
        
    }
}

Sub class in ConsoleApplication


using System;
using ClassLibrary;

namespace ConsoleApplication
{
    public class Sub : Super
    {
        public void Bar()
        {
            Foo();
            Console.WriteLine("Bar");
        }
    }
}

Program.cs class in ConsoleApplication


using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main()
        {
            var sub = new Sub();
            sub.Bar();
            Console.ReadLine();
            
        }
    }
}

Sub class simply calls Foo method which is defined as “protected internal” which in C# means family *or *assembly in IL. If you build and run application you’ll see that Sub class successfully accesses because although it is not in the same assembly but But sub is actually derived from Super class. the output will be


Foo 
Bar

Cool, now let mess around with the IL and see that would happen if we change that.

If you want to dump the IL of an assembly you can simply open a Visual Studio Command and then go to the folder your assembly exist and run ildasm with following parameters


ildasm ConsoleApplication.exe /out:ConsoleApplication.il

ildasm ClassLibrary.dll /out:ClassLibrary.il

Now, you can open ClassLibrary.il and have a look into generated code. Actually it is a bit long so I just copied part that I’m interested in which is Foo method


  .method famandassem hidebysig instance void 
          Foo() cil managed
  {
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      &quot;Foo&quot;
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  } // end of method Super::Foo

You see that protected internal compiled to famorassem. What would happen if we change this to famandassem and assemble this IL again? Answer is CLR will prevent calling this method and will raise MethodAccessException exception when we call this from console application. But let put this into action and actually test this. So, change the famorassem to famandassem and save the file and use ilasm.exe from Visual Studio Command to assemble this code again. Before assembling this you can delete current ClassLibrary.Dll. To assemble use following command parameters:


ilasm ClassLibrary.il /out:ClassLibrary.dll /dll

If you get Operation completed successfully at the end new class library is generated. If you run ConsoleApplication.exe you’ll get following exception because of violating the access level defined in the IL


Unhandled Exception: System.MethodAccessException: Attempt by method 'ConsoleApp
lication.Sub.Bar()' to access method 'ClassLibrary.Super.Foo()' failed.
   at ConsoleApplication.Sub.Bar() in f:\Users\ara\Documents\Visual Studio 2013\
Projects\ConsoleApplication3\ConsoleApplication3\Sub.cs:line 10
   at ConsoleApplication.Program.Main() in f:\Users\ara\Documents\Visual Studio
2013\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:line 10

famandassem means that only derived class within same assembly will have access to that member. Just for the sake of testing lets Super to the ConsoleApplication and see if it works.

Open ClassLIbrary.il in a text editor. Copy following IL code which is Super class il code


// =============== CLASS MEMBERS DECLARATION ===================

.class public auto ansi beforefieldinit ClassLibrary.Other
       extends [mscorlib]System.Object
{
  .method public hidebysig instance void 
          Test() cil managed
  {
    // Code size       15 (0xf)
    .maxstack  1
    .locals init ([0] class ClassLibrary.Super super)
    IL_0000:  nop
    IL_0001:  newobj     instance void ClassLibrary.Super::.ctor()
    IL_0006:  stloc.0
    IL_0007:  ldloc.0
    IL_0008:  callvirt   instance void ClassLibrary.Super::Foo()
    IL_000d:  nop
    IL_000e:  ret
  } // end of method Other::Test

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       7 (0x7)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method Other::.ctor

} // end of class ClassLibrary.Other

.class public auto ansi beforefieldinit ClassLibrary.Super
       extends [mscorlib]System.Object
{
  .method famandassem hidebysig instance void 
          Foo() cil managed
  {
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      "Foo"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  } // end of method Super::Foo

  .method assembly hidebysig instance void 
          Method() cil managed
  {
    // Code size       2 (0x2)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ret
  } // end of method Super::Method

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       7 (0x7)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method Super::.ctor

} // end of class ClassLibrary.Super


// =============================================================

Now open ConsoleApplication.il and paste this code at the end after end of Class ConsoleApplication.Sub.

We need to do one more thing and get rid off reference to ClassLibrary.il which we don’t need anymore. So right in the beginning there is some code for that. Delete that piece of code and save the file.


.assembly extern ClassLibrary
{
  .ver 1:0:0:0
}

One more thing to do and it is replacing all [ClassLibrary] with empty string.

Delete console application and assemble the il to make new ConsoleApplication.exe using following command


ilasm ConsoleApplication.il /exe /out:ConsoleApplication.exe

Now we have new ConsoleApplication which doesn’t have reference to ClassLibrary. Run ConsoleApplication.exe you see it runs successfully.