Anmeldung | Registrieren | Hilfe

.NET-Blogs Archiv Dezember 2016

Building a home robot: Part 4 - moving the head up and down

26.12.2016 09:00:00 | Daniel Springwald

(see all parts of "building a home robot")

Because the monitor and raspberry pi are placed in the front of the head most of weight is there. So the motors for up/down  movement have to be powerful enough to handle this.

I decided to use two stepper motors with built in gearboxes. They also are the axis for the head movement. I mounted them back to back into a 3d printed box ,so they are moving in contrariwise directions.

Putting together neck and front head:

Assembling including cables, Raspberry Pi and electronics:

The two stepper motors have much power - but still not enough to lift the head. To fix this problem I placed a counterbalance made from lead in the back of the head.

The first test with provisional counterbalance:

After some hours of testing another problem occurred. The mechanic connection between the two motors and the 3d printed part was very small.

Only 4mm PLA to connect  to the whole head wight and movement:

And the PLA material was not strong enough to handle this for a long time – so the freedom of movement increased.

To solve this I used two small parts of aluminum with holes matching to the axis of both stepper motors.

Goodbye Techblog

20.12.2016 16:12:00 | Martin Hey

Ich habe immer gerne gebloggt, war das doch für mich ein Weg, mein Wissen zu teilen. Und oft genug habe ich beim Suchen nach Lösungen für Probleme meine eigenen Posts gefunden und so gemerkt, dass ich das gleiche Problem schon mal hatte - ein bisschen Eigennutz war also dabei und ich habe ihn auch als private Wissenssammlung mit Indizierung durch Google verwendet. 

Aber in den letzten beiden Jahren ist immer weniger Zeit fürs Bloggen geblieben (6 Posts in 2016 ist nicht viel) und auch die Themen mit denen ich mich beschäftige verändern sich - so bin ich zwar noch an Entwickler-Themen dran, aber oft genug sind da auch eher betriebswirtschaftliche Themen die mich umtreiben.

Ich werde auch weiterhin aktiv in der Entwickler-Community bleiben und an anderer Stelle sicher weiter bloggen. Nur dieser eher privat betriebene Blog wird zum Ende des Jahres 2016 gelöscht.

Angelehnt an den allerersten Post aus 2007: goodbye world

A small library to support the CQS pattern.

11.12.2016 17:00:00 | Jürgen Gutsch

The last years, I loved to use the Command and Query Segregation pattern. Using this pattern in every new project, requires to have the same infrastructure classes in this projects. This is why I started to create a small and reusable library, which now supports ASP.NET Core and is written to match .NET Standard 1.6.

About that CQS

The idea behind CQS is to separate the query part (the read part / fetching-the-data-part) from the command part (the write part / doing-things-with-the-data-part). This enables you to optimize both parts in different ways. You are able to split the data flow into different optimized pipes.

From my perspective, the other most important benefit of it is, that this approach enforce you, to split your business logic into pretty small peaces of code. This is because each command and each query only does one single thing:

  • fetching a specific set of data
  • executing a specific command

E. g. if you press a button, you probably want to save some data. You will create a SaveDataCommand with the data to save in it. You'll pass that command to the CommandDispatcher and this guy will delegate the command to the right CommandHandler, which is just responsible to save that specific data to the database, or what ever you want to do with that data. You think you'll also add a log entry with the same command? No problem: Just create another CommandHandler using the same command. With this approach you'll have two small components, one to save the data and another one to add a log entry, which are completely independent and can be tested separately.

What about fetching the data? Just create a "Query" with the data used as a filter criteria. Pass the Query to the QueryProcessor, which delegates the Query to the right QueryHandler. in this QueryHandler, you are able to select the data from the data source, map it to the result you expect and return it back.

Sounds easy? It really is as easy.

Each Handler, both the QuerHandlers and the CommandHandlers, are isolated peaces of code, if you use Dependency Injection in it. This means unit tests are as easy as the implementation itself.

What is inside the library?

This library contains a CommandDispatcher and a QueryProcessor to delegate commands and queries to the right handlers. The library helps you to write your own commands and queries, as well as your own command handlers and query handlers. There are two main NameSpaces inside the library: Command and Query

The Command part contains the CommandDispatcher, an ICommand interface and two more interfaces to define command handlers (ICommandHandler<in TCommand>) and async command handlers (IAsyncCommandHandler<in TCommand>):

The CommandDispatcher interface looks like this:

public interface ICommandDispatcher
    void DispatchCommand<TCommand>(TCommand command) where TCommand : ICommand;
    Task DispatchCommandAsync<TCommand>(TCommand command) where TCommand : ICommand;

