mene
mene

Reputation: 382

Handing C# .NET events with edge.js in Node.js for electron

I need to do some calls from my js to my C# DLL in my Electron project and it works fine in this way:

c#

namespace Electron.Wrapper
{
    public class QueryWrapper
    {

        public async Task<object> OnQuery(dynamic request)
        {
            ...
            return ..;
        }
    }
}

js

let edge = require('electron-edge-js');
let queryWrapperQuery = edge.func({
    assemblyFile: '..dllUrl..',
    typeName: 'Electron.Wrapper.QueryWrapper',
    methodName: 'OnQuery'
});
window.query = function (options) {
    queryWrapperQuery(JSON.stringify(options), function (error, result) {
        ...
    });
}

The problem is that I use an external DLL that triggers async events sometimes, so I need find a way for listening the .NET events from js.

I found this way for resolve my problem but I think isn't the right way because I need a class library for Electron and I don't know how use it with also the previous way and probabily I don't need a WebSocketServer.

A .Net and js sample will be valued.

Thanks, Andrea

Update 1 I found this way, cold be the right one? I'm trying to implement .net, any suggestions?

Upvotes: 0

Views: 2327

Answers (1)

mene
mene

Reputation: 382

I found a good way:

C#:

public Task<object> WithCallback(IDictionary<string, object> payload)
{
    Func<object, Task<object>> changed = (Func<object, Task<object>>)payload["changed"];
    return Task.Run(async () => await OnQuery(payload["request"], changed));
}

js:

var withCallback = edge.func({
    assemblyFile: '..dllUrl..',
    typeName: 'Electron.Wrapper.QueryWrapper',
    methodName: 'WithCallback' 
});

window.query = function (options) {
    function triggerResponse(error, result) {
        ...
    }

    withCallback({
        changed: (result) => triggerResponse(null, result),
        request: JSON.stringify(options)
    }, triggerResponse);
};

When you need trigger when someting changes you should use the parameter 'payload' in OnQuery function:

public async Task<object> OnQuery(dynamic request, dynamic payload = null)
{
    ...
}

Next the OnQuery return the value you can call again the js callback in this way:

payload("Notify js callback!");

I hope this can help someone!

Upvotes: 2

Related Questions