Friday, April 26, 2013

Impress your colleagues with your knowledge about... the checked and unchecked keyword

Sometimes when working with C# you discover some hidden gems. Some of them very useful, other ones a little bit harder to find a good way to benefit from their functionality. One of those hidden gems that I discovered some days ago is the checked and unchecked keyword.
From MSDN:
C# statements can execute in either checked or unchecked context. In a checked context, arithmetic overflow raises an exception. In an unchecked context, arithmetic overflow is ignored and the result is truncated.
If neither checked nor unchecked is specified, the default context depends on external factors such as compiler options.
An example, by default if you go above the MaxValue of an integer, the runtime will start again from the MinValue allowing you to do an overflow. This is the equivalent of the unchecked mode:
If you don’t want overflow to happen, you can start using the checked keyword: 

So use checked when you don't want accidental overflow / wrap-around to be a problem, and would rather see an exception.
unchecked explicitly sets the mode to allow overflow

The default is unchecked unless you tell the compiler otherwise(through code or a compiler switch /checked).

Thursday, April 25, 2013

BlueStacks: Run all your favorite Android apps on PC and Mac

Are you interested in running all your Android apps on a PC or Mac? Try the BlueStacks App Player. (They even have an optimized version specifically build for Windows 8.)


Wednesday, April 24, 2013

Creating a custom user type in Nhibernate

NHibernate has the concept of a User Type. It allows you to specify how a custom type should be mapped between your object model and the database.

An example of an out-of-the-box User Type is the YesNo type. This type allows you to map (“Y”/”N”) values in your database to boolean values in your application. To use this in your application you only need to specify a type in your mapping file:

<property name="IsActive" type="YesNo"/>

For a project I’m working on, I had a similar requirement, but because the application was in Dutch I had to use “J”/”N” instead of “Y”/”N”.

So let’s build our own User Type to achieve this. The nice thing is that I don’t have to start from scratch but can extend one of the existing User Types:

To use this type in our application, we have to change the mapping to:

<property name="IsActive" type="NHibernate.JaNeeType,Sample.NHibernate"/>

Tuesday, April 23, 2013

Xamarin.iOS: solving the “codepage 1252 not supported” exception

When creating an application using Xamarin.iOS(also known as MonoTouch), we stumbled over following exception message when deserializing some data:

“codepage 1252 not supported”

We solved this by executing the following steps:

  • Go to the Project Settings of your project in Xamarin Studio.
  • Go to the Build Tab and select the iOS Build option.
  • Check the west checkbox in the Internationalization codesets list.


Monday, April 22, 2013

Having a hard time selecting across-platform mobile framework? PropertyCross is here to help you.

Introduction from the website:

Developers are now finding themselves having to author applications for a diverse range of mobile platforms (iOS, Android, Windows Phone, …), each of which have their own ‘native’ development languages, tools and environment.

There is an ever growing list of cross-platform frameworks that allow you to minimize the cost and effort of developing mobile apps, but which to choose?

To help solve this problem PropertyCross presents a non-trivial application, for searching UK property listings, developed using a range of cross-platform technologies and frameworks. Our aim is to provide developers with a practical insight into the strengths and weaknesses of each framework.

This project was heavily inspired by TodoMVC, which allows the comparison of JavaScript frameworks.


PropertyCross implements the same application over and over again using the following frameworks:

This gives you an easy way to compare the multiple frameworks on a real-life project.

You can download or fork the application on GitHub.

Friday, April 19, 2013

Looking for the right template engine for your web project?

