December 13, 2018

Derivative webhook was introduced early this year, and it was later included on the .NET SDK, see basic code snippet here. But what about a more complete sample?

Before we dive into a sample, we need a way to push updates to the browser client, and that's where we can use SignalR. There a few resources out there, but I liked this video.

SignalR requires:

1. Client JavaScript to connect and handle messages from the server. The video uses a package from NPM, which is an option, but for simplicity, I like to use CDNs, like:

<script src="//unpkg.com/@aspnet/signalr@1.1.0/dist/browser/signalr.min.js"></script>

2. Server hub to manage the connection, where we can implement methods to receive messages from the client (which we're not using here). For this case, we need a way to identify the client connection id and, to keep it organized, a static function to encapsulate the feature.

public class ModelDerivativeHub : Microsoft.AspNetCore.SignalR.Hub
{
    public string GetConnectionId() { return Context.ConnectionId; }

    public async static Task ExtractionFinished(IHubContext<ModelDerivativeHub> context, JObject body)
    {
        string connectionId = body["hook"]["scope"]["workflow"].Value<String>();
        await context.Clients.Client(connectionId).SendAsync("extractionFinished", body);
    }
}

And here you see the trick: I'm using the connectionId (which uniquely identifies a client) as my workflow id, so when a translation is done I know which client browser to notify.

That's it, basically. 

You can see it running at modelderivative.herokuapp.com or see this specific commit (with all changes) here.

Related Posts