public async void TryInvokeFromCacheAsync_WithTypeParameter_CreatesInvocationRequestAndCallsTryInvokeCoreAsync()
        {
            // Arrange
            const int             dummyResult = 1;
            const string          dummyModuleCacheIdentifier = "dummyModuleCacheIdentifier";
            const string          dummyExportName            = "dummyExportName";
            var                   dummyArgs = new object[0];
            var                   dummyCancellationToken = new CancellationToken();
            Mock <INodeJSService> mockNodeJSService      = _mockRepository.Create <INodeJSService>();

            mockNodeJSService.
            Setup(t => t.TryInvokeFromCacheAsync <int>(dummyModuleCacheIdentifier, dummyExportName, dummyArgs, dummyCancellationToken)).
            ReturnsAsync((true, dummyResult));
            var dummyServices = new ServiceCollection();

            dummyServices.AddSingleton(typeof(INodeJSService), mockNodeJSService.Object);
            StaticNodeJSService.SetServices(dummyServices);

            // Act
            (bool success, int result) = await StaticNodeJSService.TryInvokeFromCacheAsync <int>(dummyModuleCacheIdentifier, dummyExportName, dummyArgs, dummyCancellationToken).ConfigureAwait(false);

            // Assert
            Assert.True(success);
            Assert.Equal(dummyResult, result);
            _mockRepository.VerifyAll();
        }
Example #2
0
        public void Configure(IApplicationBuilder app)
        {
            app.UseWebSockets();
            app.UseDotNetify(c => c.UseDeveloperLogging());

#pragma warning disable 618
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true,
                HotModuleReplacementClientOptions = new Dictionary <string, string> {
                    { "reload", "true" }
                },
            });
#pragma warning restore 618

            app.UseStaticFiles();
            app.UseRouting();

            app.UseEndpoints(endpoints => endpoints.MapHub <DotNetifyHub>("/dotnetify"));
            app.UseSsr(typeof(App), (string[] args) => StaticNodeJSService.InvokeFromFileAsync <string>("wwwroot/ssr", null, args));

            app.Run(async(context) =>
            {
                // Client-side rendering.
                using (var reader = new StreamReader(File.OpenRead("wwwroot/index.html")))
                    await context.Response.WriteAsync(reader.ReadToEnd());
            });
        }
        public void AllInvokeMethods_AreThreadSafe()
        {
            // Arrange
            const string dummyResultString = "success";

            // Act
            var       results    = new ConcurrentQueue <DummyResult>();
            const int numThreads = 5;
            var       threads    = new List <Thread>();

            for (int i = 0; i < numThreads; i++)
            {
                var thread = new Thread(() => results.Enqueue(StaticNodeJSService.InvokeFromStringAsync <DummyResult>("module.exports = (callback, resultString) => callback(null, {result: resultString});", args: new[] { dummyResultString }).GetAwaiter().GetResult()));
                threads.Add(thread);
                thread.Start();
            }
            foreach (Thread thread in threads)
            {
                thread.Join();
            }

            // Assert
            Assert.Equal(numThreads, results.Count);
            foreach (DummyResult result in results)
            {
                Assert.Equal(dummyResultString, result.Result);
            }
        }
        public async void Configure_ConfiguresOptions()
        {
            // Arrange
            const int    dummyInitialInvocationResult = 1;
            const string dummyTestVariableName1       = "TEST_VARIABLE_1";
            const string dummyTestVariableValue1      = "testVariableValue1";
            const string dummyTestVariableName2       = "TEST_VARIABLE_2";
            const string dummyTestVariableValue2      = "testVariableValue2";

            // Act
            // Invoke javascript once to ensure that an initial NodeJSService is created. The invocation after configuration should properly dispose of this initial instance and create a new one with the
            // specified options.
            int initialInvocationResult = await StaticNodeJSService.
                                          InvokeFromStringAsync <int>($"module.exports = (callback) => callback(null, {dummyInitialInvocationResult});").ConfigureAwait(false);

            StaticNodeJSService.
            Configure <NodeJSProcessOptions>(options => options.EnvironmentVariables.Add(dummyTestVariableName1, dummyTestVariableValue1));
            StaticNodeJSService.
            Configure <NodeJSProcessOptions>(options => options.EnvironmentVariables.Add(dummyTestVariableName2, dummyTestVariableValue2));

            // Assert
            Assert.Equal(dummyInitialInvocationResult, initialInvocationResult);
            DummyResult result = await StaticNodeJSService.
                                 InvokeFromStringAsync <DummyResult>($"module.exports = (callback) => callback(null, {{result: process.env.{dummyTestVariableName1} + process.env.{dummyTestVariableName2}}});").
                                 ConfigureAwait(false);

            Assert.Equal(dummyTestVariableValue1 + dummyTestVariableValue2, result.Result);
        }
        public async void InvokeFromStringAsync_WithTypeParameter_WithRawStringModule_InvokesFromString()
        {
            // Arrange
            const int             dummyResult             = 1;
            const string          dummyModuleString       = "dummyModuleString";
            const string          dummyNewCacheIdentifier = "dummyNewCacheIdentifier";
            const string          dummyExportName         = "dummyExportName";
            var                   dummyArgs = new object[0];
            var                   dummyCancellationToken = new CancellationToken();
            Mock <INodeJSService> mockNodeJSService      = _mockRepository.Create <INodeJSService>();

            mockNodeJSService.
            Setup(t => t.InvokeFromStringAsync <int>(dummyModuleString, dummyNewCacheIdentifier, dummyExportName, dummyArgs, dummyCancellationToken)).
            ReturnsAsync(dummyResult);
            var dummyServices = new ServiceCollection();

            dummyServices.AddSingleton(typeof(INodeJSService), mockNodeJSService.Object);
            StaticNodeJSService.SetServices(dummyServices);

            // Act
            int result = await StaticNodeJSService.InvokeFromStringAsync <int>(dummyModuleString, dummyNewCacheIdentifier, dummyExportName, dummyArgs, dummyCancellationToken).ConfigureAwait(false);

            // Assert
            Assert.Equal(dummyResult, result);
            _mockRepository.VerifyAll();
        }