The Query part contains the QueryProcessor, a generic IQuery, which defines the result in the generic argument and two different QueryHandlers. It also contains two more interfaces to define query handlers (IHandleQuery<in TQuery, TResult>) and async query handlers (IHandleQueryAsync<in TQuery, TResult>)

public interface IQueryProcessor
        TResult Process<TResult>(IQuery<TResult> query);
        Task<TResult> ProcessAsync<TResult>(IQuery<TResult> query);

Using the library

For the following examples, I'll reuse the speaker database I already used in previous blog posts.

After you installed the library using Nuget, you need to register the the QueryProcessor and the CommandDispatcher to the dependency injection. You can do it manually in the ConfigureSerices method or just by using AddCqsEngine()

public void ConfigureServices(IServiceCollection services)



The methods AddQueryHandlers and AddCommandHandlers are just methods to encapsulate the registrtion of your Handlers, and are propably written by you as a user of this library. The method could look like this:

public static IServiceCollection AddQueryHandlers(this IServiceCollection services)
	services.AddTransient<IHandleQueryAsync<AllSpeakersQuery, IEnumerable<Speaker>>, SpeakerQueryHandler>();
	services.AddTransient<IHandleQueryAsync<SpeakerByIdQuery, Speaker>, SpeakerQueryHandler>();

	services.AddTransient<IHandleQueryAsync<AllEventsQuery, IEnumerable<Event>>, EventQueryHandler>();
	services.AddTransient<IHandleQueryAsync<SingleEventByIdQuery, Event>, EventQueryHandler>();

	services.AddTransient<IHandleQueryAsync<AllUsergroupsQuery, IEnumerable<Usergroup>>, UsergroupQueryHandler>();
	services.AddTransient<IHandleQueryAsync<SingleUsergroupByIdQuery, Usergroup>, UsergroupQueryHandler>();

	services.AddTransient<IHandleQueryAsync<AllNewslettersQuery, IEnumerable<Newsletter>>, NewsletterQueryHandler>();
	services.AddTransient<IHandleQueryAsync<SingleNewsletterByIdQuery, Newsletter>, NewsletterQueryHandler>();
	return services;

Usually you will place this method near you handlers.

The method AddCqsEngine is overloaded to add your QueryHandlers and yor CommandHandlers to the dependnecy injection. There is no real magic behind that method. It is just to group the additional dependencies:

services.AddCqsEngine(s =>

The parameter s is the same Seervicecollection as the one in the ConfigureServices method.

This library makes heavily use of dependency injection and uses the IServiceProvider, which is used and provided in ASP.NET Core. If you replace the built in DI container with different one, you should ensure that the IServiceProvider is implemented and registered with that container.

Query the data

Getting all the speakers out of the storage is a pretty small example. I just need to create a small class called AllSpeakersQuery and to implement the generic interface IQuery:

public class AllSpeakersQuery : IQuery<IEnumerable<Speaker>>

The generic argument of the IQuery interface defines the value we want to retrieve from the storage. In this case it is a IEnumerable of speakers.

Querying a single speaker looks like this:

public class SpeakerByIdQuery : IQuery<Speaker>
    public SingleSpeakerByIdQuery(Guid id)
        Id = id;

    public Guid Id { get; private set; }

The query contains the speakers Id and defines the return value of a single Speaker.

Once you got the QueryProcessor from the dependency injection, you just need to pass the queries to it and retrieve the data:

// sync
var speaker = _queryProcessor.Process(new SpeakerByIdQuery(speakerId));
// async
var speakers = await _queryProcessor.ProcessAsync(new AllSpeakersQuery());

Now let's have a look into the QueryHandlers, which are called by the QueryProcessor. This handlers will contain your business logic. This are small classes, implementing the IHandleQuery<in TQuery, TResult> interface or the IHandleQueryAsync<in TQuery, TResult> interface, where TQuery is a IQuery<TResult>. This class usually retrieves a data source via dependency injection and an Execute or ExecuteAsync method, with the specific Query as argument:

public class AllSpeakersQueryHandler :
    IHandleQuery<AllSpeakersQuery, IEnumerable<Speaker>>
    private readonly ITableClient _tableClient;

    public SpeakerQueryHandler(ITableClient tableClient)
        _tableClient = tableClient;

    public Task<IEnumerable<Speaker>> Execute(AllSpeakersQuery query)
        var result = _tableClient.GetItemsOf<Speaker>();
        return result;

public class SpeakerByIdQueryQueryHandler :
    IHandleQueryAsync<SpeakerByIdQuery, Speaker>
    private readonly ITableClient _tableClient;

    public SpeakerQueryHandler(ITableClient tableClient)
        _tableClient = tableClient;
    public async Task<Speaker> ExecuteAsync(SpeakerByIdQuery query)
        var result = await _tableClient.GetItemOf<Speaker>(query.Id);
        return result;

Sometimes I handle multiple queries in a single class, this is possible by just implementing multiple IHandleQuery interfaces. I would propose to do this only, if you have really small Execute methods.

Executing Commands

Let's have a quick look into the commands too.

Let's assume we need to create a new speaker and we need to update a speakers email address. To do this we need to define two specific commands

public class AddSpeakerCommand : ICommand
    AddSpeakerCommand(Speaker speaker)
        Speaker = speaker;

    public Speaker Speaker { get; private set; }

public class UpdateSpeakersEmailCommand : ICommand
    UpdateSpeakersEmailCommand(int speakerId, string email)
        SpeakerId = speakerId;
        Email = email;

    public int SpeakerId { get; private set; }

    public string Email { get; private set; }

As equal to the queries, the commands need to be passed to the CommandDispatcher, which is registered in the DI container.

// sync
_commandDispatcher.DispatchCommand(new AddSpeakerCommand(myNewSpeaker));
// async
await _commandDispatcher.DispatchCommandasync(new UpdateSpeakersEmailCommand(speakerId, newEmail));

The CommandHandlers are small classes which are implementing the ICommandHandler or the IAsyncCommandHandler where TCommand is a ICommand. Thise handlers contain a Handle or a HandleAync method with the specific Command as argument. As equal to the query part, you usually will also get a data source from the dependency injection:

public class AddSpeakerCommandHandler : ICommandHandler<AddSpeakerCommand>
	private readonly ITableClient _tableClient;

	public AddSpeakerCommandHandler(ITableClient tableClient)
		_tableClient = tableClient;

	public void Handle(AddSpeakerCommand command)

Command validation

What about validatig the commands? Sometimes it is needed to check authorization or to validate the command values before executing the commands. You can do the checks inside the handlers, but this is not always a good idea. This increases the size and the complexity of the handlers and the validation logic is not reusable like this.

This is why the CommandDispatcher supports precondition checks. As equal to the command handlers, you just need to write command preconditions (ICommandPrecondition<in TCommand>) od async command preconditions (ICommandPrecondition<in TCommand>). This interfaces contain a Chack or ChackAsync method which will be executed before the command handlers are executed. You can hava as many preconditions as you want for a single command. If you register the preconditions to the DI container, the command dispatcher will find and execute them:

public class ValidateChangeUsersNameCommandPrecondition : ICommandPrecondition<ChangeUsersNameCommand>
    public void Check(ChangeUsersNameCommand command)
        if (command.UserId == Guid.Empty)
            throw new ArgumentException("UserId cannot be empty");
        if (String.IsNullOrWhiteSpace(command.Name))
            throw new ArgumentNullException("Name cannot be null");

In case of errors, the command dispatcher will throw an AggregateException with all the possible exceptions in it.


The whole speaker database application is built like this: Using handlers to create small components, which are handling queries to fetch data or which are executing commands to do something with the data.

What do you think? Does it make sense to you? Would it be useful for your projects? Please drop some lines and tell me about your opinion :)

This library is hosted on GitHub in the "develop" branch. I would be happy about any type contribution on GitHub. Feel free to try id out and let me know about issues, tips and improvements :)

Contributing to OSS projects on GitHub using fork and upstream

06.12.2016 17:00:00 | Jürgen Gutsch


Some days ago, Damien Bowden wrote a pretty cool post about, how to contribute to an open source software project hosted on GitHub, like the AspLabs. He uses Git Extensions in his great and pretty detailed post. Also a nice fact about this post is, that he uses a AspLabs as the demo project. Because we both worked on that on the hackathon at the MVP Summit 2016, together with Glen Condron and Andrew Stanton-Nurse from the ASP.NET Team.

At that Hackathon we worked on the HealthChecks for ASP.NET Core. The HealthChecks can be used to check the heath state of dependent sub systems in an e. g. micro service environment, or in any other environment where you need to know the health of depending systems. A depending systems could be a SQL Server, an Azure Storage service, the Hard drive, a Web-/REST-Service, or anything else you need to run your application. Using the HealthChecks you are able to do something, if a service is not available or unhealthy.

BTW: The HealthChecks are mentioned by Damian Edwards in this ASP.NET Community Standup: https://youtu.be/hjwT0av9gzU?list=PL0M0zPgJ3HSftTAAHttA3JQU4vOjXFquF

