Lately I’ve been playing around with USB led lights in .Net. I wanted the¬†animations to be separated¬†from my code. Wouldn’t it be great if you could define¬†what animations¬†are executed in a JSON file? And map it to code?

Normally one would build a mapper that does the conversion of the JSON commands¬†to the methods. I like to use a more generic approach.¬†I’ve created a small utility class¬†that¬†executes commands by mapping and executing them as a method of the¬†object. The solution is workable for a host of scenarios:

  • You can use it to map a JSON RPC command from a webservice on an object, creating a more generic service.
  • You can now create a JSON file with USB led¬†animations specification that need to be executed when a certain event occurs.
  • Simplifying the mapping between commands and objects in a generic way.

Nuget

Before you start, there is a Nuget package. (Link to GitHub at the end of the blog.)

Install-Package KeesTalksTech.Utilities.Rpc»

Remote Timer Example

I’ll show you how things work using an example. Let’s create a remotely controlled timer. Commands on the timer are actions like¬†start and¬†stop.

Let’s implement the class:

Safety first

Classes¬†have many (inherited) methods. There are some methods you most likely never ever want to expose (like the¬†Dispose method).¬†That’s why the¬†Interpertation is always done on¬†an interface. This is especially important¬†when you are using this project as part of RPC construction.

To execute JSON commands we’ll need to create an¬†IInterpreter¬†based on an instance of the timer and the¬†IRemoteTimer interface:

Executing a method

A method is defined as a JSON object with a method-name property. The system uses it to map it to a method.

Got parameters?

Parameters are defined as properties as well. Just add their names and values to JSON:

A series of methods

If you want to execute more than one method, just add the command in an array:

How about retrieving information?

Thought of that as well! Any results are returned as an object or an array of objects (in case of a series):

How about extension methods?

Extension methods are awesome. Let’s define a¬†Pause method:

To allow extensions methods to be considered, they’ll need to be given to the¬†Create:

Wrap up

The code has potential to solve a host of problems. If you like to fork it, please check GitHub and let me know what you think. The code used in the example can be found here.