Example #6
0
        public async void SetServices_RestartsNodeJSProcessWithNewServices()
        {
            // Arrange
            const string dummyTestVariableName   = "TEST_VARIABLE_1";
            const string dummyTestVariableValue1 = "testVariableValue1";
            const string dummyTestVariableValue2 = "testVariableValue2";

            StaticNodeJSService.Configure <NodeJSProcessOptions>(options => options.EnvironmentVariables.Add(dummyTestVariableName, dummyTestVariableValue1));
            string result1 = await StaticNodeJSService.
                             InvokeFromStringAsync <string>($"module.exports = (callback) => callback(null, process.env.{dummyTestVariableName});").ConfigureAwait(false);

            var dummyServices = new ServiceCollection();

            dummyServices.
            AddNodeJS().
            Configure <NodeJSProcessOptions>(options => options.EnvironmentVariables.Add(dummyTestVariableName, dummyTestVariableValue2));

            // Act
            StaticNodeJSService.SetServices(dummyServices);

            // Assert
            string result2 = await StaticNodeJSService.
                             InvokeFromStringAsync <string>($"module.exports = (callback) => callback(null, process.env.{dummyTestVariableName});").ConfigureAwait(false);

            Assert.Equal(dummyTestVariableValue1, result1);
            Assert.Equal(dummyTestVariableValue2, result2);
        }
Example #7
0
        public void AllInvokeMethods_AreThreadSafe()
        {
            // Arrange
            StaticNodeJSService.DisposeServiceProvider(); // In case previous test registered a custom service

            // Act
            var       results    = new ConcurrentQueue <string>();
            const int numThreads = 5;
            var       threads    = new List <Thread>();

            for (int i = 0; i < numThreads; i++)
            {
                var thread = new Thread(() => results.Enqueue(StaticNodeJSService.InvokeFromStringAsync <string>("module.exports = (callback) => callback(null, process.pid);").GetAwaiter().GetResult()));
                threads.Add(thread);
                thread.Start();
            }
            foreach (Thread thread in threads)
            {
                thread.Join();
            }

            // Assert
            Assert.Equal(numThreads, results.Count);
            Assert.Single(results.Distinct()); // All invocations should run in process started by first invocation
        }
