Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
simplified updating of Program.cs
  • Loading branch information
Stefan Pahontu committed Jul 21, 2022
commit 7d7b8063037ccdee7477b85b209daa8375596739
18 changes: 18 additions & 0 deletions src/mono/sample/wasm/console/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Runtime.InteropServices.JavaScript;

Console.WriteLine("Hello, Console");

public partial class MyClass
{
[JSExport]
internal static string Greeting() {
var text = $"Hello, World! Greetings from node version: {GetNodeVersion()}";
Console.WriteLine(text);
return text;
}

[JSImport("node.process.version")]
internal static partial string GetNodeVersion();

}
7 changes: 7 additions & 0 deletions src/mono/sample/wasm/console/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Node/CommonJS console App

Run the published application like:

node main.cjs

in `bin/$(Configuration)/net7.0/browser-wasm/AppBundle` directory.
192 changes: 192 additions & 0 deletions src/mono/sample/wasm/console/app-support.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// -*- mode: js; js-indent-level: 4; -*-
//
"use strict";
import createDotnetRuntime from './dotnet.js'
import { promises } from "fs";
import { argv } from "process";
const { readFile, stat } = promises;

const is_browser = false;
const is_node = !is_browser && typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node === 'string';
export const App = {};

if (!is_node)
throw new Error(`This file only supports nodejs`);

if (is_node && process.versions.node.split(".")[0] < 14) {
throw new Error(`NodeJS at '${process.execPath}' has too low version '${process.versions.node}'`);
}

function stringify_as_error_with_stack(err) {
if (!err)
return "";

// FIXME:
if (App && App.INTERNAL)
return App.INTERNAL.mono_wasm_stringify_as_error_with_stack(err);

if (err.stack)
return err.stack;

if (typeof err == "string")
return err;

return JSON.stringify(err);
}

function set_exit_code(exit_code, reason) {
if (reason) {
if (reason instanceof Error)
console.error(stringify_as_error_with_stack(reason));
else if (typeof reason == "string")
console.error(reason);
else
console.error(JSON.stringify(reason));
}

if (App && App.INTERNAL) {
let _flush = function(_stream) {
return new Promise((resolve, reject) => {
_stream.on('error', (error) => reject(error));
_stream.write('', function() { resolve () });
});
};
let stderrFlushed = _flush(process.stderr);
let stdoutFlushed = _flush(process.stdout);

Promise.all([ stdoutFlushed, stderrFlushed ])
.then(
() => App.INTERNAL.mono_wasm_exit(exit_code),
reason => {
console.error(`flushing std* streams failed: ${reason}`);
App.INTERNAL.mono_wasm_exit(123456);
});
}
}

let runArgs = {};
let is_debugging = false;

function initRunArgs() {
// set defaults
runArgs.applicationArguments = []; // not set in runArgs.json for non-browser cases
runArgs.workingDirectory = runArgs.workingDirectory === undefined ? '/' : runArgs.workingDirectory;
runArgs.environmentVariables = runArgs.environmentVariables === undefined ? {} : runArgs.environmentVariables;
runArgs.runtimeArgs = runArgs.runtimeArgs === undefined ? [] : runArgs.runtimeArgs;
runArgs.diagnosticTracing = runArgs.diagnosticTracing === undefined ? false : runArgs.diagnosticTracing;
runArgs.debugging = runArgs.debugging === undefined ? false : runArgs.debugging;
runArgs.forwardConsole = false; // not relevant for non-browser
}

function mergeArguments() {
let incomingArguments = argv.slice(2);

while (incomingArguments && incomingArguments.length > 0) {
const currentArg = incomingArguments[0];
if (currentArg.startsWith("--setenv=")) {
const arg = currentArg.substring("--setenv=".length);
const parts = arg.split('=');
if (parts.length != 2)
set_exit_code(1, "Error: malformed argument: '" + currentArg);
runArgs.environmentVariables[parts[0]] = parts[1];
} else if (currentArg.startsWith("--runtime-arg=")) {
const arg = currentArg.substring("--runtime-arg=".length);
runArgs.runtimeArgs.push(arg);
} else if (currentArg == "--diagnostic_tracing") {
runArgs.diagnosticTracing = true;
} else if (currentArg.startsWith("--working-dir=")) {
const arg = currentArg.substring("--working-dir=".length);
runArgs.workingDirectory = arg;
} else if (currentArg == "--debug") {
runArgs.debugging = true;
} else {
break;
}
incomingArguments = incomingArguments.slice(1);
}
runArgs.applicationArguments = incomingArguments;

is_debugging = runArgs.debugging === true;
}

let toAbsoluteUrl = function (path, prefix) {
if (prefix.startsWith("/")) {
return path;
}
return prefix + path;
}

