Node JS run a c# program - c#

I have written a simple program in C# that saves to a text file every 5 seconds. I have also made a program in electron using node.js, is there a way I can start the C# program through electron?
I have tried compiling the C# program as an exe and running it that way but I couldn't get it to work.
Any help will be greatly appreciated!
Answer
The problem was that my C# file needed to be run as an administrator, I used the function below;
var exec = require('child_process').execFile;
var fun =function(){
console.log("fun() start");
exec('HelloJithin.exe', function(err, data) {
console.log(err)
console.log(data.toString());
});
}
fun();

You could just run a command with nodejs that starts the c# program.
const { exec } = require("child_process");
exec("cmd /K 'C:\SomeFolder\MyApp.exe'", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
DISCLAIMER: i haven't tested it because i am not on windows right now
source:
superuser
stackabuse

Related

How to import Rust library folder in my C# Program?

I want to use certain functions from a Rust library file but as you can see they require another file's data (config and a lot of others inside. The files are in the lib folder).
pub fn create(config: &Config, path: &Path) -> Result<()> {
if config.verbose {
info!("Creating new empty Mod Pack at {}.", path.to_string_lossy().to_string());
}
match &config.game {
Some(game) => {
let mut file = BufWriter::new(File::create(path)?);
let mut pack = Pack::new_with_version(game.pfh_version_by_file_type(PFHFileType::Mod));
pack.encode(&mut file, &None)?;
Ok(())
}
None => Err(anyhow!("No Game provided.")),
}
}
So how do I use this function in my c# program?

Problem with building C# code in Windows Service App

I have some server app. This app run, read some files, create C# classes, build this and load assembly. This app can work in two modes - one mode is window desktop application, and other mode - as windows service but core in dll is common.
Sometimes when this app work long time as service, and machine server has long timeup, they can't build anything. I attach to debugger, and debug. I debug .NET source (CompileAssemblyFromSource), and I see, that .NET classes just run csc.exe process with some params (CSharpCodeProvider class), but csc.exe run, return no errors or exceptions, output is blank and nothing is happend. No assembly is build.
I wrote some dump test service to compile code:
namespace CompilerService
{
public class Compiler
{
private Task _compilerTask;
public Compiler()
{
_compilerTask = Task.Run(() => CompileHalloWorld());
}
private const string _workingDir = #"C:\tmp";
private void CompileHalloWorld()
{
System.Threading.Thread.Sleep((30000));
if (!Directory.Exists(_workingDir))
{
Directory.CreateDirectory(_workingDir);
}
Directory.SetCurrentDirectory(_workingDir);
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = null;
try
{
results = csc.CompileAssemblyFromSource(parameters,
#"using System;
class Program {
public static void Main(string[] args) {
Console.WriteLine(""Hallo World!"");
}
}");
}
catch (Exception e)
{
int a = 2;
}
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
}
}
}
This dump service is fail too with build hallo world in this state of machine.
After restart machine, all work again ok, compile and load assembly all the time. After few weeks, problem come back, and we must reset server. This problem is on only one machine. On otger machines this service and csc.exe work perfect from years.
If machine is in this wird state, csc.exe dont build in windows service app, but when We run this app as Windows Desktop App all work fine, and csc.exe build normal...
Can you tell me, this is some known issue, oraz is some solution of don't compile csc.exe without machine restart?

Quantum Program The name 'BellTest' does not exist in the current context

This is my first Q# program and i'm following this getting started link.https://learn.microsoft.com/en-us/quantum/quantum-writeaquantumprogram?view=qsharp-preview
Error is
The name 'BellTest' does not exist in the current context
but its defined in the Bell.cs
I followed the steps and when building its having errors. I'm not sure how to import the operations from .qs file to driver c# file as this error looks like it can't find that operation.
Any help is really appreciated
Here is the code
Driver.cs
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace Quantum.Bell
{
class Driver
{
static void Main(string[] args)
{
using (var sim = new QuantumSimulator())
{
// Try initial values
Result[] initials = new Result[] { Result.Zero, Result.One };
foreach (Result initial in initials)
{
var res = BellTest.Run(sim, 1000, initial).Result;
var (numZeros, numOnes) = res;
System.Console.WriteLine(
$"Init:{initial,-4} 0s={numZeros,-4} 1s={numOnes,-4}");
}
}
System.Console.WriteLine("Press any key to continue...");
System.Console.ReadKey();
}
}
}
Bell.qs
namespace Quantum.Bell
{
open Microsoft.Quantum.Primitive;
open Microsoft.Quantum.Canon;
operation Set (desired:Result,q1:Qubit) : ()
{
body
{
let current = M(q1);
if (desired != current)
{
X(q1);
}
}
}
operation BellTest (count : Int, initial: Result) : (Int,Int)
{
body
{
mutable numOnes = 0;
using (qubits = Qubit[1])
{
for (test in 1..count)
{
Set (initial, qubits[0]);
let res = M (qubits[0]);
// Count the number of ones we saw:
if (res == One)
{
set numOnes = numOnes + 1;
}
}
Set(Zero, qubits[0]);
}
// Return number of times we saw a |0> and number of times we saw a |1>
return (count-numOnes, numOnes);
}
}
}
I also got the same error, but I was able to do it by pressing the F5 key.
Perhaps the Visual Studio editor is not yet fully support to the .qs file.
Namespace sharing does not seem to be working properly between .cs file and .qs file.
I was able to execute using your code in my development environment.
--
IDE: Visual Studio Community 2017 (Version 15.5.2)
Dev Kit: Microsoft Quantum Development Kit (0 and 1)
I engage the same problem in microsoft.quantum.development.kit/0.3.1811.203-preview version.
The BellTest operation cannot recognised by VSC Pic of VSCode
What I do is,
save all but keep VSCode open
go to directory and delete anything in bin/ obj/ by /bin/rm -rf bin obj
dotnet run
you go back to check VSCode, the BellTest recognised by VSC now.

Script Error when open .chm disappear when opening through the debugger

I get a number of script errors and none of the images will be shown when I open a .chm file on my computer. If I esc all error messages and refresh (twice) then the .chm is shown correctly. Although I need to do this for each new page.
I have made all recommended fixes for .chm files! Reregistrered, unblocked, fixed paths,... The errors is for all .chm on the machine
But, here is my real question, if I run this program, with a .chm file as argument, through the Visual Studio 2013 debugger then the .chm is shown correctly!
The problem is probably in my Windows configuration, but somehow the debugger "fixes" this error and get it to work. Does the debugger have it's own configuration that isn't dependent on the actual Windows configuration?
using System.Diagnostics;
namespace xcute
{
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
string f = args[0];
Process.Start(f);
}
}
}
}
EDIT: Here are the error dialogs
I have found the problem (well sort of)!
If I open the .chm as administrator then everything works! So obviously I have some permission error on my computer. The reason it worked when I ran my program in the debugger is that Visual Studio is started as Administrator...
But since I'm a programmer I solved the issue by creating a small program that start hh.exe as admin. I get the UAC consent form but I can live with that.
// Anders
The program:
internal class Program
{
private static void Main(string[] args)
{
if (args.Length > 0)
{
Execute(args[0]);
}
}
private static void Execute(string chmFile)
{
const int ERROR_CANCELLED = 1223; //The operation was canceled by the user.
ProcessStartInfo info = new ProcessStartInfo(#"C:\Windows\hh.exe");
info.Arguments = chmFile;
info.UseShellExecute = true;
info.Verb = "runas";
try
{
Process.Start(info);
}
catch (Win32Exception ex)
{
if (ex.NativeErrorCode == ERROR_CANCELLED)
Console.WriteLine("Why you no select Yes?");
else
throw;
}
}
}

c# mono get cpu usage of threads

How can i get the cpuload of running-threads of my application.
My application runs on linux, mac NOT windows.
I update mono to version 3.0.2.
Now i can get the correct thread-count of "Process.GetCurrentProcess().Threads" but no ProcessThread object is available to read the "TotalProcessorTime"
What can i do to calculate the cpu-usage/threads of my running application?
Can i get the linux-process-id of my running thread? If i can, i can read the proc directory structure but i can't find any way.
I hope someone can help me.
Apparently the Process.Threads property is only partially implemented at the moment:
// This'll return a correctly-sized array of empty ProcessThreads for now.
int error;
return new ProcessThreadCollection(new ProcessThread[GetProcessData (pid, 0, out error)]);
Not sure what trouble you have run into getting the process id, this code seems to work for me:
using System;
using System.Diagnostics;
using System.IO;
class MainClass
{
static void Main(string[] args)
{
int pid = Process.GetCurrentProcess().Id;
DirectoryInfo taskDir = new DirectoryInfo(String.Format("/proc/{0}/task", pid));
foreach(DirectoryInfo threadDir in taskDir.GetDirectories())
{
int tid = Int32.Parse(threadDir.Name);
Console.WriteLine(tid);
}
}
}

Categories

Resources