harre.dev

C#

Multiple listeners for your Service Fabric service

Service Fabric is a great piece of technology on the Azure platform and I’ve been using it quite a lot in recent projects. It takes away a lot of the setup and orchestration when dealing with microservices.

There comes a point where services need to talk to each other and this is easily achieved using the Remoting bits you can get from NuGet. The general way of doing this is creating an Interfaces project next to the service that contains the service interface and classes used in transport. The interface is implemented on the service entrypoint and a listener is exposed to the Fabric runtime so that it can communicate with the rest of the platform. We’re going to take it one step further and put the service implementations in their own class instead of on the service entrypoint (keeps things nice and clean) and also enable dependency injection from that point forward.

Multiple DbContext's with migrations on a single database

Here is a small problem I ran into while working on my current project. This project already has an Entity Framework DbContext class with entities and a database. I’m adding a new feature but want to keep the changes as isolated as possible. So I wanted to create a second DbContext that handles the entities specific to my new feature.

Adding the context to the codebase is no hassle, just create the new class and derive it from DbContext. The problem is in the migrations. Entity Framework has a system that can track changes to the model and apply those changes to the actual database. To keep track of these changes, Entity Framework uses a table called __MigrationHistory where it stores all kinds of metadata about the model that it can compare to when you make changes to your entities in code.

POST-ing JSON to an ASP.NET Web API controller

So you want to post some JSON to an ASP.NET Web API controller?

I bet you’ve written this more than you wanted to:

$.ajax({
	type: "POST",
	url: url,
	data: JSON.stringify(data),
	dataType: "json",
	contentType: "application/json; charset=utf-8"
});

I hate that work-around where you specify all sorts of stuff that you don’t really want to specify (like dataType, contentType, etc…). This is all required because the friendlier $.post(...) will send your data in a Form encoded way.

App.config xdt transforms

Here is a little hack you can do to enable transformations in app.config like you can in your web.config.

A quick intro to transformations, they can make your life a bit easier by storing different configs in different files that, depending on your build configuration, end up in the actual config file. Here is a simple example.

This is the original web.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
	<add key="SomeSetting" value="true" />
	<add key="Title" value="Debug" />
  </appSettings>
</configuration>

And there is also a web.Release.config, that looks like this:

Read Spotify track info using C#

Spotify recently updated the desktop app again and it is once again possible to read current track info directly from it. Here is how you to read it using a little C# code.

A tiny little disclaimer, Spotify can break this code by updating their desktop app. It’ll work now, but if they remove the track info from the title again, things won’t work anymore.

So the current track is hidden somewhere, let’s find out where it is.

Basic string templating in C#

Every solution I’ve worked on required some form of communication via e-mail or other form of text to the outside world, reporting, notifications or something else. There are a bunch of libraries out there that can make your life easy if you need complex templates. But this is not about complex, this is supporting the basics without including all sorts of unnecessary stuff.

What do we need to make this happen? The first thing is a template. A template is nothing more than a piece of plain text (or HTML if you want) in which we want to replace parts to create a complete message. Lets use something very simple, a single line, one tag.

Fluent data access

Working in a team of developers, the following might happen:

Developer 1 creates a piece of UI and adds a method to load data into said UI. The method he creates is called GetUserInfo(…)

Here comes Developer 2 and he also creates a piece of UI that displays user info. Developer 2 however, needs to display more than just the user info, he also needs the requests made by the user. And then GetUserInfoWithRequests(…) is created next to the already existing GetUserInfo method.

Easy Windows Service debugging

Long-running processes in a web application running on IIS is a bad idea. The reason for that is that IIS might unload the AppPool that is running your process due to inactivity. Inactivity? Yep, if IIS does not recieve a requests for a while, it will shut the site down to conserve system resources. (This is all configurable ofcourse, but I’ve seen it happen)

To allow for long-running stuff, a Windows Service might be a right fit. Here is what the default startup code for a Windows service looks like:

Generating an RSS feed in C#

A hobby project of mine needed to generate an RSS feed. I was already doing this by just generating and XML file in the webroot and linking to that on the frontpage. But during this coding session, where all the data is pulled straight from the markdown files I wanted to create a controller action to do the generating for me.

First things first, there is an assembly available out of the box in the .NET Framework. All you need is to make reference to System.ServiceModel.Syndication and you are ready to start writing code. The classes we are using are

Getting started with Inversion of Control

Alright, lets dive straight into the deep end! … ok, but not drown in the process of doing so. One step at a time. Lets’s start with an example.

The technical side

Here is some code:

public class Foo
{
    private readonly Bar bar;

    public Foo()
    {
        this.bar = new Bar();
    }
}

To create an instance of Foo we write

Foo theFoo = new Foo();

In this example we have two classes, Foo and Bar. Foo makes use of a Bar to do some work. When a Foo instance is created the creator of the Foo instance has no control over what kind of Bar the Foo instance is going to use. They are stuck together. This code is completely valid but what if we want to let the creator of Foo control the kind of Bar that is used? We have to invert control! Here is the same code with it’s control flow inverted:

SignalR dependency injection

My go-to container for IoC at the moment is SimpleInjector because you know.. it’s simple. I’ve used it in a couple of projects and used in a hobby project recently again.

This hobby project uses SignalR for real-time communication between browser and server and after setting that up I wanted to inject dependencies in to the SignalR hubs. It is pretty easy but there was a minor catch. Let’s look at some code.