try {
try {
if (await stat('./runArgs.json')) {
const argsJson = await readFile('./runArgs.json', { encoding: "utf8" });
runArgs = JSON.parse(argsJson);
console.debug(`runArgs: ${JSON.stringify(runArgs)}`);
}
} catch (err) {
console.debug(`could not load ./runArgs.json: ${err}. Ignoring`);
}
initRunArgs();
mergeArguments();

createDotnetRuntime(({ MONO, INTERNAL, BINDING, IMPORTS, Module }) => ({
disableDotnet6Compatibility: true,
config: null,
configSrc: "./mono-config.json",
locateFile: toAbsoluteUrl,
onConfigLoaded: (config) => {
if (!Module.config) {
const err = new Error("Could not find ./mono-config.json. Cancelling run");
set_exit_code(1);
throw err;
}
// Have to set env vars here to enable setting MONO_LOG_LEVEL etc.
for (let variable in runArgs.environmentVariables) {
config.environment_variables[variable] = runArgs.environmentVariables[variable];
}
config.diagnostic_tracing = !!runArgs.diagnosticTracing;
if (is_debugging) {
if (config.debug_level == 0)
config.debug_level = -1;

config.wait_for_debugger = -1;
}
},
onDotnetReady: async () => {
let wds = Module.FS.stat(runArgs.workingDirectory);
if (wds === undefined || !Module.FS.isDir(wds.mode)) {
set_exit_code(1, `Could not find working directory ${runArgs.working_dir}`);
return;
}

Module.FS.chdir(runArgs.workingDirectory);

if (runArgs.runtimeArgs.length > 0)
INTERNAL.mono_wasm_set_runtime_options(runArgs.runtimeArgs);

Object.assign(App, { MONO, BINDING, IMPORTS, Module, runArgs });

try {
if (App.main) {
let exit_code = await App.main(runArgs.applicationArguments);
set_exit_code(exit_code ?? 0);
}
else {
set_exit_code(1, "WASM ERROR: no App.main defined");
}
} catch (err) {
if (is_browser && document.getElementById("out"))
document.getElementById("out").innerHTML = `error: ${err}`;
set_exit_code(1, err);
}
},
onAbort: (error) => {
set_exit_code(1, error);
},
}));
}
catch (err) {
set_exit_code(2, err);
}
23 changes: 23 additions & 0 deletions src/mono/sample/wasm/console/console.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetArchitecture>wasm</TargetArchitecture>
<TargetOS>browser</TargetOS>
<RuntimeIdentifier>browser-wasm</RuntimeIdentifier>
<UseMonoRuntime>true</UseMonoRuntime>
<WasmMainJSPath>main.mjs</WasmMainJSPath>
<OutputType>Exe</OutputType>
<PublishTrimmed>true</PublishTrimmed>
<WasmEmitSymbolMap Condition="'$(RunAOTCompilation)' != 'true'">true</WasmEmitSymbolMap>
</PropertyGroup>
<PropertyGroup>
<_SampleProject>console.csproj</_SampleProject>
</PropertyGroup>
<Target Name="RunSample" DependsOnTargets="RunSampleWithBrowser" />
<Target Name="RunSample" DependsOnTargets="RunSampleWithNode" />
<ItemGroup>
<WasmExtraFilesToDeploy Include="app-support.mjs" />
<ProjectReference Include="$(LibrariesProjectRoot)System.Runtime.InteropServices\gen\Microsoft.Interop.SourceGeneration\Microsoft.Interop.SourceGeneration.csproj" OutputItemTe="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="$(LibrariesProjectRoot)System.Runtime.InteropServices.JavaScript\gen\JSImportGenerator\JSImportGenerator.csproj" OutputItemType="Analyzer" ReferencutputAssembly="false" />
</ItemGroup>
</Project>
25 changes: 25 additions & 0 deletions src/mono/sample/wasm/console/console.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32708.82
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "console", "console.csproj", "{3314C4A3-00FD-44C3-B77E-CCF3281A1E3B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3314C4A3-00FD-44C3-B77E-CCF3281A1E3B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3314C4A3-00FD-44C3-B77E-CCF3281A1E3B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3314C4A3-00FD-44C3-B77E-CCF3281A1E3B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3314C4A3-00FD-44C3-B77E-CCF3281A1E3B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1CB078F1-EA87-46B8-BADB-F00B0554DFA1}
EndGlobalSection
EndGlobal
16 changes: 16 additions & 0 deletions src/mono/sample/wasm/console/main.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { App } from './app-support.mjs'

App.main = async function (applicationArguments) {

App.IMPORTS.node = {
process : {
version: () => globalThis.process.version
}
};

const exports = await App.MONO.mono_wasm_get_assembly_exports("console.dll");
const text = exports.MyClass.Greeting();
console.log(text);

await App.MONO.mono_run_main("console.dll", applicationArguments);
}
4 changes: 4 additions & 0 deletions src/mono/sample/wasm/console/run.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
dotnet build
cd .\bin\Debug\AppBundle\
node .\main.mjs
cd ../../../
16 changes: 16 additions & 0 deletions src/mono/sample/wasm/console/runtimeconfig.template.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"wasmHostProperties": {
"perHostConfig": [
{
"name": "node",
"js-path": "main.mjs",
"Host": "nodejs"
},
{
"name": "v8",
"js-path": "main.mjs",
"Host": "v8"
}
]
}
}
19 changes: 19 additions & 0 deletions src/mono/sample/wasm/consoleAlin/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System;
using System.Runtime.InteropServices.JavaScript;

Console.WriteLine("Hello, Console");

public partial class MyClass
{
[JSExport]
internal static string Greeting()
{
var text = $"Hello, World! Greetings from node version: {GetNodeVersion()}";
Console.WriteLine(text);
return text;
}

[JSImport("node.process.version")]
internal static partial string GetNodeVersion();

}
7 changes: 7 additions & 0 deletions src/mono/sample/wasm/consoleAlin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Node/CommonJS console App

Run the published application like:

node main.cjs

in `bin/$(Configuration)/net7.0/browser-wasm/AppBundle` directory.
Loading