Archive for the ‘C#’ Category

Building Netflix style microservices in .NET – Getting Started

August 15, 2017 Leave a comment

This is the first post of what will be a series of blog posts on Netflix style microservices in c# with .NET Core. The series is not meant as the ultimate guide for developing microservices in c#, but it is rather the summary of my personal experiences. I will describe how to setup an environment based on the Netflix microservice stack, how to develop a .NET Core Web API integrating with this stack, how to setup an API gateway, etc.

Introduction on microservices

Microservices are an architectural pattern that is becoming more and more popular. The pattern originated in web born companies such as Netflix, Spotify, Uber, Google,…. Luckily for us these companies shared their knowledge and experiences at various conferences with the rest of the world; resulting in the current rapid adaption of the microservice pattern. If you want to know more about microservices you can find some interesting videos recorded at tech conferences on YouTube from people working for Netflix, Spotify, etc.

Microservices are not the silver bullet that are going to make the development of every application smoother. They are probably even going to make the development of smaller applications more complex. But for building complex applications or the development within larger organizations, they will make the different components more decoupled and will bring more autonomy to the different teams. Resulting in more agility and a better time to market for each of the independent teams. If your organization is in a situation where software releases are complex and require the coordination of lots of people and components, then I recommend you to have a look at the microservices architectural pattern.

Martin fowler has a nice high-level overview on microservices:

What is important to understand about microservices, is that microservices is not about very small (REST) services, but rather about how to decouple a large application into smaller components, each responsible for a specific bounded context. The responsibility over these different bounded contexts is then given to different teams. Communication between the different components is going over formal interfaces allowing the different teams to work in full autonomy. You could describe the microservice pattern as SOA done right 😉

An important component of a microservice architecture is the service registry. This registry is used by the various microservices for looking up the address and port of a specific microservice they which to call. Every microservice instance registers itself to the service registry at startup and will periodically send heartbeats. A popular service registry is Eureka of Netflix, but other implementations such as Consul exist too.

In my personal opinion microservices are not a revolutionary new pattern, but is rather building further upon insights gathered from:

  • SOA
  • DevOps
  • DDD
  • Test Automation

Preparing the development environment

In order to setup a local development environment, you will need Windows 10 Pro x64 (for Hyper-V) and Visual Studio 2017.


The first component we need to install is Docker. Docker has a version for Windows that is fully compatible with all the Linux containers available online. Behind the scenes it is making use of a Linux kernel that is running on Hyper-V. You can find Docker for Windows at:


Eureka is the service registry developed by Netflix ( For simplicity, I wanted to host this component within a fully self-contained Docker container. There exist a Docker build file for Eureka created by Netflix. But unfortunately this was a kind of garage project and the build file is outdated (is was using a very old Eureka version). So I decided to create my own Docker build file.

I have based it on Tomcat Alpine. You can find the build file and the necessary configuration files at my GitHub:

FROM tomcat:8.5.15-jre8-alpine
MAINTAINER Pieter De Rycke <>

RUN rm -fr /usr/local/tomcat/webapps/ROOT &&\
mkdir /usr/local/tomcat/webapps/ROOT && \
cd /usr/local/tomcat/webapps/ROOT/ && \
wget -q &&\
unzip eureka-server-1.7.0.war &&\
rm eureka-server-1.7.0.war

COPY /usr/local/tomcat/webapps/ROOT/
COPY /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/
COPY /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/


ENTRYPOINT ["/usr/local/tomcat/bin/"]

CMD ["run"]

If you do a check-out from my GitHub, you can build the image with the following command:

docker build --tag eureka .

Microservice Environment

During the rest of the blog series, I will make use of a Docker environment consisting of a dedicated Docker network and a number of containers running within this network.

The network is a simple Docker bridge network:

docker network create --driver bridge netflix-network

Next we create a Docker container from the Eureka image we just created:

docker run -p 8080:8080 --name=eureka --network="netflix-network" --network-alias="eureka" eureka

Wrap Up

This was the first blog in what will be a serie on microservice development with C# and .NET Core. This first article should already provide you a high level overview on microservices and you should now also have a development environment running locally for developing microservices. In the next article we are going to create a first Web API Core microservice running in a Docker container and connecting to Eureka.

Categories: C#, microservices

Authenticating users with the Belgium eID in ASP.NET

August 14, 2015 10 comments

Every Belgium resident has an eID card. This card functions as PKCS#11 keystore containing two X509 certificates (including their private keys): one for authentication and one for digital signing. These certificates are protected against a PIN/PUK code. The card can be used to authenticate the user in a web application using HTTPS with client certificate authentication. Because this mode of authentication makes use of two out of the three different types of information that can be used for authentication (something you know and something you have), it can be considered strong authentication.

In a classic HTTPS scenario, only the server will prove its identity to the user by making use of its X509 certificate, it is then up to the web application to do an authentication of the user in applicative code (over the secure SSL tunnel). With client certificate authentication, both the server and the user (in fact the browser) will prove their identity by making use of their X509 certificate.

eID authentication in ASP.NET

Authentication based on the Belgium eID card can be easily integrated into an ASP.NET web application. I have created the necessary code as an OWIN middleware component that can hooked into your web application and that will create a ClaimsIdentity representing the user. You can already find the source at Github (, but in the comming days I will also create a NuGet package for it.

The first thing you must do, is configure your web application to allow or require client certificates in IIS.

2015-08-04 19_54_32-Internet Information Services (IIS) Manager

2015-08-04 19_57_36-Internet Information Services (IIS) Manager

Once this is done, we can read out the client certificate in our OWIN middleware. There are a number of properties that can be parsed from the certificate. My code will create claims for all these properties

public class EidAuthenticationHandler : AuthenticationHandler
    protected override async Task AuthenticateCoreAsync()
        var x509 = Context.Get("ssl.ClientCertificate");

        if (x509 != null)
            ClaimsIdentity identity = ValidateX509Certificate(x509);
            return new AuthenticationTicket(identity, new AuthenticationProperties());
            return new AuthenticationTicket(null, new AuthenticationProperties());

    private ClaimsIdentity ValidateX509Certificate(X509Certificate2 x509)
        var chain = new X509Chain(true);
        chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;

        X509Certificate2 citizenCertificate = chain.ChainElements[0].Certificate;

        if (citizenCertificate.NotAfter  DateTime.Now)
            throw new Exception("The citizen certificate is not (longer) valid.");

        //TODO verify if citizen certificate has not been revoked

        if (chain.ChainElements[1].Certificate.Thumbprint != "74CC6E5559FFD7C2DD0526C0C21593C56C9384F3")
            throw new Exception("Invalid Citizen CA certificate.");

        if (chain.ChainElements[2].Certificate.Thumbprint != "51CCA0710AF7733D34ACDC1945099F435C7FC59F")
            throw new Exception("Invalid Belgium Root CA certificate.");

        string firstName = Regex.Match(citizenCertificate.Subject, "G=([^,]*),").Groups[1].Value;
        string lastName = Regex.Match(citizenCertificate.Subject, "SN=([^,]*),").Groups[1].Value;
        string nationalRegisterIdentificationNumber = Regex.Match(citizenCertificate.Subject, "SERIALNUMBER=([^,]*),").Groups[1].Value;
        string nationality = Regex.Match(citizenCertificate.Subject, "C=([^,]*)").Groups[1].Value;

        // Based on information of:
        bool isMale = int.Parse(nationalRegisterIdentificationNumber.Substring(6, 3)) % 2 == 1;

        ClaimsIdentity identity = new ClaimsIdentity(Options.SignInAsAuthenticationType);
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, firstName + " " + lastName, null, Options.AuthenticationType));
        identity.AddClaim(new Claim(ClaimTypes.GivenName, firstName));
        identity.AddClaim(new Claim(ClaimTypes.Name, lastName));
        identity.AddClaim(new Claim(ClaimTypes.Gender, isMale ? "M" : "F"));
        identity.AddClaim(new Claim(ClaimTypes.Country, nationality));

        return identity;

And for average Joe programer, this is super easy. All he/she has to add to his "Startup.Auth.cs" file is the following code and he/she can authenticate the users based on the eID card.

app.UseEidAuthentication(new EidAuthenticationOptions() 
	SignInAsAuthenticationType = "Cookies"
Categories: C#, eID

Jace.NET 0.9: your input is appreciated!

February 12, 2014 19 comments

Most of the last previous releases were limited and only introduced bug fixes or new mathematical functions. Jace.NET has already a complete support for all the standard math, but for the next release I have decided to increase the scope: from version 0.9 forward Jace.NET will have full support for matrices!

The following syntax is planned:

  • Definition of a matrix: A = [1,2,3;4,5,6;7,8,9]
  • Scalar multiplication: 3*A
  • Matrix multiplication: A*B
  • Transpose: A’ or transpose(A)
  • Select a matrix element: A[2,3]
  • New functions: ones(3,3), zeros(3,3)

For the initial 0.9.x release(s), I have foreseen the following constraints to simplify the initial support for matrices:

  • It will not be supported to use variables in matrix elements: so the following syntax will initially not be allowed: [1,2,3;4,var,6;7,8,9]
  • All matrix elements will be interpreted as doubles in the engine (not as integers)

And now comes the part where you are involved as a reader: I would really like have your input.

  • Would this satisfy you (matrix) needs?
  • Is the proposal ok?
  • Are the constraints acceptable?
  • Besides matrix support, what else would you like to see in Jace.NET?

Hope to hear from you guys! Smile

Categories: C#, Jace.NET

Changing the supported media types of the default media formatters in the ASP.NET Web API client library

January 15, 2014 Leave a comment

A couple of days ago, I encountered an issue when calling a REST service. The REST service was returning JSON data, but the content type in the HTTP header was set to “text/javascript”. This caused the default JSON formatter of the ASP.NET Web API client not to recognize the data (he expects “application/json”). It took me a while to find this proper solution as I wanted to avoid creating a custom formatter, but the ASP.NET Web API client library allows to modify the supported content types for the default content formatters.

HttpClient client = new HttpClient();

MediaTypeFormatterCollection formatters = new MediaTypeFormatterCollection();
formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));