With the increased interest in Single Page Applications(SPA), the usage of template engines become more and more important.
A template engine will take a preformatted client side or server side template(based on html or any other syntax) and transform it to usable html that can be added to your web page. (A good article to get started about template engines is the following:
The only problem is that every day, a new template engine appears. To help you pick the right tool for the right job, you can use the Template-Engine-Chooser:

Remark: I noticed that the tool didn't work on Internet Explorer.

Thursday, April 18, 2013

Disable browser cache for an ASP.NET MVC application

Sometimes a problem doesn’t have to be hard to fix…

Last week I was looking to disable browser caching for a specific action method on an ASP.NET MVC controller. There are multiple ways to do this. I decided to take the ActionFilter attribute road:

Wednesday, April 17, 2013

Plato: a JavaScript source code visualization, static analysis, and complexity tool

To improve the quality of my JavaScript code, I’m always looking at good tools (like JsLint) that can help me writer better code and more maintainable code.

Last week I discovered Plato,a JavaScript source code visualization, static analysis, and complexity tool.

This node.js module analyses your JavaScript code and gives you an indication about:

  • The maintainability of your code
  • Lines of code
  • Estimated errors in implementation(based on the Halstead complexity measures)
  • Lint errors(based on the results of JsHint)

Get started

  • Download and install node.js from the node.js website(
  • Start a command prompt
  • Install plato as a global module through the npm package manager: npm install -g plato


  • Browse to the folder where you want to run Plato.
  • Call Plato and specify to do a recursive scan on the scripts folder:  plato -r -d reports scripts
  • Go to the reports folder and open the index.html page to see the results(here you see an example run on Marionette.js):


Tuesday, April 16, 2013

Error in jQuery Validation after upgrading to jQuery 1.9

After upgrading my ASP.NET MVC 4 project to jQuery 1.9, I started to get into trouble the moment I called jquery.validate.js.


This is the error message I got:

0x800a138f - JavaScript runtime error: Unable to get property 'call' of undefined or null reference

How can you fix this issue?

It seems that the introduction of jQuery 1.9 breaks the compatibility with the default jQuery.validation library(that is part of the ASP.NET MVC template). The guys of the jQuery.validation library are aware of the issue and already fixed in a new release of their library available on NuGet:

So if you upgrade your web application to jQuery 1.9, don’t forget to also upgrade jQuery.validation to at least version 1.11.0.

Monday, April 15, 2013

The essential Git cheat sheet

Git is a great distributed source control system and with the introduction of Update 2 for Visual Studio 2012, you no longer have an excuse to not start using it.


However starting with Git can be a daunting task, therefore the guys at DZone created a free to download cheat sheet containing the list of the most important Git commands end their explanation.

Go and download it here(you’ll have to register first):

Friday, April 12, 2013

ASP.NET MVC: SCRIPT1004: Expected ‘;’ after upgrading to jQuery 1.9

After upgrading our ASP.NET MVC 4 project to jQuery 1.9, our application started to fail with the following error message:
This is caused by the fact that starting from jQuery 1.9 a map file is added to the NuGet package. In my BundleConfig.cs I had the following:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
The wildcard was being used to get the latest version of jQuery, however, this caused the map file to be included as well.

To solve this update the BundleConfig.cs to:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(

Thursday, April 11, 2013

WCF Data Service: The type initializer for 'System.Data.Services.Client.TypeSystem' threw an exception.

In an application, we are consuming an OData feed. In development, this worked without any issue but the moment we deployed the application to our test environment, it started to fail with the following exception:

The type initializer for 'System.Data.Services.Client.TypeSystem' threw an exception.

Looking in the logs on the server, we found the following stacktrace:

Sync.exe Information: 0 : Error occured during synchronization: The type initializer for 'System.Data.Services.Client.TypeSystem' threw an exception.
Sync.exe Information: 0 : Stacktrace:    at System.Data.Services.Client.TypeSystem.IsPrivate(PropertyInfo pi)
   at System.Data.Services.Client.ResourceBinder.PatternRules.MatchNonPrivateReadableProperty(Expression e, PropertyInfo& propInfo, Expression& target)
   at System.Data.Services.Client.ResourceBinder.VisitMemberAccess(MemberExpression m)
   at System.Data.Services.Client.ALinqExpressionVisitor.Visit(Expression exp)
   at System.Data.Services.Client.DataServiceALinqExpressionVisitor.Visit(Expression exp)
   at System.Data.Services.Client.ALinqExpressionVisitor.VisitBinary(BinaryExpression b)
   at System.Data.Services.Client.ResourceBinder.VisitBinary(BinaryExpression b)
   at System.Data.Services.Client.ALinqExpressionVisitor.Visit(Expression exp)
   at System.Data.Services.Client.DataServiceALinqExpressionVisitor.Visit(Expression exp)
   at System.Data.Services.Client.ALinqExpressionVisitor.VisitLambda(LambdaExpression lambda)
   at System.Data.Services.Client.ALinqExpressionVisitor.Visit(Expression exp)
   at System.Data.Services.Client.DataServiceALinqExpressionVisitor.Visit(Expression exp)
   at System.Data.Services.Client.ALinqExpressionVisitor.VisitUnary(UnaryExpression u)
   at System.Data.Services.Client.ALinqExpressionVisitor.Visit(Expression exp)
   at System.Data.Services.Client.DataServiceALinqExpressionVisitor.Visit(Expression exp)
   at System.Data.Services.Client.ALinqExpressionVisitor.VisitExpressionList(ReadOnlyCollection`1 original)
   at System.Data.Services.Client.ALinqExpressionVisitor.VisitMethodCall(MethodCallExpression m)
   at System.Data.Services.Client.ResourceBinder.VisitMethodCall(MethodCallExpression mce)
   at System.Data.Services.Client.ALinqExpressionVisitor.Visit(Expression exp)
   at System.Data.Services.Client.DataServiceALinqExpressionVisitor.Visit(Expression exp)
   at System.Data.Services.Client.ResourceBinder.AnalyzeProjection(MethodCallExpression mce, SequenceMethod sequenceMethod, Expression& e)
   at System.Data.Services.Client.ResourceBinder.VisitMethodCall(MethodCallExpression mce)
   at System.Data.Services.Client.ALinqExpressionVisitor.Visit(Expression exp)
   at System.Data.Services.Client.DataServiceALinqExpressionVisitor.Visit(Expression exp)
   at System.Data.Services.Client.ResourceBinder.Bind(Expression e, DataServiceContext context)
   at System.Data.Services.Client.DataServiceQueryProvider.Translate(Expression e)
   at System.Data.Services.Client.DataServiceQuery`1.Execute()
   at System.Data.Services.Client.DataServiceQuery`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Sync.Synchronizer.GetChangedPortfolios(DateTime lastSyncDate)
   at Sync.Synchronizer.Start(DateTime lastSyncDate)
   at Sync.Program.StartSynchronization(DateTime lastSyncDate)
   at Sync.Program.Main(String[] args)

There are 2 things you need to check if you see this error:

  1. Are all required assemblies copied to the server? (In our case Copy Local was set to false for some assemblies). You’ll need the following assemblies to be copied:
    • System.Spatial.dll
    • Microsoft.Data.Edm.dll
    • Microsoft.Data.OData.dll
    • Microsoft.Data.Services.dll
    • Microsoft.Data.Services.Client.dll
  2. Do all these assemblies have the same version number? (In our case, one project contained a newer version of System.Spatial.dll)

Wednesday, April 10, 2013

Secure your cookies

Troy Hunt did a great blog post about how and why you should secure your cookies.

They are 2 important lessons you can learn from this post:

  • Lesson 1: if you don’t need to read the cookie value on the client, disable this function. In ASP.NET you can set this as the default for all cookies through the web.config:
    • <httpCookies httpOnlyCookies="true" />
  • Lesson 2: allow your cookies to be send only over HTTPS. And again this can be set in the web.config in ASP.NET :
    • <httpCookies requireSSL="true" />

More info:

Tuesday, April 9, 2013

Edge.js: Run C# code from node.js

Edge.js allows you to run .NET and node.js code in one process. You can call .NET functions from node.js and node.js functions from .NET. Edge.js takes care of marshaling data between CLR and V8. Edge.js also reconciles threading models of single threaded V8 and multi-threaded CLR. Edge.js ensures correct lifetime of objects on V8 and CLR heaps. The CLR code can be pre-compiled or specified as C# or Python source: edge.js can execute C# or IronPython script at runtime. Edge allows CLR languages other than C# or IronPython to be plugged in.

More information here:

To get started:

  • Download and install node.js from the node.js website(
  • Start a command prompt
  • Browse to the location where you want to run node
  • Install edge through the npm package manager: npm install edge


  • Create a hellocsharp.js file in the current folder and add the following code:
  • Run the program: node hellocsharp.js

Monday, April 8, 2013

Windows Azure ACS: Get ACS Namespace and Management Key

When you want to integrate the Windows Azure Access Control Service(ACS) into your application(through the Identity and Access option in Visual Studio), you’ll need both the ACS Namespace value and the Management Key. The problem is that I always forget where I can get these values. There are multiple settings stored at different locations.


To find these values, you don’t need to go to the Certificates and keys section under Service Settings (available on the old Windows Azure Portal). Instead browse to Management Service under Administration.

The ACS Namespace field is the unique string you chose as your namespace(https://{MYNAMESPACE}

The Management Key can be found when clicking on the Symmetric Key from the Credentials list and copying the key from the Edit Management Credential screen.


Friday, April 5, 2013

Windows 8 application returns “Unable to connect to the remote server” when sending requests to an internal test server

After weeks of testing, we were finally ready to release a first version of our Windows 8 app to our key user. So I created a package and copied all the files on an USB stick to ‘side load’ the application on his machine.  After running the Powershell installation script, installing the developer certificate,  the moment was finally there. The application started and the main hub was shown.

However the moment, the user started to click around and HttpWebRequests were send out to our backend services, the application failed with the following error message:

Unable to connect to the remote server

System.Exception {System.Net.WebException}

An attempt was made to access a socket in a way forbidden by its access permissions

We were clueless why it failed. We tested the application for weeks without any issue. The only difference is that we hosted the backend API somewhere else. Could this cause the issue? We were using a DNS that was mapped differently depending if you connect internally or externally.

The first thing we tried to do, was to add Fiddler into the mix to see what was going on. This made the experience even stranger because suddenly all web calls started to succeed?!            

In a desperate attempt, I opened up the Windows 8 manifest and added the capability for Private Networks:


The Private Networks (Client & Server capability provides inbound and outbound access to home and work networks through the firewall. This capability is typically used for games that communicate across the local area network (LAN), and for apps that share data across a variety of local devices. If your app specifies musicLibrary, picturesLibrary, or videosLibrary, you don't need to use this capability to access the corresponding library in a Home Group. Inbound access to critical ports is always blocked. The capability is written in the AppxManifest.xml file as the following code shows:

Afterwards the application worked fine.

Anyone with more insight who can explain why this solved the issue? I’m guessing this is required because the DNS is resolved to an internal network address…

Remark: To validate if my guess was correct, I removed the capability again and this time connected from outside our company network. I started the application and everything was working as expected.

Thursday, April 4, 2013

OData: attach a client certificate through code when connecting to an OData service

At a customer, we had to use a 3th party OData service. Using OData feeds in .NET is simple, but this one was a little bit harder to use because it was secured using a client certificate.

So how can we tell OData to include the certificate when connecting to the service?
  • Open or create a Visual Studio project where you want to use the OData feed.
  • Add a service reference to the OData feed using the Visual Studio Add Service Reference option. If the metadata url is also secured, you can use Fiddler to temporarily work around the security.
  • A reference is generated for you and added to the Visual Studio project.
  • Inside this reference you’ll find a partial class containing a DataServiceContext object:
  • To include our client certificate, we can extend the generated class with some extra code. Therefore add a partial.cs file in the same namespace:
  • Now we can create the DataServiceContext and include the certificate using the property we just added:

Wednesday, April 3, 2013

OData: attach a client certificate through Fiddler when connecting to an OData service

At a customer, we had to use a 3th party OData service. Using OData feeds in .NET is simple, but this one was a little bit harder to use because it was secured using a client certificate.

We first wanted to browse through the OData feed using LinqPad but we couldn’t find a way to configure LinqPad to add the certificate to each request.

Use Fiddler to include a client certificate with each request

We decided to follow a different route and use Fiddler to include the certificate for us. Fiddler is a web debugging proxy that can intercept all the HTTP traffic we are doing on our system.

Here are the steps you need to take:

  • Get the client certificate.
  • If you have a .pfx file including the private key, extract it and install the certificate in your personal certificate store.
  • Download and install Fiddler in case you didn’t have it.
  • Start Fiddler.
  • Go to Tools –> Fiddler Options
  • Go to the HTTPS Tab and check the checkbox next to Decrypt HTTPS traffic.
  • Fiddler will ask you to install a new root certificate, click Yes if asked for confirmation. (Installing this certificate implies a security risk, so remove it after you’re done)
  • Go to the C:\Users\{UserName}\Documents\Fiddler2 folder.
  • Copy the client certificate to this folder and rename it to ClientCertificate.cer
  • That’s it.

If you now try to connect to your OData service, Fiddler will capture the traffic, attach the client certificate and forward the request to the service.

Tuesday, April 2, 2013

TFS 2012 Update 1 issue: Assigned to field is ‘Unknown’ in all reports

After upgrading from Team Foundation Server 20120 to 2012, everything looked OK. However when we looked at the reports, we saw that all user names were gone and the only value we saw was ‘Unknown’.  I took a look at the Team Foundation Server database, but all data was there as expected. So clearly something went wrong, when building the data warehouse.

Our first attempt to fix it, was just doing a full rebuild of the warehouse but no luck. The issue was still there.

I started to look around on the Internet and discovered the following update: Update to Team Foundation Server Update 1 (KB2803625)

In the list of issues this update fixes, I discovered point 5, which was exactly the issue we were having:

  1. Collections that are attached to a server that is running TFS 2012 Update 1 may lose permissions
  2. Group scopes may incorrectly cause permission errors
  3. Severe decrease in performance after TFS 2012 Update 1 is installed
  4. Identity sync jobs may fail repeatedly
  5. Warehouse is not updated correctly, or fields that represent a person are not filled
  6. Users can see names of collections of which they are not a member
  7. You cannot remove a user or a group after you attach a collection to a TFS 2012 Update 1 server
  8. You cannot view artifacts that reference an identity that is no longer a part of a collection

So I downloaded and installed the update on the TFS application tier.

Remark: After installing the patch, you will need to manually initiate a rebuild of the warehouse in order to correctly populate the fields which reference people for the latest revisions of work items.

After the rebuild, the issue was gone and the data was finally there…