Example #8
0
        public static async Task <T> InvokeNode <T>(BotData data, string scriptFile, object[] parameters)
        {
            data.Logger.LogHeader();
            var result = await StaticNodeJSService.InvokeFromFileAsync <T>(scriptFile, null, parameters, data.CancellationToken);

            data.Logger.Log($"Executed NodeJS script with result: {result}", LogColors.PaleChestnut);
            return(result);
        }
Example #9
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMemoryCache();
            services.AddSignalR();
            services.AddDotNetify();

            StaticNodeJSService.Configure <OutOfProcessNodeJSServiceOptions>(options => options.TimeoutMS = 2000);
        }
Example #10
0
        private async Task <string[]> RunCoreAsync()
        {
            string code = await runnableCode.Value;

            string[] output = await StaticNodeJSService.InvokeFromStringAsync <string[]>(code);

            return(output);
        }
        public async void InvokeFromFileAsync_InvokesJavascript()
        {
            // Arrange
            const string dummyResultString = "success";

            // Act
            DummyResult result = await StaticNodeJSService.
                                 InvokeFromFileAsync <DummyResult>("dummyModule.js", args : new[] { dummyResultString }).ConfigureAwait(false);

            // Assert
            Assert.Equal(dummyResultString, result.Result);
        }
        public async void InvokeFromStringAsync_InvokesJavascript()
        {
            // Arrange
            const string dummyResultString = "success";

            // Act
            DummyResult result = await StaticNodeJSService.
                                 InvokeFromStringAsync <DummyResult>("module.exports = (callback, resultString) => callback(null, {result: resultString});", args : new[] { dummyResultString }).ConfigureAwait(false);

            // Assert
            Assert.Equal(dummyResultString, result.Result);
        }
        public async void TryInvokeFromCacheAsync_ReturnsFalseIfModuleIsNotCached()
        {
            // Arrange
            const string dummyResultString    = "success";
            const string dummyCacheIdentifier = "dummyCacheIdentifier";

            // Act
            (bool success, DummyResult value) = await StaticNodeJSService.TryInvokeFromCacheAsync <DummyResult>(dummyCacheIdentifier, args : new[] { dummyResultString }).ConfigureAwait(false);

            // Assert
            Assert.False(success);
            Assert.Null(value);
        }
    public async Task Calc(CommandContext ctx, [RemainingText] string input)
    {
        var lang = await Language.GetLanguageFromCtxAsync(ctx);

        StringBuilder builder = new("```");

        foreach (var step in
                 await StaticNodeJSService.InvokeFromStringAsync <MathStep[]>(Jscode, args: new object[] { input }))
        {
            builder.Append(step.OldVal).Append(' ').Append(step.Step).Append(' ').AppendLine(step.NewVal);
        }
        builder.Append("```");
        await new DiscordMessageBuilder().WithContent(lang.MathSteps + builder).SendAsync(ctx.Channel);
    }
Example #15
0
        public async Task <string> Parse(string input)
        {
            string output;

            try
            {
                output = await StaticNodeJSService.InvokeFromStringAsync <string>(_DPackJs, "parse", args : new object[] { input });
            }
            catch (Exception ex)
            {
                output = ex.Message;
            }

            return(output);
        }
Example #16
0
        public void ConfigureServices(IServiceCollection services)
        {
            // Add OpenID Connect server to produce JWT access tokens.
            services.AddAuthenticationServer();

            services.AddSignalR()
            //.AddMessagePackProtocol()
            ;
            services.AddDotNetify();
            services.AddDotNetifyPulse();
            services.AddMvc();

            services.AddScoped <IEmployeeRepository, EmployeeRepository>();
            services.AddSingleton <IMovieService, MovieService>();
            services.AddSingleton <IWebStoreService, WebStoreService>();

            StaticNodeJSService.Configure <OutOfProcessNodeJSServiceOptions>(options => options.TimeoutMS = 2000);
        }