HttpResponseMessage response = await client.GetAsync(url);
SearchResult result = await response.Content.ReadAsAsync(formatters);
Categories: ASP.NET Web API, C#, REST

Compiled Zip package for Jace 0.8.4

January 8, 2014 Leave a comment

Jace.NET is a mathematical calculation engine for .NET that can parse and execute strings containing mathematical formulas. More information on Jace can be found in previous articles published on this blog or in the following codeproject article:

Previously, the only way to obtain an already compiled version of Jace.Net was to use NuGet. Although I am still convinced that nowadays the recommended way to add frameworks to Visual Studio projects should be NuGet, I understand that this is not always possible. Especially in enterprise environments. For people in such situations, I have created a zip based version of Jace.NET. This zip package contains compiled versions of Jace for .NET 4.x, Windows Store, Windows Phone 7 and Windows Phone 8.

The zip version can be downloaded using the following link:

All future zip packages will be published on the following GitHub page:

The assemblies in the zip package are currently not strongly signed. If you would rather prefer strongly singed assemblies, you can let me know by mail or by leaving a comment.

Categories: C#, Jace.NET

Jace.NET published on NuGet

November 10, 2012 Leave a comment

A couple of days ago, I have released the first version of my mathematical calculation engine for the .NET framework: Jace.NET. This build includes support for all the standard mathematical operations and a number of mathematical functions like: sin, cos, loge, logn, …

You can also download a demo application, that gives a visual insight into the parsing and execution steps of Jace.NET:


More information about the architecture of Jace.NET can found at:

Categories: C#, Jace.NET

Jace.NET – Just another calculation engine for .NET

November 4, 2012 33 comments

I work as a .NET technical architect in the financial industry and I get in touch with all sorts of mathematical formulas representing insurance or banking products. Most of the time, these formulas are hard coded by programmers and are thus not very flexible to be change dynamically at runtime by end-users.

This inspired me to start developing a calculation engine for the .NET platform that can execute any mathematical formula stored as a string both with or without variables. I wiped the dust of my university book: “Modern compiler implementations” and started the development a couple of weeks ago. I decided to name the calculation engine Jace.NET: Just another calculation engine for .NET.

Jace.NET is designed to run on .NET 4.0, Windows Phone 7, Windows Phone 8 and Windows RT.

How to use it

Jace.NET can be used in a couple of ways:

By directly executing a given mathematical function using the provided variables:

Dictionary<string, double> variables = new Dictionary<string, double>();
variables.Add("var1", 2.5);
variables.Add("var2", 3.4);

CalculationEngine engine = new CalculationEngine();
double result = engine.Calculate("var1*var2", variables);

By building a .NET Func accepting a dictionary as input containing the values for each variable:

CalculationEngine engine = new CalculationEngine();
Func<Dictionary<string, double>, double> function = engine.Build("var1+2/(3*otherVariable)");

Dictionary<string, double> variables = new Dictionary<string, double>();
variables.Add("var1", 2);
variables.Add("otherVariable", 4.2);

double result = function(variables);

By building a typed .NET Func:

CalculationEngine engine = new CalculationEngine();
Func<int, double, double> function = (Func<int, double, double>)engine.Function("var1+2/(3*otherVariable)")
    .Parameter("var1", DataType.Integer)
    .Parameter("otherVariable", DataType.FloatingPoint)

double result = function(2, 4.2);


Jace.NET has an architecture similar to the one of modern compilers: interpretation and execution are performed in a number of steps. Each step focuses on one aspect of the parsing and interpretation of the formula. This keeps the overall complexity manageable.


The process starts with the tokenizing phase. During this phase the input string is converted into the various allowed tokens: integers, doubles, operations and variables. If a part of the input string contains text that does not match with any type of token, an exception is thrown and Jace will halt.

When tokenizing is successfully finished, an abstract syntax tree (AST) is constructed. This abstract syntax tree is a tree like data model that unambiguously represents the mathematical formula in memory. All mathematical precedence rules are taking into account when constructing the abstract syntax tree. Jace uses an algorithm inspired by the shunting-yard algorithm of Dijkstra to create this AST.


After AST creation, the optimizer will try to simplify the abstract syntax tree: if a part of the formula does not depend on variables but solely on constants. This part of the tree is already calculated and replaced by a constant in the tree.


The final phase is the OpCode generation. During this phase, a .NET dynamic method is created and the necessary MSIL is generated to execute the formula. This dynamic method is cached in memory. If the same formula is executed again in the future with other values for the variables. The interpretation steps are skipped and the dynamic method is directly executed. If the formulas of the calculations are frequently reoccurring, Jace.NET has near compiled code performance.


If you are interested in the source code, please have a look at:

Categories: C#, Jace.NET