Short solution for short problems

API.NET: Web API How to handle space or %20 in URL route

Failed to load resource: the server responded with a status of 404 (Not Found)

accounts.bdo.be/:1 Failed to load ...Accounts/Lookup/A.D.V.%20/maxrows/10

This is what I got when trying to call a web API. The space, even encoded was giving trouble. When you have this problem, do not look to far, do not start rewriting the url. 

Just add this to your config file in the Web API:

    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.5.2" relaxedUrlToFileSystemMapping="true" />

More info on this here:


Azure web apps and PDF sharp to generate pdf. (1.3 -> 1.5)

I was using PDF sharp 1.3 to generate PDF via my web api. I had some challenges but generally speaking it went fine. After some good tests I decided to publish it to Azure. Then things got strange. I got a 500 internal server error. After some investigation, this was the error:

font data could not retrieved

Well, this was a pain. Locally this worked fine, but not in azure. I found a nice explanation here, but no solution.

This is what is says:

Azure App Service (aka Azure Websites) enforces a number of more restrictive security constraints than a cloud service or IaaS (VMs). One of the things that is blocked is access to much of the GDI API surface area, which includes some font manipulation. As other folks have noted, if the same code works on a plain IaaS VM, a cloud service, or even a local desktop/laptop, then the problem you are running into is a hard block on the underlying GDI calls.

So the problem is that in web apps you cannot acces the fonts. the solution is to add font as a resource to your application and use the IFormatter interface of PDF sharp 1.5. 

