ruidfigueiredo / electron-cgi Goto Github PK
View Code? Open in Web Editor NEWA library to connect NodeJs application with executables from other languages
License: MIT License
A library to connect NodeJs application with executables from other languages
License: MIT License
I was trying to use electron-cgi in a typescript electron application and had an issue because I couldn't get the Connection type since the change in #9 removed exporting it from index.d.ts
The specific code in my app that wants me to have Connection's type is:
let connection: Connection; // <- where I need the Connection type
if (process.env.NODE_ENV === 'production') {
connection = new ConnectionBuilder()
.connectTo('dotnet', './resources/server/server.dll')
.build();
} else {
connection = new ConnectionBuilder()
.connectTo('dotnet', 'run', '--project', '../server')
.build();
}
Adding export {Connection} from './connection'
to index.d.ts lets me use import { ConnectionBuilder, Connection } from 'electron-cgi';
in my app, which solves the issue for me.
Is there an alternate way to get the type of Connection, or should it be added back to index.d.ts?
What would be the correct way to build and bundle with a built .NET application?
There should be a way to remove any listener that we add to the connection. Because, sometimes we want to remove the listener as well or change the listener for that specified event type.
Thanks.
Is it possible to add customized MagicWord to separated individual requests or responses when constructing the connection, while '\t'
is used as the default MagicWord. There are some cases where '\t'
is contained in the object.
Provide a way to start the connection from .Net file to Node/electron file. My use case is opening Electron app on Excel Add in's button click
Response handler in example in documentation appears to be wrong:
connection.send('greeting', 'John', theGreeting => {
console.log(theGreeting); // will print "Hello John!"
});
theGreeting
is always null
. This is confirmed by looking at the code which invokes the response handler:
https://github.com/ruidfigueiredo/electron-cgi/blob/master/connection.js#L25
This change was introduced in 2d07554.
So, I assume that this handler signature change is intentional and that the documentation is just out of date.
Hi,
I am using Tauri to build a desktop app (+angular), the backend is .net framework.
I would want to use electron-cgi to communicate between the frontend and backend.
Tauri is based on Rust language (not Node.js like electron),
do you think it's possible?
should I change any part in the code of electron-CGI in order to adjust it to Tauri?
thanks in advance.
when I await the data I want to send to Electron Js I get error One or more errors occurred. (Serialisation failed for: { Type = RESPONSE, Response = ElectronCgi.DotNet.Response`1[System.Threading.Tasks.Task`1[System.String]] }.)
. Why is this error occurring? I am awaiting the response from the post request I made so System.Threading.Tasks.Task
shouldn't be occurring. Where did I go wrong? Thanks in advance.
C#
using ElectronCgi.DotNet;
static void Main(string[] args) {
var connection = new ConnectionBuilder()
.WithLogging()
.Build();
static async Task < string > getCred(string testing) {
using
var client = new HttpClient();
var jsonString = "{\"requestType\": \"" + testing + "\"}";
var data = new StringContent(jsonString, Encoding.UTF8, "application/json");
var url = "http://serverIp:port/api/server";
var response = await client.PostAsync(url, data);
string result = await response.Content.ReadAsStringAsync();
dynamic parsedResult = JsonConvert.DeserializeObject(result);
string cred = parsedResult.cred;
var credArrVec = cred.Split('\n');
return credArrVec;
}
connection.On("getCred", async(string testing) => {
//error occurs here
var test = await getCred(testing);
return test;
});
connection.Listen();
}
Node Js
const {
ConnectionBuilder
} = require("electron-cgi");
const connection = new ConnectionBuilder()
.connectTo("dotnet", "run", "--project", "../testProject")
.build();
connection.onDisconnect = () => {
console.log("Connection between node and .net lost");
};
connection.send("getCred", "testCred", (error, res) => {
if (error) {
console.log(error); //serialized exception from the .NET handler
return;
}
console.log(res);
});
Firstly, let me thank @ruidfigueiredo for not just coming up with this idea but implementing it. I find it to be an excellent alternative to electron.net, neutronium etc. since I want to keep the vue ui code separate from the c# but still be able to interact with each other on demand.
That said, I'm having two issues:
connection.send('greeting', 'John', (error, theGreeting) => {
if (error) {
console.log(error); // always triggered..even when no error
return;
}
console.log(theGreeting); // never gets called
});
const connection = new ConnectionBuilder()
.connectTo('dotnet', 'run', '--project', 'DotNetConsoleProjectWithElectronCgiDotNetNugetPackage')
.build();
Btw, I'm currently using this approach, which works but I don't have the benefit of .net watcher:
const connection = new ConnectionBuilder()
.connectTo('C:/folder/DotNetConsoleProjectWithElectronCgiDotNetNugetPackage.exe')
.build();
These issues are in the context of a vue app built with vuetify, electron-nuxt, vuex and a .net framework 4.7.2 console app built in visual studio 2019. Latest version of electron-cgi used in both cases.
Thanks, in advance for your assistance. I'm not an expert in c# or javascript but I know a thing or two and I'm willing to contribute where I can.
This causes future npm install
commands to fail as follows:
npm ERR! code EISGIT
npm ERR! path /Users/name/src/electron-typescript-app/node_modules/electron-cgi
npm ERR! git /Users/name/src/electron-typescript-app/node_modules/electron-cgi: Appears to be a git repo or submodule.
npm ERR! git /Users/name/src/electron-typescript-app/node_modules/electron-cgi
npm ERR! git Refusing to remove it. Update manually,
npm ERR! git or move it out of the way first.
This also interferes with the use of git clean
and other git commands in the referencing project.
result: JSON.stringify(resultArgs || null)
When the resultArgs
is 0, ''(empty string), NaN, null, undefined
, the result
will be all evaluated to null
! It is better to convert underfined
only to null
, as other values are usually used as valid return values.
Consider:
result: JSON.stringify(resultArgs === undefined ? null : resultArgs)
Hi,
I'm new in electron cgi ,
@ruidfigueiredo - do you have an example of a project containing Angular + C# code + Electron cgi?
As I checked - all the examples you shared contain electron cgi + react.
it could help me a lot to do my first steps.
thanks
My repo is here: https://github.com/fairking/electron-cgi-calculator-demo
If I try to run the project everything works fine so far.
But if I create a snap package and then install it on the linux machine the line:
_connection = new ConnectionBuilder().connectTo('./DotNetCalculator/DotNetCalculator').build();
the line complains about missing DotNetCalculator
file.
Can somebody help to figure out what is going on?
The file is definitely there.
Thanks
Hi Rui,
I have been using Electron-CGI in my development of a windows desktop application with a C# backend. Throughout development and when debugging, everything seems to be working correctly. However, when I package the application and run the .exe version of the program, the connection to Electron-CGI is repeatedly lost on startup. Do you have any suggestions on how I can approach this issue?
I have tried different packaging methods, using Electron-Forge and electron-packager.
Any help would be much appreciated, thank you!
Instead of relying on console.log, it would be nice to emit errors coming from the spawned process.
Right now when there is an issue with ConnectionBuilder.build(), there is no way for the electron application to know that there is an issue.
I'm trying to convert a "windows form" application to work with electron-cgi because I want the entire UI to be made with electron
I noticed that the windows form UI does not appear until I close the connection from electron is it possible to fix this?
I guess It might be because the current project is not multithread?
Because when I remove the ConnectionBuilder code the form app appears
Hi, I have similar problem as Tim Antonius mentioned here: https://github.com/ruidfigueiredo/electron-cgi/issues/2 My app works in development mode. But when I packaged it, it stopped working. I understand that the dotnet csproj path might change in packaged version and I checked in resource folder as you mentioned. But in resource folder, I see only icons. Also, I couldn't find where logs are stored. Can you please help me with package version and logs?
Hello,
I followed the instructions in the README as well as the tutorial you posted: https://www.youtube.com/watch?v=-aJDzyGgNLY
This is the code in index.js of the elctron-node-demo app:
const { ConnectionBuilder } = require('electron-cgi');
let connection = new ConnectionBuilder()
.connectTo('dotnet', 'run', '--project', '../ElectronCgiDotNetDemo')
.build();
connection.onDisconnect = () => {
console.log('Connection between node and .net lost')
};
connection.send('greeting', 'Mahesh', response => {
console.log("message is " + response);
connection.close();
});
And this is the code in the .NET console app:
using System;
using ElectronCgi.DotNet;
namespace ElectronCgiDotNetDemo // Note: actual namespace depends on the project name.
{
internal class Program
{
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("greeting", (string name) =>
{
return $"Hello {name}!";
});
// wait for incoming requests
connection.Listen();
}
}
}
When I run node index.js I get the following error:
As you can see it is generating the JSON object from the console app correctly:
{"type":"RESPONSE","response":{"result":"Hello Mahesh!","id":"4529207b-c562-4bd6-9155-45106dd06054"}}
But it is erroring at this line in the elctron-cgi code:
Are you able to reproduce this? Please let me know.
Thank you.
inputStreamParser.onRequest(request => { const requestType = request.type; requestHandlersQueue.filter(rh => rh.type === requestType).forEach(handlerContainer => { const requestHandler = handlerContainer.onRequest; const resultArgs = requestHandler(request.args) sendResponse(request.id, resultArgs); }); });
What if requestHandlersQueue.filter
returns an empty array, maybe because the programmer forgot to subscribe it or a typo in the requestType
.
It is better to check the outcome of requestHandlersQueue.filter
, and throw an error when it is empty.
Can you provide any documentation or guidance on distributing apps created with electron-cgi. How to publish this app with .net code?
The connection.d.ts file generates the error below during compilation.
It looks like this is due to a breaking change in typescript 2.6.1.
how to connect the app from published .exe?
.connectTo('dotnet', 'run', '--project', 'app.exe')
does not work
Hey,
great package you have going on here, I really like it.
Im starting new project and Im looking for solution that connects c# with electron and I like your solution to this.
I just wanted to ask if this package is still being worked on what is current state.
And one more question, is there a posibility to connect to running c# project in debug mode and debug my c# code?
I havent found anything about this.
Thanks J.
Hello, I'm working with a friend on making a modding tool for games.
My friend makes the entire pointer system and game modding code in C# and I need to take care of the UI;
I want to make clear that both the c# .exe and electron will run on the same machine and I cannot just add the C# project source to the electron project because It needs to be closed source and obfuscated to avoid misuse of our code.
So, can electron-cgi work with an already built and obfuscated C# executable?
Hi @ruidfigueiredo, thank for your great work. I'm new to electron. Trying to develop a combination with electron , angular and C#. I'm facing a issue everytime when electron run code below. I get "null", "lost", "Connection to dotnet was terminated (code: 0)" on my console log. And of course, there is no connections between electon & c# console. electron-cgi.log is created but the content is empty.
Any idea, why this issue happen? Any help would be greatful!
Electron side:
const { ConnectionBuilder } = require("electron-cgi");
let connection = new ConnectionBuilder()
.connectTo("dotnet", "run", "--project", "./core")
.build();
connection.onDisconnect = () => {
console.log("lost");
};
connection.send("greeting", "Jack", (response: any) => {
console.log(response);
connection.close();
});
C# console side:
static void Main(string[] args)
{
var connection = new ConnectionBuilder()
.WithLogging()
.Build();
connection.On<string, string>("greeting", name => "Hello " + name);
connection.Listen();
}
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.