static ReactRenderer()
        {
            // Consider populating this lazily
            var script = EmbeddedResourceReader.Read(typeof(ReactRenderer), "/Content/Node/react-rendering.js");

            nodeScript = new StringAsTempFile(script); // Will be cleaned up on process exit
        }
Beispiel #2
0
        /// <summary>
        /// Starts the webpack dev server. If the start fails for known reason, modifies the aspnet-webpack module to be compliant with webpack-dev-middleware 5.
        /// For compatibility purposes as the change is rather samll it's easier to modify the existing module than to create new NPM package and enforce anyone to udpate.
        /// </summary>
        private static WebpackDevServerInfo StartWebpackDevServer(IDictionary <string, string> environmentVariables, string projectPath, WebpackDevServerArgs devServerArgs, bool fixAttempted)
        {
            // Unlike other consumers of NodeServices, WebpackDevMiddleware dosen't share Node instances, nor does it
            // use your DI configuration. It's important for WebpackDevMiddleware to have its own private Node instance
            // because it must *not* restart when files change (if it did, you'd lose all the benefits of Webpack
            // middleware). And since this is a dev-time-only feature, it doesn't matter if the default transport isn't
            // as fast as some theoretical future alternative.
            // This should do it by using Jering.Javascript.NodeJS interop
            var nodeJSService = NodeInteropFactory.BuildNewInstance(environmentVariables, projectPath);

            try
            {
                return(nodeJSService.InvokeFromStringAsync <WebpackDevServerInfo>(
                           EmbeddedResourceReader.Read(typeof(WebpackDevMiddleware), "/Content/Node/webpack-dev-middleware.js"), //Embedded JS file
                           args: new object[] { JsonSerializer.Serialize(devServerArgs, jsonSerializerOptions) } //Options patched so that they work with aspnet-webpack package
                           ).Result);
            }
            catch (Exception ex)
            {
                if (fixAttempted)
                {
                    throw;
                }

                if (ex != null && ex.Message.Contains("Dev Middleware has been initialized using an options object that does not match the API schema."))
                {
                    //Attempt to modify module file so that it doesn't contain arguments not recognized by the webpack-dev-middleware 5
                    try
                    {
                        const string SEARCH_PATTERN = "at validate (";
                        var          startIndex     = ex.Message.IndexOf(SEARCH_PATTERN);
                        if (startIndex > -1)
                        {
                            startIndex += SEARCH_PATTERN.Length;
                            var endIndex    = ex.Message.IndexOf("webpack-dev-middleware", startIndex);
                            var modulesPath = ex.Message.Substring(startIndex, endIndex - startIndex);

                            if (Directory.Exists(modulesPath))
                            {
                                var modulePath = Path.Combine(modulesPath, @"aspnet-webpack\WebpackDevMiddleware.js");
                                if (File.Exists(modulePath))
                                {
                                    var fileContent = File.ReadAllText(modulePath);
                                    fileContent = fileContent.Replace("noInfo: true,", "");
                                    fileContent = fileContent.Replace("watchOptions: webpackConfig.watchOptions", "");
                                    File.WriteAllText(modulePath, fileContent);
                                    nodeJSService.Dispose();

                                    return(StartWebpackDevServer(environmentVariables, projectPath, devServerArgs, true));
                                }
                            }
                        }
                    }
                    catch (Exception)
                    { }
                }

                throw;
            }
        }
Beispiel #3
0
 static Prerenderer()
 {
     nodeScript = new Lazy <StringAsTempFile>(() => {
         var script = EmbeddedResourceReader.Read(typeof(Prerenderer), "/Content/Node/prerenderer.js");
         return(new StringAsTempFile(script)); // Will be cleaned up on process exit
     });
 }
 protected override void OnWebKitInitialized()
 {
     CefRuntime.RegisterExtension(bindingExtensionName,
                                  EmbeddedResourceReader.Read(typeof(MessageRenderProcessHandler), "/Renderer/Javascript/extension.js"),
                                  handler);
     base.OnWebKitInitialized();
 }
        private static string GetAngularCliMiddlewareScriptPath(IApplicationBuilder appBuilder)
        {
            var script     = EmbeddedResourceReader.Read(typeof(AngularCliMiddleware), _middlewareResourceName);
            var nodeScript = new StringAsTempFile(script, GetStoppingToken(appBuilder));

            return(nodeScript.FileName);
        }
        public static async Task <NodeHost> Create(string handlerFile, string projectPath, CancellationToken applicationStopping, ILogger logger, IDictionary <string, string> environmentVars)
        {
            var hostScript = EmbeddedResourceReader.Read(typeof(NodeHost), "/Content/node-host.js");
            var result     = new NodeHost(hostScript, projectPath, "\"" + handlerFile + "\"", applicationStopping, logger, environmentVars);
            await result.Start();

            return(result);
        }
Beispiel #7
0
        private static string GetNodeScript(CancellationToken applicationStoppingToken)
        {
            lock (CreateNodeScriptLock)
            {
                if (NodeScript == null)
                {
                    NodeScript = EmbeddedResourceReader.Read(typeof(Prerenderer), "/Content/Node/prerenderer.js");
                }
            }

            return(NodeScript);
        }
        static INodeServices fallbackNodeServices; // Used only if no INodeServices was registered with DI

        public static void UseWebpackDevMiddleware(this IApplicationBuilder appBuilder, WebpackDevMiddlewareOptions options = null)
        {
            // Validate options
            if (options != null)
            {
                if (options.ReactHotModuleReplacement && !options.HotModuleReplacement)
                {
                    throw new ArgumentException("To enable ReactHotModuleReplacement, you must also enable HotModuleReplacement.");
                }
            }

            // Get the NodeServices instance from DI
            var nodeServices = (INodeServices)appBuilder.ApplicationServices.GetService(typeof(INodeServices)) ?? fallbackNodeServices;

            // Consider removing the following. Having it means you can get away with not putting app.AddNodeServices()
            // in your startup file, but then again it might be confusing that you don't need to.
            var appEnv = (IApplicationEnvironment)appBuilder.ApplicationServices.GetService(typeof(IApplicationEnvironment));

            if (nodeServices == null)
            {
                nodeServices = fallbackNodeServices = Configuration.CreateNodeServices(NodeHostingModel.Http, appEnv.ApplicationBasePath);
            }

            // Get a filename matching the middleware Node script
            var script     = EmbeddedResourceReader.Read(typeof(WebpackDevMiddleware), "/Content/Node/webpack-dev-middleware.js");
            var nodeScript = new StringAsTempFile(script); // Will be cleaned up on process exit

            // Tell Node to start the server hosting webpack-dev-middleware
            var devServerOptions = new {
                webpackConfigPath = Path.Combine(appEnv.ApplicationBasePath, "webpack.config.js"),
                suppliedOptions   = options ?? new WebpackDevMiddlewareOptions()
            };
            var devServerInfo = nodeServices.InvokeExport <WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer", JsonConvert.SerializeObject(devServerOptions)).Result;

            // Proxy the corresponding requests through ASP.NET and into the Node listener
            appBuilder.Map(devServerInfo.PublicPath, builder => {
                builder.RunProxy(new ProxyOptions {
                    Host = WebpackDevMiddlewareHostname,
                    Port = devServerInfo.Port.ToString()
                });
            });

            // While it would be nice to proxy the /__webpack_hmr requests too, these return an EventStream,
            // and the Microsoft.Aspnet.Proxy code doesn't handle that entirely - it throws an exception after
            // a while. So, just serve a 302 for those.
            appBuilder.Map(WebpackHotMiddlewareEndpoint, builder => {
                builder.Use(next => async ctx => {
                    ctx.Response.Redirect($"http://localhost:{ devServerInfo.Port.ToString() }{ WebpackHotMiddlewareEndpoint }");
                    await Task.Yield();
                });
            });
        }