Oh no, this means migrating the code and rewriting. Forntunately this was NOT the case. I looked for the nuget package (it's a beta vesion, so you need to include pre releases) 

I only had to remove the old reference to the charting dll and that was it. 

Now I could start to make a class that implements the IFormatter interface:

using PdfSharp.Fonts;
using System;
using System.IO;
using System.Reflection;
namespace spib.print
    public class SPIBFontresolver : IFontResolver

In my case I'm using the Verdana font. So where to find the fonts. Thats easy. Go to C:\Windows\Fonts\ and look for the fonts you want to use. copy them and paste them in a folder in your project.

I placed the fonts in a sub folder called font directly in my project. then I added them as embedded resource:

Here you see the project structure with the files:

Next we can complete the implementation of the interface. 

Implement the interface and complete. Here how I completed it in my case for the Verdana font:

public class SPIBFontresolver : IFontResolver
    public byte[] GetFont(string faceName)
        switch (faceName)
            case "Verdana#":
                return LoadFontData("spib.print.font.verdana.ttf"); ;
            case "Verdana#b":
                return LoadFontData("spib.print.font.verdanab.ttf"); ;
            case "Verdana#i":
                return LoadFontData("spib.print.font.verdanai.ttf");
            case "Verdana#bi":
                return LoadFontData("spib.print.font.verdanaz.ttf");
        return null;
    /// <summary>
    /// Returns the specified font from an embedded resource.
    /// </summary>
    private byte[] LoadFontData(string name)
        var assembly = Assembly.GetExecutingAssembly();
        // Test code to find the names of embedded fonts - put a watch on "ourResources"
        //var ourResources = assembly.GetManifestResourceNames();
        using (Stream stream = assembly.GetManifestResourceStream(name))
            if (stream == null)
                throw new ArgumentException("No resource with name " + name);
            int count = (int)stream.Length;
            byte[] data = new byte[count];
            stream.Read(data, 0, count);
            return data;
    public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
        // Ignore case of font names.
        var name = familyName.ToLower().TrimEnd('#');
        // Deal with the fonts we know.
        switch (name)
            case "verdana":
                if (isBold)
                    if (isItalic)
                        return new FontResolverInfo("Verdana#bi");
                    return new FontResolverInfo("Verdana#b");
                if (isItalic)
                    return new FontResolverInfo("Verdana#i");
                return new FontResolverInfo("Verdana#");
        // We pass all other font requests to the default handler.
        // When running on a web server without sufficient permission, you can return a default font at this stage.
        return PlatformFontResolver.ResolveTypeface(familyName, isBold, isItalic);

Last, you will need to add the formatter to your applcation where you are using it.

public PrintOffer()
    GlobalFontSettings.FontResolver = new SPIBFontresolver();

And now it works. So with some minimum easy code, you can add private fonts to Azure web apps. I tested it and got a desired result!

I got a good help here: https://stackoverflow.com/questions/27606877/pdfsharp-private-fonts-for-azure-1-50

IIS copy files to file share in API or web site

Recently, I needed to copy some files from a database to a file share in a .Net web API that runs on an IIS. First I was trying to run the application pool using a domain user, but I couldn't get it working. The application pool keeps stopping, even if the username and password is correct and the local policies are correct.

So I found another better way to do it. In stead of giving the user permissions on the file share. I gave the server permissions on the file share. Then I ran the application pool under the NetworkService and it works.

On the file share under security, put DOMAIN\SERVERNAME and give modify rights (do not forget to include computers in de AD search). Thats it. Now the server can write to this specific location, no harm can be done. In fact, giving a user permissions can be more dangerous, because he can access it anywhere.

ASP.NET: app_offline.htm takes your site offline

When deploying to a site, you want to show a nice message like, working on the site untill 12 PM or something.
You can do this several ways, one way is to add to the deploy script a drop of the file app_offline.htm into the root of your site. This will send all incoming request to this file. 
When the deploy is finished, simply remove it again!

IIS: What triggers recycle of a website in IIS?

A colleague and me where thinking about this, because we were copying files to the root directory of the web site. But no worries, this doesn't trigger a recycle. What does trigger a recycle?

Trigger Immediate Recycle

  • Web.config changes
  • Machine.config changes
  • Global.asax changes
  • Bin directory changes
  • App_Code changes

Tech: My Techorama 2015 review

1.           ASP.NET 5

1.           ASP.NET 5

A session on the new ASP.NET 5. A lot of overlapping information. New features of visual studio 2015. This session also confirms that WEB API is the way to go in the future.

Here is a summary of the foundational improvements:

  • New light-weight and modular HTTP request pipeline
  • Ability to host on IIS or self-host in your own process
    • Showed in the session, you can host is from command line on USB stick.
  • Built on .NET Core, which supports true side-by-side app versioning
  • Ships entirely as NuGet packages
    • Not part of the System.Web.dll anymore.
  • Integrated support for creating and using NuGet packages
  • Single aligned web stack for Web UI and Web APIs
  • Cloud-ready environment-based configuration
  • Built-in support for dependency injection
  • New tooling that simplifies modern Web development
  • Build and run cross-platform ASP.NET apps on Windows, Mac and Linux
  • Open source and community focused


2.           The internet of your things (Iot)

Mainly about Azure and the capabilities to host applications on Azure. Interesting was the table storage. You can create a table service where different types of data can be stored in 1 table. It’s a no SQL datastore. This is ideal for storing structured non relational data.

Link to this:



3.           How to live longer and happier with Visual Studio 2015

This session was about the new features of Visual Studio 2015.

You can see that a lot of resharper functionality is now default in VS 2015.

Also integration with a BOWER, Gulp and Grunt are used very frequenly. For packages like AngularJS, bower is better than NuGet.




4.           EF7, Who are You and What Have You Done With My ORM?

Julie Lerman who gave the session is an expert on EF. She wrote books and gives trainings about it. Her conclusion in regard with the silver bullet key note is that the best way to go for the future is:

-       Keep using EF 6.0 in existing projects.

-       Start using EF 7.0 in new projects.

EF7 is a complete makeover of the entity framework. Since the start of EF they continued on the same code base. For EF7 they restarted completely from the beginning, to make it more light weight and also to tackle some challenges that were not possible to take with the old code base.


5.           "Write once, run anywhere”: Can AngularJS & Cordova do it?

This was definitely my favorite session. Christian Weyer explained in 1 hour and 30 min the complete lifecycle of a modern app that has 1 code base but can be published in any device!


He is co-owner of thinktecture that tackle very large implementations using .Net back-end, HTML5 and Javascript to code once, deploy anywhere.


Their code base is EF --> .Net WEB API --> AngularJS.

Using Cordova they can deploy the code to native iOS, Android and Windows Phone.

Then the AngularJS is also available in any browser and can even be build to native Apps for Windows and Mac OS.


6.           "It's alive!": Real-time applications with ASP.NET SignalR and AngularJS

Again a great session by Christian Weyer. SignalR is definitely something to look into. Very brief it’s a way to let the server communicate to the clients. E.g. when some data is updated and the clients need to refresh without the user having to click on a refresh button.

More info:



7.           HTML 5 Security

This session was mainly about CORS and ways that javascript could inject bad code. If setup the code in the correct way, you could prevent this.


8.           Aurelia Deep Dive

This session was about an alternative to AngularJS. Another javascript framework. The demo were not impressive, some failed. I do not believe in Aurelia, since the community behind it is not comparable with AngularJS.


9.           Domain Driven Design for the Database Driven-Mind

Another view on application architecture. This looks promising, but at the moment not feasible because lack of knowledge and high impact on development. Also we are in a process of change that first need to be advanced.


10.        The Engaging User Experience & the Natural User Interface

Key note about user experience. Not very interesting. Talking a lot about xbox Kinect and face recognition.


11.        Chrome developer tools

Here is a good summery made by one of the attendees:

The Console tab

It’s probably safe to assume that you all know and use the Console Tab of Google Chrome to write your debug statements and evaluate JavaScript expressions. Most of the time we do that by using “console.log” statement which writes your logging messages to the console. If you are using a lot of those “console.log” statements in your code then things can quickly get messy and it will become difficult to work through your logs to find the one line you actually need.

To organize your statements you can use “console.groupCollapsed” and “console.groupEnd”. These functions will create a collapsable group in the log window so you can find your debug lines faster.

If you want to measure how fast your code is executing you can use “console.time” and “console.timeEnd”. This can also prove quite handy when you want to benchmark certain functions.

Device Emulation

The Device Emulator enables you to test out your website on several devices (phones, tablets, computers…) and on different network speeds (4G, 3G, GPRS…). This makes it very easy to test out your responsive design. The emulator even supports touch events!

You can enable/disable it by toggling the device icon Chrome Dev Tools - Mobile Iconin your Dev Tools.

The Network tab

The Network tab is used to monitor the performance of your application and helps you identify slow loading resources. It includes detailed timing data, HTTP request and response headers, cookies…

A very useful feature of the Network tab is that you can download its contents to a .HAR file. This could help us debug the “unreproducible bugs” reported by a QA Engineer. If he’s doing his tests with the Network tab opened he can just send the failed requests to a developer to investigate. All he has to do is right-click the network table and select “Save as HAR with Content”. This will download a .HAR-file that can be read using a tool called Chrome HAR Viewer.

Quick tips

Inline editing

To enable inline editing just open up the console and type “document.body.contentEditable = true” and press ENTER. You can now modify any text on your page by just typing into the browser window. If you have to build a multilingual application you can use this to easily test what would happen if the text in your title or menu items would be translated (and thus be longer or shorter than intended by the designer).

Blackbox scripting

You all know that you can debug javascript code by adding breakpoints to your code in the “sources tab”. Very often this tab includes a lot of scripts that you don’t care about (external libraries etc.). You can prevent the debugger from breaking in those scripts by “blackboxing” them. Just right-click on the file and select “Blackbox Script”. You can stop blackboxing a script by right-clicking the same file and selecting “stop blackboxing”.

Styling log statements

You can add CSS styling to your “console.log” statements. This can prove useful if you want something to stand out if it occurs.


Please note that this blogpost is just a high level overview of useful and time saving features that were presented by Shay Friedman (@ironshay) at Techorama. The Google Chrome dev tools contain a lot more functionality than what can be covered here. If you are curious to learn more or want to read on about the topics covered in this post you can visit https://developer.chrome.com/devtools.


12.        Decomposing AngularJS

This was an interesting session that gave a deeper view of how the AngularJS binding works. He actually created a fresh JavaScript Framework from scratch (using code blocks and copy paste) that bound model to the view.


13.        EF7 demo demo demo

This was a replacing session were Julie showed EF 7 in combination with ASP.NET 5 in action.

HTTP Error 500.19 - Internal Server Error

After getting a latest version of the source files of my web project I got this error:

HTTP Error 500.19 - Internal Server Error

The requested page cannot be accessed because the related configuration data for the page is invalid.

The solution was to set the application pool to network identity and provide this user read access to the files of my web site.

JSON & EF: Error Self referencing loop detected for type System.data.entity occurs .

I got this error when I started to add the navigation properties to the entities. Because a master detail relation has got 2 kinds of navigation properties. The master gets the collection of childs and the child gets the master where it belongs to. JSON serialization will end up in a circular loop, since it serializes the child, then tries to serialize the parent, but this has a collection of child etc.

You can solve this many ways.

- If you do not need the parent navigation property, you can remove it. 

- You could set an attribute to the property: [JsonIgnore] [IgnoreDataMember]. The problem here is when you use the generated classes, the next time you generate it will be removed.

- Set lazy loading on your context to false: db.Configuration.LazyLoadingEnabled = false;

In my case I chose the first one, since the parent did not need to know about it's children.  

.Net: Ajax UpdatePanel causes DevExpress Controls to lose style after post

In my web application, I had a dev express gridview with a detail grid view. It was not so nice to see the form post backing after every click in the master grid, so I decided to use the ajax update panel.

The grid looks like this:

But after the first click the form looked like this:

The problem was apparently devexpress tries to edit the header of the page adding the style sheets links, so adding the runat="server" to your page header fixes this problem. In my case I had to add this to the master page and remove some <% tags in the header.

 <head runat="server">

.Net Web API and querystrings


Creating a web api is very easy and powerfull. If you want to use querystrings, its not done with the ols Request.Querystrings, but rather like this:

publicIEnumerable<GALV_ACCOUNT> GetAllAccounts()


    var q = Request.GetQueryNameValuePairs().Where(nv => nv.Key =="q").Select(nv => nv.Value).FirstOrDefault();

    if (q != null && q != string.Empty)


        var result = accounts.Where(a=>a.Name.ToLower().StartsWith(q.ToLower()));

        return result;




        thrownewException("Please specify a search query");



Then you can call the method like this: