Example #1
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
        }
        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 #3
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);
        }
        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);
        }
Example #6
0
        private async Task <string[]> RunCoreAsync()
        {
            string code = await runnableCode.Value;

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

            return(output);
        }
        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 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 #9
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 #10
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 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 InvokeFromStringAsync_WithoutTypeParameter_WithModuleFactory_IfModuleIsCachedInvokesFromCacheOtherwiseInvokesFromString()
        {
            // Arrange
            Func <string>         dummyModuleFactory     = () => "dummyModule";
            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.InvokeFromStringAsync(dummyModuleFactory, dummyCacheIdentifier, dummyExportName, dummyArgs, dummyCancellationToken));
            var dummyServices = new ServiceCollection();

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

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

            // Assert
            _mockRepository.VerifyAll();
        }
Example #14
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());
        }
Example #15
0
 public Task InvokeFromStringAsync(Func <string> moduleFactory, string cacheIdentifier, string exportName = null, object[] args = null, CancellationToken cancellationToken = default)
 {
     return(StaticNodeJSService.InvokeFromStringAsync(moduleFactory, cacheIdentifier, exportName, args, cancellationToken));
 }
Example #16
0
 public Task InvokeFromStringAsync(string moduleString, string newCacheIdentifier = null, string exportName = null, object[] args = null, CancellationToken cancellationToken = default)
 {
     return(StaticNodeJSService.InvokeFromStringAsync(moduleString, newCacheIdentifier, exportName, args, cancellationToken));
 }