Example #17
0
        public async void DisposeServiceProvider_RestartsNodeJSProcess()
        {
            // Arrange
            const string dummyTestVariableName  = "TEST_VARIABLE";
            const string dummyTestVariableValue = "testVariableValue";

            StaticNodeJSService.Configure <NodeJSProcessOptions>(options => options.EnvironmentVariables.Add(dummyTestVariableName, dummyTestVariableValue));
            string result1 = await StaticNodeJSService.
                             InvokeFromStringAsync <string>($"module.exports = (callback) => callback(null, process.env.{dummyTestVariableName});").ConfigureAwait(false);

            // Act
            StaticNodeJSService.DisposeServiceProvider(); // Dispose, environment variable should not be set in the next call

            // Assert
            string result2 = await StaticNodeJSService.
                             InvokeFromStringAsync <string>($"module.exports = (callback) => callback(null, process.env.{dummyTestVariableName});").ConfigureAwait(false);

            Assert.Equal(dummyTestVariableValue, result1);
            Assert.Equal(string.Empty, result2);
        }
        public async void TryInvokeFromCacheAsync_InvokesJavascriptIfModuleIsCached()
        {
            // Arrange
            const string dummyResultString    = "success";
            const string dummyCacheIdentifier = "dummyCacheIdentifier";

            // Cache
            await StaticNodeJSService.
            InvokeFromStringAsync <DummyResult>("module.exports = (callback, resultString) => callback(null, {result: resultString});",
                                                dummyCacheIdentifier,
                                                args : new[] { dummyResultString }).
            ConfigureAwait(false);

            // Act
            (bool success, DummyResult value) = await StaticNodeJSService.TryInvokeFromCacheAsync <DummyResult>(dummyCacheIdentifier, args : new[] { dummyResultString }).ConfigureAwait(false);

            // Assert
            Assert.True(success);
            Assert.Equal(dummyResultString, value.Result);
        }
        public async void InvokeFromStreamAsync_InvokesJavascript()
        {
            // Arrange
            const string dummyResultString = "success";

            DummyResult result;

            using (var memoryStream = new MemoryStream())
                using (var streamWriter = new StreamWriter(memoryStream))
                {
                    streamWriter.Write("module.exports = (callback, resultString) => callback(null, {result: resultString});");
                    streamWriter.Flush();
                    memoryStream.Position = 0;

                    // Act
                    result = await StaticNodeJSService.InvokeFromStreamAsync <DummyResult>(memoryStream, args : new[] { dummyResultString }).ConfigureAwait(false);
                }

            // Assert
            Assert.Equal(dummyResultString, result.Result);
        }
        public async void InvokeFromFileAsync_WithoutTypeParameter_InvokesFromFile()
        {
            // Arrange
            const string          dummyModulePath        = "dummyModulePath";
            const string          dummyExportName        = "dummyExportName";
            var                   dummyArgs              = new object[0];
            var                   dummyCancellationToken = new CancellationToken();
            Mock <INodeJSService> mockNodeJSService      = _mockRepository.Create <INodeJSService>();

            mockNodeJSService.
            Setup(t => t.InvokeFromFileAsync(dummyModulePath, dummyExportName, dummyArgs, dummyCancellationToken));
            var dummyServices = new ServiceCollection();

            dummyServices.AddSingleton(typeof(INodeJSService), mockNodeJSService.Object);
            StaticNodeJSService.SetServices(dummyServices);

            // Act
            await StaticNodeJSService.InvokeFromFileAsync(dummyModulePath, dummyExportName, dummyArgs, dummyCancellationToken).ConfigureAwait(false);

            // Assert
            _mockRepository.VerifyAll();
        }
        public async void DisposeServiceProvider_DisposesServiceProvider()
        {
            // Arrange
            const string dummyTestVariableName  = "TEST_VARIABLE";
            const string dummyTestVariableValue = "testVariableValue";

            StaticNodeJSService.
            Configure <NodeJSProcessOptions>(options => options.EnvironmentVariables.Add(dummyTestVariableName, dummyTestVariableValue));
            DummyResult initialInvocationResult = await StaticNodeJSService.
                                                  InvokeFromStringAsync <DummyResult>($"module.exports = (callback) => callback(null, {{result: process.env.{dummyTestVariableName}}});").
                                                  ConfigureAwait(false);

            // Act
            StaticNodeJSService.DisposeServiceProvider(); // Dispose, environment variable should not be set in the next call
            DummyResult result = await StaticNodeJSService.
                                 InvokeFromStringAsync <DummyResult>($"module.exports = (callback) => callback(null, {{result: process.env.{dummyTestVariableName}}});").
                                 ConfigureAwait(false);

            // Assert
            Assert.Equal(dummyTestVariableValue, initialInvocationResult.Result);
            Assert.Null(result.Result);
        }
        public async void InvokeFromStreamAsync_WithoutTypeParameter_WithModuleFactory_IfModuleIsCachedInvokesFromCacheOtherwiseInvokesFromStream()
        {
            // Arrange
            Func <Stream>         dummyModuleFactory     = () => new MemoryStream();
            const string          dummyCacheIdentifier   = "dummyCacheIdentifier";
            const string          dummyExportName        = "dummyExportName";
            var                   dummyArgs              = new object[0];
            var                   dummyCancellationToken = new CancellationToken();
            Mock <INodeJSService> mockNodeJSService      = _mockRepository.Create <INodeJSService>();

            mockNodeJSService.
            Setup(t => t.InvokeFromStreamAsync(dummyModuleFactory, dummyCacheIdentifier, dummyExportName, dummyArgs, dummyCancellationToken));
            var dummyServices = new ServiceCollection();

            dummyServices.AddSingleton(typeof(INodeJSService), mockNodeJSService.Object);
            StaticNodeJSService.SetServices(dummyServices);

            // Act
            await StaticNodeJSService.InvokeFromStreamAsync(dummyModuleFactory, dummyCacheIdentifier, dummyExportName, dummyArgs, dummyCancellationToken).ConfigureAwait(false);

            // Assert
            _mockRepository.VerifyAll();
        }