Because Damien Bowden also worked on that project, my idea was to do the same post. So asked him to "fork" the original post, but use the Git CLI in the console instead of Git Extensions. Because this is a fork, some original words are used in this post ;)

Why using the console? Because I'm a console junkie since a few years and from my perspective, no Git UI is as good as the simple and clean Git CLI :) Anyway, feel free to use the tool that fits your needs. Maybe someone will write the same post using SourceTree or using the Visual Studio Git integration. ;)

As a result this post is a also simple guideline on how you could contribute to OSS projects hosted on GitHub using fork and upstream. This is even not the only way to do it. In this demo I'm going to use the console and the basic git commands. As same as Damien did, I'll also use the aspnet/AspLabs project from Microsoft as the target Repository.

True words by Damien: So you have something to contribute, cool, that’s the hard part.

Setup your fork

Before you can make your contribution, you need to create a fork of the repository where you want to make your contribution. Open the project on GitHub, and click the "Fork" button in the top right corner.

Now clone your forked repository. Click the "Clone and download" button and copy the clone URL to the clipboard.

Open a console and cd to the location where you want to place your projects. It is c:\git\ in my case. Write git clone followed by the URL to the repository and press enter.

Now you have a local master branch and also a server master branch (remote) of your forked repository. The next step is to configure the remote upstream branch to the original repository. This is required to synchronize with the parent repository, as you might not be the only person contributing to the repository. This is done by adding another remote to that git repository. On GitHub copy the clone URL the the original repository aspnet/AspLabs. Go back to the console and type git remote add upstream followed by the URL of the original repository:

To check if anything is done right, type git remote -v, to see all existing remotes. It should look like this:

Now you can pull from the upstream repository. You pull the latest changes from the upstream/master branch to your local master branch. Due to this you should NEVER work on your master branch. Then you can also configure your git to rebase the local master with the upstream master if preferred.

Start working on the code

Once you have pulled from the upstream, you can push to your remote master, i. e. the forked master. Just to mention it again, NEVER WORK ON YOUR LOCAL FORKED MASTER, and you will save yourself hassle.

Now you’re ready to work. Create a new branch. A good recommendation is to use the following pattern for naming:

<gitHub username>/<reason-for-the-branch>

Here’s an example:


By using your GitHub username, it makes it easier for the person reviewing the pull request.

To create that branch in the console, use the git checkout -b command followed by the branch name. This creates the branch and checks it out immediately:

Creating pull requests

When your work is finished on the branch, you need to push your branch to your remote repository by calling git push Now you are ready to create a pull request. Go to your repository on GitHub, select your branch and and click on the "Compare & pull request" button:

Check if the working branch and the target branch are fine. The target branch is usually the master of the upstream repo.

NOTE: If your branch was created from an older master commit than the actual master on the parent, you need to pull from the upstream and rebase your branch to the latest commit. This is easy as you do not work on the local master. Or update your local master with the latest changes from the upstream, push it to your remote and merge your local master into your feature branch.

If you are contributing to any Microsoft repository, you will need to sign an electronic contribution license agreement before you can contribute. This is pretty easy and done in a few minutes.

If you are working together with a maintainer of the repository, or your pull request is the result of an issue, you could add a comment with the GitHub name of the person that will review and merge, so that he or she will be notified that you are ready. They will receive a notification on GitHub as soon as you save the pull request.

Add a meaningful description. Tell the reviewer what they need to know about your changes. and save the pull request.

Now just wait and fix the issues as required. Once the pull request is merged, you need to pull from the upstream on your local forked repository and rebase if necessary to continue with you next pull request.

And who knows, you might even get a coin from Microsoft. ;)

The console I use

I often get the question what type console I use. I have four consoles installed on my machine, in addition to the cmd.exe and PowerShell. I also installed the bash for Windows. But my favorite console is the Cmder, which is a pretty nice ConEmu implementation. I like this console because it is easy to use, easy to customize and it has a nice color theme too.


Thanks to Andrew Stanton-Nurse for his tips. Thanks to Glen Condron for the reviews. thanks Damien Bowden for the original blog post ;)

I'd also be happy for tips from anyone on how to improve this guideline.

VSTO: Bilder in Ribbons nutzen

01.12.2016 14:40:01 | Hendrik Loesch

Aktuell habe ich die Ehre ein Excel Plugin zu schreiben. Dieses verfügt über ein eigenes Ribbon, welches möglichst ansprechend aussehen soll. Für mich als Farblegastheniker ist es unmöglich ansprechende Icons zu designen. Dazu kommt, dass die Google Bildersuche schon allein aufgrund der rechtlichen Situation eine eher fragliche Quelle ist. Um nun also möglichst nah am […]

Regeln | Impressum