Beispiel #9
0
        public static void UseWebpackDevMiddleware(this IApplicationBuilder appBuilder, WebpackDevMiddlewareOptions options = null)
        {
            // Validate options
            if (options != null)
            {
                if (options.ReactHotModuleReplacement && !options.HotModuleReplacement)
                {
                    throw new ArgumentException("To enable ReactHotModuleReplacement, you must also enable HotModuleReplacement.");
                }
            }

            // Unlike other consumers of NodeServices, WebpackDevMiddleware dosen't share Node instances, nor does it
            // use your DI configuration. It's important for WebpackDevMiddleware to have its own private Node instance
            // because it must *not* restart when files change (if it did, you'd lose all the benefits of Webpack
            // middleware). And since this is a dev-time-only feature, it doesn't matter if the default transport isn't
            // as fast as some theoretical future alternative.
            var appEnv       = (IApplicationEnvironment)appBuilder.ApplicationServices.GetService(typeof(IApplicationEnvironment));
            var nodeServices = Configuration.CreateNodeServices(new NodeServicesOptions {
                HostingModel        = NodeHostingModel.Http,
                ProjectPath         = appEnv.ApplicationBasePath,
                WatchFileExtensions = new string[] {} // Don't watch anything
            });

            // Get a filename matching the middleware Node script
            var script     = EmbeddedResourceReader.Read(typeof(WebpackDevMiddleware), "/Content/Node/webpack-dev-middleware.js");
            var nodeScript = new StringAsTempFile(script); // Will be cleaned up on process exit

            // Tell Node to start the server hosting webpack-dev-middleware
            var devServerOptions = new {
                webpackConfigPath = Path.Combine(appEnv.ApplicationBasePath, "webpack.config.js"),
                suppliedOptions   = options ?? new WebpackDevMiddlewareOptions()
            };
            var devServerInfo = nodeServices.InvokeExport <WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer", JsonConvert.SerializeObject(devServerOptions)).Result;

            // Proxy the corresponding requests through ASP.NET and into the Node listener
            appBuilder.Map(devServerInfo.PublicPath, builder => {
                builder.RunProxy(new ProxyOptions {
                    Host = WebpackDevMiddlewareHostname,
                    Port = devServerInfo.Port.ToString()
                });
            });

            // While it would be nice to proxy the /__webpack_hmr requests too, these return an EventStream,
            // and the Microsoft.Aspnet.Proxy code doesn't handle that entirely - it throws an exception after
            // a while. So, just serve a 302 for those.
            appBuilder.Map(WebpackHotMiddlewareEndpoint, builder => {
                builder.Use(next => async ctx => {
                    ctx.Response.Redirect($"http://localhost:{ devServerInfo.Port.ToString() }{ WebpackHotMiddlewareEndpoint }");
                    await Task.Yield();
                });
            });
        }
Beispiel #10
0
        private static string GetNodeScriptFilename(CancellationToken applicationStoppingToken)
        {
            lock (CreateNodeScriptLock)
            {
                if (NodeScript == null)
                {
                    var script = EmbeddedResourceReader.Read(typeof(Renderer), "/Content/Node/prerenderer.js");
                    NodeScript = new StringAsTempFile(script, applicationStoppingToken); // Will be cleaned up on process exit
                }
            }

            return(NodeScript.FileName);
        }
Beispiel #11
0
        private static string GetNodeScriptFilename(CancellationToken applicationStoppingToken)
        {
            lock (CreateNodeScriptLock)
            {
                if (nodeScript == null)
                {
                    var script = EmbeddedResourceReader.Read(typeof(EmPageRenderer), RendererScriptPath);
                    nodeScript = new StringAsTempFile(script, applicationStoppingToken);
                }
            }

            return(nodeScript.FileName);
        }
            public void ShouldReadFoldingWithSinglePanelCorrectly()
            {
                var singlePanel   = new EmbeddedResource(typeof(TestsForXmlModelReader).Assembly, typeof(TestsForXmlModelReader).Namespace + ".SinglePanel.xml");
                var xml           = _embeddedResourceReader.Read(singlePanel);
                var actualFolding = _sut.Read(xml);

                var expectedFolding = new XmlModels.Folding {
                    Items = new[] {
                        new XmlModels.Item {
                            PanelId          = new Guid("872201A9-2D6E-FD0C-E7E9-A24588D95B5E"),
                            PanelName        = "Dummy Panel",
                            MinRot           = 1,
                            MaxRot           = 2,
                            InitialRot       = 3,
                            StartRot         = 4,
                            EndRot           = 5,
                            HingeOffset      = 6,
                            PanelWidth       = 7,
                            PanelHeight      = 8,
                            AttachedToSide   = 9,
                            CreaseBottom     = 10,
                            CreaseTop        = 11,
                            CreaseLeft       = 12,
                            CreaseRight      = 13,
                            IgnoreCollisions = true,
                            MouseEnabled     = true,
                            AttachedPanels   = new XmlModels.Item[0]
                        }
                    }
                };

                actualFolding.Should().NotBeNull();
                actualFolding.Items.Should().NotBeNull().And.NotBeEmpty();
                actualFolding.Items[0].ShouldBeEquivalentTo(expectedFolding.Items[0]);
                actualFolding.Items.Should().HaveCount(1);
            }