Example #23
0
        public void Configure(IApplicationBuilder app)
        {
            app.UseWebSockets();
            app.UseDotNetify(c => c.UseDeveloperLogging());

#pragma warning disable 618
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true,
                HotModuleReplacementClientOptions = new Dictionary <string, string> {
                    { "reload", "true" }
                },
            });
#pragma warning restore 618

            app.UseStaticFiles();
            app.UseRouting();
            app.UseEndpoints(endpoints => endpoints.MapHub <DotNetifyHub>("/dotnetify"));

            app.UseSsr(typeof(App), (string[] args) => StaticNodeJSService.InvokeFromFileAsync <string>("wwwroot/ssr", null, args), DefaultRequestHandler);

            // Client-side rendering.
            app.Run(DefaultRequestHandler);
        }
Example #24
0
        /// <summary>
        /// Converts a pdf to pngs
        /// </summary>
        /// <param name="pathToPdf"></param>
        /// <param name="pathToPngOutput">Prefix of file path to pngs created for each page of pdf. E.g. c:\temp\PdfPage will result in c:\temp\PdfPage1.png and c:\temp\PdfPage2.png for a Pdf with two pages.</param>
        /// <returns>Collection of paths to pngs for each page in the pdf</returns>
        public async Task <IReadOnlyList <string> > ConvertToPngAsync(string pathToPdf, string pathToPngOutput)
        {
            await InitNodeModules().ConfigureAwait(false);

            var assembly = Assembly.GetExecutingAssembly();
            var stream   = assembly.GetManifestResourceStream("Codeuctivity.PdfjsSharp.Rasterize.js");

            using var reader = new StreamReader(stream !);
            var script = reader.ReadToEnd();

            var scriptWithAbsolutePathsToNodeModules = script.Replace("MagicPrefix", pathToNodeModules);
            var pdfRasterizerJsCodeToExecute         = scriptWithAbsolutePathsToNodeModules;

            var pathsToPngOfEachPage = new List <string>();

            var pageQuantity = await StaticNodeJSService.InvokeFromStringAsync <int>(pdfRasterizerJsCodeToExecute, args : new object[] { pathToPdf, pathToPngOutput }).ConfigureAwait(false);

            for (var pagenumber = 1; pagenumber <= pageQuantity; pagenumber++)
            {
                pathsToPngOfEachPage.Add($"{pathToPngOutput}{pagenumber}.png");
            }

            return(pathsToPngOfEachPage.AsReadOnly());
        }
        public NodeJS_ASTWrapper(
            string source
            )
        {
            var nodeJSPath = Path.Combine(
                Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location
                    ),
                "AstParser",
                "NodeImpl",
                "NodeJS"
                );
            var nodeModulesPath = Path.Combine(
                nodeJSPath,
                "node_modules"
                );
            var indexJSPath = Path.Combine(
                nodeJSPath,
                "index.js"
                );

            // Check for existing node_modules, install if needed
            if (!Directory.Exists(
                    nodeModulesPath
                    ))
            {
                var cmdProcessInfo = new ProcessStartInfo
                {
                    FileName         = "npm",
                    WorkingDirectory = nodeJSPath,
                    UseShellExecute  = true,
                    Arguments        = "install",
                };
                var cmdProcess = Process.Start(
                    cmdProcessInfo
                    );
                cmdProcess.WaitForExit();
            }

            var result = StaticNodeJSService.InvokeFromFileAsync <string>(
                indexJSPath,
                args: new object[]
            {
                source
            }
                ).GetAwaiter().GetResult();

            // Use for testing the generated AST
            //File.WriteAllText(
            //    Path.Combine(
            //        ".",
            //        "AstParser",
            //        "NodeImpl",
            //        "NodeJS",
            //        "_generated",
            //        "ast.json"
            //    ),
            //    result
            //);
            var ast = JsonSerializer.Deserialize <ASTModel>(
                result,
                new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
            }
                );

            RootNode = new NodeJS_Node(
                ast.Program
                );
        }
