ruidfigueiredo / electron-cgi

A library to connect NodeJs application with executables from other languages
MIT License
148 stars 11 forks source link

error System.Threading.Tasks.Task when returning from an async function #31

Open thryfts opened 1 year ago

thryfts commented 1 year ago

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);
});
ruidfigueiredo commented 1 year ago

Are you sure you C# code compiles? There's missing using statements, there's the seemingly wrong function signature for getCred, it has Task<string> has a return type but String.Split returns a string[]

Another thing I noticed is that you are using connection.On in dotnet where probably what you want is:

connection.OnAsync<string, string[]>("getCred", async (string testing) =>
{
///...
});

Second template arg is the return type which from what I can tell is what you want, an array of strings (you can also omit the template args and just use OnAsync(...)).

Another thing that might be the cause of your issues is that warnings in dotnet go to the stdout stream, so if there are any warning when running your code like warning CS8602: Dereference of a possibly null reference. which probably will happen on this line string cred = parsedResult.cred; then you'll get a serialization error