Giter VIP home page Giter VIP logo

electron-cgi-dotnet's Introduction

Electron CGI

Electron CGI is a library that enables creating requests in NodeJs that are then served by .NET.

The npm package is called electron-cgi.

The nuget package is called ElectronCgi.DotNet.

Here's an example of how you can interact with a .Net application from Node:

In NodeJs/Electron:

const { ConnectionBuilder } = require('electron-cgi');

const connection = new ConnectionBuilder()
        .connectTo('dotnet', 'run', '--project', 'DotNetConsoleProjectWithElectronCgiDotNetNugetPackage')
        .build();

connection.onDisconnect = () => {
    console.log('Lost connection to the .Net process');
};

connection.send('greeting', 'John', (err, theGreeting) => {
    if (err) {
        console.log(err);
        return;
    }
    console.log(theGreeting); // will print "Hello John!"
});

//or using promises

const theGreeting = await connection.send('greeting', 'John')

connection.close();

And in the .Net Console Application:

using ElectronCgi.DotNet;

//...
static void Main(string[] args)
{
    var connection = new ConnectionBuilder()
                        .WithLogging()
                        .Build();

    // expects a request named "greeting" with a string argument and returns a string
    connection.On<string, string>("greeting", name =>
    {
        return $"Hello {name}!";
    });

    // wait for incoming requests
    connection.Listen();        
}

How does it work?

Electron CGI establishes a "connection" with an external process. That external process must be configured to accept that connection. In the example above that's what the Listen method does.

In Node we can "send" requests (for example "greeting" with "John" as a parameter) and receive a response from the other process.

The way this communication channel is established is by using the connected process' stdin and stdout streams. This approach does not rely on staring up a web server and because of that introduces very little overhead in terms of the requests' round-trip time.

Changelog

Update version 1.0.3

Bugfix for Connection.Send(requestType, arg, responseArg => {...}) where argument type information for the response argument type was being inadvertently discarded.

Update version 1.0.2

Added the the UsingEncoding(System.Text.Encoding encoding) method to ConnectionBuilder, usage:

var connection = new ConnectionBuilder().UsingEncoding(System.Text.Encoding.UTF8).Build()

If you are having encoding issues with messages between Node and .NET failing because of special characters (e.g. ä,ö,ü) try to set the encoding this way in .NET.

Update version 1.0.1

  • Error propagation to Node.js

    • An exception in a handler will be serialized and sent to Node.js (requires electron-cgi 1.0.0) and won't crash the process
  • Bugfixes

Update version 1.0.0

  • This version was uploaded incorrectly. Skip it.

Update version 0.0.5

  • Duplex: ability to send requests from both .Net and Node.js

Update version 0.0.2

  • Ability to serve request concurrently (uses System.Threading.Tasks.DataFlow)

Next steps

  • Add the ability to send requests form .Net to Node
  • Instead of making the process fail when there's an exception in a handler, serialise the exception and "surface" it in Node

electron-cgi-dotnet's People

Contributors

rcook avatar ruidfigueiredo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

electron-cgi-dotnet's Issues

Typescript definition files not updated for breaking change

The file connection.d.ts was not updated for the breaking change on the send method:

    /**
     * Sends a request to the connected process
     * @param type The request type
     * @param onResponse Optional callback that will be invoked after the request has been executed on the connected process 
     */
    send(type: string, onResponse?: (returnArg: any) => void): void | Promise<any>;
    /**
     * Sends a request and arguments to the connected process
     * @param type The request type
     * @param args Argument to be sent to the connected process request handler 
     * @param onResponse Optional callback that will be invoked after the request has been executed on the connected process 
     */
    send(type: string, args?: any, onResponse?: (returnArg: any) => void): void | Promise<any>;

So right now I have code that works, because I updated it according to the example and added the error variable. But the typescript compiler gives me an error that it doesn't match the definitions.

Does electron CGI support REST API and MQTT?

HI,

I wonder if Electron CGI supports REST API request/response and MQTT subscription/publish.

If electron CGI supported the REST API, how should I specify the method type for REST API request (i.e., POST, GET, UPDATE, etc.)?

Also, there is a URL as a recipient for REST API requests, I attempted to replace the name of the executables of the server in Electron CGI but it did not work.. So how shall I set this up in electron CGI if it did support REST API?

Also, The same set of questions go for the MQTT subscriptions and publication.

Please advise.

Allow setting a custom Serilog logger

I want to use a rolling serilog sink instead of the default. Right now I can hack it in by replacing the Log.Logger global variable but it would be nice to not have to do this.

How do you log?

If I use Console.WriteLine for logs, the electron main process encounters an error because the logs are not JSON.

A Javascript error occured in the main process

Im getting an error A Javascript error occured in the main process when I try to run this project using npm run start. This occurs when the dotnet core project sends a message back to electron

screenshot 404

I am using the following packages and versions:
electron-cgi: ^1.0.6
electron-cgi-dotnet: 1.0.4-beta

Have I got something wrong in the project?

how to log in eletron-cgi with log4net?

Hi,

I encountered a problem that the log4net contents, which are supposed to log on the socket server, are sent to the client whenever a message is received and handled by the server. What I want is to log the event when the server received a message but I do not expect that log was sent back to the client. I am not sure how log4net's API is linked to the electron-cgi for providing the log content to e sent back.. Please advise.

Thread/Task sleep prevents sending?

Hello,

consider this small program:

using System.Threading;
using ElectronCgi.DotNet;
using Microsoft.Extensions.Logging;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
			var connection = new ConnectionBuilder()
				.WithLogging(minimumLogLevel: LogLevel.Trace)
				.Build();

			connection.Send("1", 1);
			connection.Send("2", 2);
			Thread.Sleep(5000);
			connection.Send("3", 3);

			connection.Listen();
		}
	}
}

What I would expect is, that the first two messages are sent immediately upon start of the program and then the third message is being sent after a 5 second delay.

But what happens is that no message is sent until those 5 seconds passed and then all are sent at once. Am I doing something wrong here?

.NET app as the master?

Hello,
I saw that currently the library works as if the main app is electron and it spawns a .NET application.
Is there a way to do it backwards? .NET app spawning Electron.
I tried some stuff like running electron which calls my app again, but then there is no way to debug the .NET (master) app.
Any suggestions?

Code Signing issue

Hello, I am wondering if the package in the NuGet.org for this particular package is code signed?

Thanks,
Ganda

Send<TRequestArgs, TResponseArgs>(string, TRequestArgs, Action<TResponseArgs>) fails to convert result to TResponseArgs type

This is the overload in question:

public void Send<TRequestArgs, TResponseArgs>(string requestType, TRequestArgs args, Action<TResponseArgs> responseHandler)

This fails to convert the raw response to TRequestArgs due to intermediate conversion via System.Object. This leads to errors of the following form:

2020-06-12 16:41:17.913 -07:00 [ERR] Failed to run response handler for request with id: 811e5a88-d5cb-480e-ae55-705a2962e4da
System.InvalidCastException: Object must implement IConvertible.
   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
   at System.Convert.ChangeType(Object value, Type conversionType)
   at ElectronCgi.DotNet.Connection.<>c__DisplayClass39_0`2.<SendAsync>b__0(Object arg) in /path/to/ElectronCgi.DotNet/Connection.cs:line 198
   at ElectronCgi.DotNet.ResponseHandler.HandleResponseAsync(Object argument) in /path/to/ElectronCgi.DotNet/IResponseHandler.cs:line 35
   at ElectronCgi.DotNet.ResponseHandlerExecutor.<>c__DisplayClass4_0.<<ExecuteAsync>b__0>d.MoveNext() in /path/to/ElectronCgi.DotNet/ResponseHandlerExecutor.cs:line 43

This is a result of SendAsync first converting the response to System.Object at

new Func<object, Task>(arg => responseHandlerAsync((TResponseArgs)Convert.ChangeType(arg, typeof(TResponseArgs))))));
since SendAsync is instantiated with TResponseArgs=System.Object. The handler in Send at
SendAsync(requestType, args, new Func<object, Task>(arg => { responseHandler((TResponseArgs)Convert.ChangeType(arg, typeof(TResponseArgs))); return Task.CompletedTask; }));
then attempts to convert this System.Object instance to the real TRequestArgs type using System.Convert.ChangeType which fails since System.Object does not implement IConvertible.

The fix is to instantiate SendAsync with the correct TRequestArgs type. This bug probably affects other overloads of Send and SendAsync.

Inconsistent with electron-cgi on registering multiple request handlers

electron-cgi allows to register multiple request handlers for a request type, while its dotnet counterpart will throw a DuplicateHandlerForRequestTypeException.

I think allow multiple subscription matches the design pattern of both .Net and NodeJs events. It is more familiar to programmers. Thanks.

Encoding Issues

I'm trying to receive some different special characters (é,í, ó, ñ ) from my Electron cgi application but when I receive the data I'm getting: �

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.