Example #26
0
 public Task <T> InvokeFromStringAsync <T>(string moduleString, string cacheIdentifier = null, string exportName = null, object[] args = null, CancellationToken cancellationToken = default)
 {
     return(StaticNodeJSService.InvokeFromStringAsync <T>(moduleString, cacheIdentifier, exportName, args, cancellationToken));
 }
Example #27
0
 public Task InvokeFromStreamAsync(Func <Stream> moduleFactory, string cacheIdentifier, string exportName = null, object[] args = null, CancellationToken cancellationToken = default)
 {
     return(StaticNodeJSService.InvokeFromStreamAsync(moduleFactory, cacheIdentifier, exportName, args, cancellationToken));
 }
Example #28
0
 public Task InvokeFromStreamAsync(Stream moduleStream, string newCacheIdentifier = null, string exportName = null, object[] args = null, CancellationToken cancellationToken = default)
 {
     return(StaticNodeJSService.InvokeFromStreamAsync(moduleStream, newCacheIdentifier, exportName, args, cancellationToken));
 }
Example #29
0
 public Task InvokeFromFileAsync(string modulePath, string exportName = null, object[] args = null, CancellationToken cancellationToken = default)
 {
     return(StaticNodeJSService.InvokeFromFileAsync(modulePath, exportName, args, cancellationToken));
 }
 /// <summary>
 /// Print to pdf.
 /// </summary>
 /// <param name="args"></param>
 /// <returns></returns>
 protected virtual async Task Print(params object[] args)
 {
     await StaticNodeJSService.InvokeFromFileAsync(_module, _method, args);
 }