Beispiel #13
0
 public HttpNodeInstance(NodeServicesOptions options, int port = 0)
     : base(
         EmbeddedResourceReader.Read(typeof(OutOfProcessNodeInstance), "/Content/Node/entrypoint-http.js"),
         options.ProjectPath,
         options.WatchFileExtensions,
         MakeCommandLineOptions(port),
         options.ApplicationStoppingToken,
         options.NodeInstanceOutputLogger,
         options.EnvironmentVariables,
         options.InvocationTimeoutMilliseconds,
         options.LaunchWithDebugging,
         options.DebuggingPort)
 {
     _client         = new HttpClient();
     _client.Timeout = TimeSpan.FromMilliseconds(options.InvocationTimeoutMilliseconds + 1000);
 }
Beispiel #14
0
 public SocketNodeInstance(NodeServicesOptions options, string socketAddress)
     : base(
         EmbeddedResourceReader.Read(
             typeof(SocketNodeInstance),
             "/Content/Node/entrypoint-socket.js"),
         options.ProjectPath,
         options.WatchFileExtensions,
         MakeNewCommandLineOptions(socketAddress),
         options.ApplicationStoppingToken,
         options.NodeInstanceOutputLogger,
         options.EnvironmentVariables,
         options.InvocationTimeoutMilliseconds,
         options.LaunchWithDebugging,
         options.DebuggingPort)
 {
     _socketAddress = socketAddress;
 }
Beispiel #15
0
            public TempScriptDirectory()
            {
                var directory = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));

                while (Directory.Exists(directory))
                {
                    directory = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
                }

                Directory.CreateDirectory(directory);

                File.WriteAllText(Path.Combine(directory, "marked.js"),
                                  EmbeddedResourceReader.Read(typeof(TempScriptDirectory), "/Content/Node/marked.js"));
                File.WriteAllText(Path.Combine(directory, "markedHelper.js"),
                                  EmbeddedResourceReader.Read(typeof(TempScriptDirectory), "/Content/Node/markedHelper.js"));
                File.WriteAllText(Path.Combine(directory, "compile-markdown.js"),
                                  EmbeddedResourceReader.Read(typeof(TempScriptDirectory), "/Content/Node/compile-markdown.js"));

                TempDirectory = directory;

                CompileScriptPath = Path.Combine(TempDirectory, "compile-markdown.js");
            }
Beispiel #16
0
 protected override void OnWebKitInitialized()
 {
     base.OnWebKitInitialized();
     CefRuntime.RegisterExtension("test",
                                  EmbeddedResourceReader.Read(typeof(Handler), "/Javascript/test_extension.js"), new TestHandler());
 }
Beispiel #17
0
        public static NodeHost Create(string handlerFile, string projectPath, ILogger logger)
        {
            var hostScript = EmbeddedResourceReader.Read(typeof(NodeHost), "/Content/node-host.js");

            return(new NodeHost(hostScript, projectPath, logger, "\"" + handlerFile + "\""));
        }
        /// <summary>
        /// Enables Parcel dev middleware support. This hosts an instance of Parcel in memory
        /// in your application so that you can always serve up-to-date Parcel-built resources without having
        /// to run it manually. Since Parcel is retained in memory, incremental
        /// compilation is vastly faster that re-running it from scratch.
        ///
        /// Incoming requests that match Parcel-built files will be handled by returning the Parcel
        /// output directly, regardless of files on disk. If compilation is in progress when the request arrives,
        /// the response will pause until updated compiler output is ready.
        /// </summary>
        /// <param name="appBuilder">The <see cref="IApplicationBuilder"/>.</param>
        /// <param name="options">Options for configuring Parcel.</param>
        public static void UseParcelDevMiddleware(
            this IApplicationBuilder appBuilder,
            ParcelBundlerOptions options = null)
        {
            // Prepare options
            if (options == null)
            {
                options = new ParcelBundlerOptions();
            }

            // Unlike other consumers of NodeServices, ParcelDevMiddleware dosen't share Node instances, nor does it
            // use your DI configuration. It's important for ParcelDevMiddleware to have its own private Node instance
            // because it must *not* restart when files change (if it did, you'd lose all the benefits of Parcel
            // middleware). And since this is a dev-time-only feature, it doesn't matter if the default transport isn't
            // as fast as some theoretical future alternative.
            var nodeServicesOptions = new NodeServicesOptions(appBuilder.ApplicationServices);

            nodeServicesOptions.WatchFileExtensions = new string[] { }; // Don't watch anything
            if (!string.IsNullOrEmpty(options.ProjectPath))
            {
                nodeServicesOptions.ProjectPath = options.ProjectPath;
            }

            if (options.EnvironmentVariables != null)
            {
                foreach (var kvp in options.EnvironmentVariables)
                {
                    nodeServicesOptions.EnvironmentVariables[kvp.Key] = kvp.Value;
                }
            }

            var nodeServices = NodeServicesFactory.CreateNodeServices(nodeServicesOptions);

            // Get a filename matching the middleware Node script
            //Actual resource name: RudiBech.AspNetCore.SpaServices.Parcel.parcel-dev-middleware.js
            var script = EmbeddedResourceReader.Read(typeof(ParcelDevMiddelware), "/parcel-dev-middleware.js");

            // Will be cleaned up on process exit
            var nodeScript = new StringAsTempFile(script, nodeServicesOptions.ApplicationStoppingToken);

            // Tell Node to start the server hosting webpack-dev-middleware
            var parcelOptions = new
            {
                watch          = options.Watch,
                hmrPort        = options.Port,
                outDir         = options.OutDir,
                outFile        = options.OutFile,
                publicUrl      = options.PublicUrl,
                cache          = options.Cache,
                cacheDir       = options.CacheDir,
                minify         = options.Minify,
                target         = options.Target,
                logLevel       = (int)options.LogLevel,
                sourceMaps     = options.SourceMaps,
                detailedReport = options.DetailedReport,
                entryPoint     = options.EntryPoint
            };

            var devServerInfo =
                nodeServices.InvokeExportAsync <ParcelDevServerInfo>(nodeScript.FileName, "createParcelDevServer",
                                                                     JsonConvert.SerializeObject(parcelOptions, jsonSerializerSettings)).Result;

            // Proxy the corresponding requests through ASP.NET and into the Node listener
            // Anything under /<publicpath> (e.g., /dist) is proxied as a normal HTTP request with a typical timeout (100s is the default from HttpClient)
            foreach (var publicPath in devServerInfo.PublicPaths)
            {
                appBuilder.UseProxyToLocalParcelDevMiddleware(publicPath, devServerInfo.Port, TimeSpan.FromSeconds(100));
            }
        }
Beispiel #19
0
        private void InjectJavaScriptHelpers()
        {
            var script = _embeddedResourceReader.Read("ChromeChauffeur.Core.Scripts.ChromeChauffeur.js", GetType().Assembly);

            Eval(script);
        }
        /// <summary>
        /// Enables Webpack dev middleware support. This hosts an instance of the Webpack compiler in memory
        /// in your application so that you can always serve up-to-date Webpack-built resources without having
        /// to run the compiler manually. Since the Webpack compiler instance is retained in memory, incremental
        /// compilation is vastly faster that re-running the compiler from scratch.
        ///
        /// Incoming requests that match Webpack-built files will be handled by returning the Webpack compiler
        /// output directly, regardless of files on disk. If compilation is in progress when the request arrives,
        /// the response will pause until updated compiler output is ready.
        /// </summary>
        /// <param name="appBuilder">The <see cref="IApplicationBuilder"/>.</param>
        /// <param name="options">Options for configuring the Webpack compiler instance.</param>
        public static void UseWebpackDevMiddleware(
            this IApplicationBuilder appBuilder,
            WebpackDevMiddlewareOptions options = null)
        {
            // Prepare options
            if (options == null)
            {
                options = new WebpackDevMiddlewareOptions();
            }

            // Validate options
            if (options.ReactHotModuleReplacement && !options.HotModuleReplacement)
            {
                throw new ArgumentException(
                          "To enable ReactHotModuleReplacement, you must also enable HotModuleReplacement.");
            }

            // Unlike other consumers of NodeServices, WebpackDevMiddleware dosen't share Node instances, nor does it
            // use your DI configuration. It's important for WebpackDevMiddleware to have its own private Node instance
            // because it must *not* restart when files change (if it did, you'd lose all the benefits of Webpack
            // middleware). And since this is a dev-time-only feature, it doesn't matter if the default transport isn't
            // as fast as some theoretical future alternative.
            var nodeServicesOptions = new NodeServicesOptions(appBuilder.ApplicationServices);

            nodeServicesOptions.WatchFileExtensions = new string[] { }; // Don't watch anything
            if (!string.IsNullOrEmpty(options.ProjectPath))
            {
                nodeServicesOptions.ProjectPath = options.ProjectPath;
            }

            if (options.EnvironmentVariables != null)
            {
                foreach (var kvp in options.EnvironmentVariables)
                {
                    nodeServicesOptions.EnvironmentVariables[kvp.Key] = kvp.Value;
                }
            }

            var nodeServices = NodeServicesFactory.CreateNodeServices(nodeServicesOptions);

            // Get a filename matching the middleware Node script
            var script = EmbeddedResourceReader.Read(typeof(WebpackDevMiddleware),
                                                     "/Content/Node/webpack-dev-middleware.js");
            var nodeScript = new StringAsTempFile(script, nodeServicesOptions.ApplicationStoppingToken); // Will be cleaned up on process exit

            // Ideally, this would be relative to the application's PathBase (so it could work in virtual directories)
            // but it's not clear that such information exists during application startup, as opposed to within the context
            // of a request.
            var hmrEndpoint = !string.IsNullOrEmpty(options.HotModuleReplacementEndpoint)
                ? options.HotModuleReplacementEndpoint
                : "/__webpack_hmr"; // Matches webpack's built-in default

            // Tell Node to start the server hosting webpack-dev-middleware
            var devServerOptions = new
            {
                webpackConfigPath = Path.Combine(nodeServicesOptions.ProjectPath, options.ConfigFile ?? DefaultConfigFile),
                suppliedOptions   = options,
                understandsMultiplePublicPaths  = true,
                hotModuleReplacementEndpointUrl = hmrEndpoint
            };
            var devServerInfo =
                nodeServices.InvokeExportAsync <WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer",
                                                                      JsonConvert.SerializeObject(devServerOptions, jsonSerializerSettings)).Result;

            // If we're talking to an older version of aspnet-webpack, it will return only a single PublicPath,
            // not an array of PublicPaths. Handle that scenario.
            if (devServerInfo.PublicPaths == null)
            {
                devServerInfo.PublicPaths = new[] { devServerInfo.PublicPath };
            }

            // Proxy the corresponding requests through ASP.NET and into the Node listener
            // Anything under /<publicpath> (e.g., /dist) is proxied as a normal HTTP request with a typical timeout (100s is the default from HttpClient),
            // plus /__webpack_hmr is proxied with infinite timeout, because it's an EventSource (long-lived request).
            foreach (var publicPath in devServerInfo.PublicPaths)
            {
                appBuilder.UseProxyToLocalWebpackDevMiddleware(publicPath + hmrEndpoint, devServerInfo.Port, Timeout.InfiniteTimeSpan);
                appBuilder.UseProxyToLocalWebpackDevMiddleware(publicPath, devServerInfo.Port, TimeSpan.FromSeconds(100));
            }
        }