Ejemplo n.º 1
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)
 {
     _connectionCreationSemaphore = new SemaphoreSlim(MaxConcurrentRequestCount);
     _socketAddress = socketAddress;
 }
Ejemplo n.º 2
0
            public CanonicalTestSource()
            {
                var vrilFiles = EmbeddedResourceReader.Of <CanonicalTestSource>().GetAllFileStringContent($"Vmr.Cli.Tests.Internal.Resources.{nameof(CanonicalTests)}", "vril");

                VrilFiles = vrilFiles.ToDictionary(m => TrimFileExt(m.FileReference), m => EnsureLastNewLine(m.Content));

                var binFiles = EmbeddedResourceReader.Of <CanonicalTestSource>().GetAllFileBinaryContent($"Vmr.Cli.Tests.Internal.Resources.{nameof(CanonicalTests)}", "bin");

                BinFiles = binFiles.ToDictionary(m => TrimFileExt(m.FileReference), m => m.Content);

                var binVrilFiles = EmbeddedResourceReader.Of <CanonicalTestSource>().GetAllFileStringContent($"Vmr.Cli.Tests.Internal.Resources.{nameof(CanonicalTests)}.dasm", "dasm");

                BinVrilFiles = binVrilFiles.ToDictionary(m => TrimFileExt(m.FileReference), m => EnsureLastNewLine(m.Content));

                var txtFiles = EmbeddedResourceReader.Of <CanonicalTestSource>().GetAllFileStringContent($"Vmr.Cli.Tests.Internal.Resources.{nameof(CanonicalTests)}.results", "txt");

                TxtFiles = txtFiles.ToDictionary(m => TrimFileExt(m.FileReference), m => EnsureLastNewLine(m.Content));
            }
Ejemplo n.º 3
0
 public HttpNodeInstance(NodeServicesOptions options, int port = 0)
     : base(
         EmbeddedResourceReader.Read(
             typeof(HttpNodeInstance),
             "/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);
 }
Ejemplo n.º 4
0
        public async Task FailedRequestTest()
        {
            var expectedResponse =
                EmbeddedResourceReader.ReadResponseAsString("error.sgml");

            var options       = new OfxClientOptions(ApiUrl, "HAN", "5959", "testUserAccount", "testUserPassword");
            var transportMock = Substitute.For <IOfxClientTransport>();
            var utilsMock     = Substitute.For <IUtils>();

            utilsMock.GenerateTransactionId().Returns("0000000000");
            utilsMock.GetCurrentDateTime().Returns("XXXXXXXXXXXXXX");

            transportMock.PostRequest(Arg.Any <Uri>(), Arg.Any <string>()).Returns(Task.FromResult(expectedResponse));

            var client = new OfxClient(options, transportMock, utilsMock);
            var ex     = await Assert.ThrowsAsync <OfxResponseException>(() => client.GetAccounts());

            Assert.Equal("An incorrect username/password combination has been entered. Please try again.", ex.Message);
        }
Ejemplo n.º 5
0
        public static IEnumerable <string> ReadPizzaData(DataSize size)
        {
            var assembly = Assembly.GetExecutingAssembly();

            switch (size)
            {
            case DataSize.Big:
                return(EmbeddedResourceReader.ReadStrings("HashCode2017.Practice.Resources.big.in", assembly));

            case DataSize.Medium:
                return(EmbeddedResourceReader.ReadStrings("HashCode2017.Practice.Resources.medium.in", assembly));

            case DataSize.Small:
                return(EmbeddedResourceReader.ReadStrings("HashCode2017.Practice.Resources.small.in", assembly));

            default:
                throw new ArgumentException();
            }
        }
Ejemplo n.º 6
0
        public static IEnumerable <string> ReadFile(ProblemSettings problemSetting)
        {
            var assembly = Assembly.GetExecutingAssembly();

            switch (problemSetting)
            {
            case ProblemSettings.kittens:
                return(EmbeddedResourceReader.ReadStrings("HashCode2017.Qualification.Resources.kittens.in", assembly));

            case ProblemSettings.me_at_the_zoo:
                return(EmbeddedResourceReader.ReadStrings("HashCode2017.Qualification.Resources.me_at_the_zoo.in", assembly));

            case ProblemSettings.trending_today:
                return(EmbeddedResourceReader.ReadStrings("HashCode2017.Qualification.Resources.trending_today.in", assembly));

            case ProblemSettings.video_worth_spreading:
                return(EmbeddedResourceReader.ReadStrings("HashCode2017.Qualification.Resources.videos_worth_spreading.in", assembly));

            default:
                throw new ArgumentException();
            }
        }
Ejemplo n.º 7
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");
            }
Ejemplo n.º 8
0
        public void TheUserIsLoggedInWithRoleForOrganisation(string role, string organisationId)
        {
            var builder = new BearerTokenBuilder()
                          .WithSigningCertificate(EmbeddedResourceReader.GetCertificate())
                          .IssuedBy(settings.Authority)
                          .ForSubject("7B195137-6A59-4854-B118-62B39A3101EF")
                          .WithClaim("client_id", "PasswordClient")
                          .WithClaim("preferred_username", "*****@*****.**")
                          .WithClaim("unique_name", "*****@*****.**")
                          .WithClaim("given_name", "Bob")
                          .WithClaim("family_name", "Smith")
                          .WithClaim("name", "Bob Smith")
                          .WithClaim("email", "*****@*****.**")
                          .WithClaim("email_verified", "true")
                          .WithClaim("primaryOrganisationId", organisationId)
                          .WithClaim("organisationFunction", role)
                          .WithClaim(ClaimTypes.Name, "Test User")
                          .WithClaim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString());

            if (role.Equals("Read-only Buyer", StringComparison.OrdinalIgnoreCase))
            {
                builder.WithClaim("Ordering", "view");
            }

            if (role.Equals("Buyer", StringComparison.OrdinalIgnoreCase))
            {
                builder = builder.WithClaim("Ordering", "Manage");
            }
            else if (role.Equals("Authority", StringComparison.OrdinalIgnoreCase))
            {
                builder = builder.WithClaim("Organisation", "Manage");
                builder = builder.WithClaim("Account", "Manage");
            }

            var token = builder.BuildToken();

            context[ScenarioContextKeys.AccessToken] = token;
        }
Ejemplo n.º 9
0
        public async Task CreditCardTransactionsListTest()
        {
            var expectedResponse =
                EmbeddedResourceReader.ReadResponseAsString("creditCardTransactions.sgml");

            var options   = new OfxClientOptions(ApiUrl, "HAN", "5959", "testUserAccount", "testUserPassword");
            var utilsMock = Substitute.For <IProtocolUtils>();

            utilsMock.Requests.Returns(new DefaultOfxRequestLocator());
            utilsMock.PostRequest(Arg.Any <Uri>(), Arg.Any <string>()).Returns(Task.FromResult(expectedResponse));

            utilsMock.GenerateTransactionId().Returns("0000000000");
            utilsMock.GetCurrentDateTime().Returns("XXXXXXXXXXXXXX");

            var client    = new OfxClient(options, utilsMock, new OfxSgmlSerializer());
            var statement = await client.GetStatement(new CreditCardStatementArgs()
            {
                AccountNumber = "XXXXXXXXXXXX3158"
            });

            Assert.NotNull(statement);
            Assert.Equal(2, statement.Transactions.Length);
        }
Ejemplo n.º 10
0
        public async Task BankTransactionsListTest()
        {
            var expectedRequest =
                EmbeddedResourceReader.ReadRequestAsString("bankTransactions.sgml");
            var expectedResponse =
                EmbeddedResourceReader.ReadResponseAsString("bankTransactions.sgml");

            var options       = new OfxClientOptions(ApiUrl, "HAN", "5959", "testUserAccount", "testUserPassword");
            var transportMock = Substitute.For <IOfxClientTransport>();
            var utilsMock     = Substitute.For <IUtils>();

            transportMock.PostRequest(Arg.Any <Uri>(), Arg.Any <string>()).Returns(Task.FromResult(expectedResponse));

            utilsMock.GenerateTransactionId().Returns("0000000000");
            utilsMock.GetCurrentDateTime().Returns("XXXXXXXXXXXXXX");

            var client = new OfxClient(options, transportMock, utilsMock);
            var result = await client.GetTransactions(new Account(AccountTypeEnum.Checking, "YYYYYYYY1924", "XXXXXXXXX"));

            var transactions = result;

            Assert.NotEqual(null, transactions);
            Assert.Equal(2, transactions.Items.Length);
        }
Ejemplo n.º 11
0
        public async Task AccountListTest()
        {
            var expectedResponse =
                EmbeddedResourceReader.ReadResponseAsString("accountList.sgml");

            var options   = new OfxClientOptions(ApiUrl, "HAN", "5959", "testUserAccount", "testUserPassword");
            var utilsMock = Substitute.For <IProtocolUtils>();

            utilsMock.Requests.Returns(new DefaultOfxRequestLocator());
            utilsMock.PostRequest(Arg.Any <Uri>(), Arg.Any <string>()).Returns(Task.FromResult(expectedResponse));


            utilsMock.GenerateTransactionId().Returns("0000000000");
            utilsMock.GetCurrentDateTime().Returns("20150127131257");
            utilsMock.GetClientUid(Arg.Is <string>(val => val == "testUserAccount")).Returns("SomeGuidHere");

            var client = new OfxClient(options, utilsMock, new OfxSgmlSerializer());
            var result = await client.GetAccounts();

            var account = result;

            Assert.NotEqual(ImmutableArray <Account> .Empty, account);
            Assert.Equal(2, account.Length);
        }
Ejemplo n.º 12
0
        public static string GetContent()
        {
            var embeddedResourceReader = new EmbeddedResourceReader();

            return(embeddedResourceReader.GetContent(Assembly.GetExecutingAssembly(), $"Mtf.Languages.Languages.Csv.{FileName}"));
        }
        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 hostEnv      = (IHostingEnvironment)appBuilder.ApplicationServices.GetService(typeof(IHostingEnvironment));
            var nodeServices = Configuration.CreateNodeServices(new NodeServicesOptions
            {
                HostingModel        = Configuration.DefaultNodeHostingModel,
                ProjectPath         = hostEnv.ContentRootPath,
                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(hostEnv.ContentRootPath, options.ConfigFile ?? DefaultConfigFile),
                suppliedOptions   = options
            };
            var devServerInfo =
                nodeServices.InvokeExport <WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer",
                                                                 JsonConvert.SerializeObject(devServerOptions)).Result;

            // Proxy the corresponding requests through ASP.NET and into the Node listener
            var proxyOptions = new ConditionalProxyMiddlewareOptions(WebpackDevMiddlewareScheme,
                                                                     WebpackDevMiddlewareHostname, devServerInfo.Port.ToString());

            appBuilder.UseMiddleware <ConditionalProxyMiddleware>(devServerInfo.PublicPath, proxyOptions);

            // While it would be nice to proxy the /__webpack_hmr requests too, these return an EventStream,
            // and the Microsoft.AspNetCore.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(
                        $"{WebpackDevMiddlewareScheme}://{WebpackDevMiddlewareHostname}:{devServerInfo.Port.ToString()}{WebpackHotMiddlewareEndpoint}");
                    await Task.Yield();
                });
            });
        }
Ejemplo n.º 14
0
        public static NodeHost Create(string handlerFile, string projectPath, CancellationToken applicationStopping, ILogger logger, IDictionary <string, string> environmentVars)
        {
            var hostScript = EmbeddedResourceReader.Read(typeof(NodeHost), "/Content/node-host.js");

            return(new NodeHost(hostScript, projectPath, "\"" + handlerFile + "\"", applicationStopping, logger, environmentVars));
        }
        /// <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));
            }
        }
Ejemplo n.º 16
0
 protected override void OnWebKitInitialized()
 {
     base.OnWebKitInitialized();
     CefRuntime.RegisterExtension("test",
                                  EmbeddedResourceReader.Read(typeof(Handler), "/Javascript/test_extension.js"), new TestHandler());
 }
Ejemplo n.º 17
0
        /// <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));
            }
        }
 public Read()
 {
     _embeddedResourceReader = new EmbeddedResourceReader();
 }
Ejemplo n.º 19
0
        protected FlowStepComponent(
            string viewName,
            IPlatformSettings platformSettings,
            string customLoadingViewName          = null,
            [CallerFilePath] string componentPath = null)
            : this($"~{GetCustomViewPath(componentPath, viewName, "cshtml")}")
        {
            PlatformSettings = platformSettings;

            UpdateCachedLoaderView();
            SetComponentId();

            _loadingViewContent = new Lazy <string>(() =>
            {
                string customLoadingViewFullPath = null;
                if (customLoadingViewName != null)
                {
                    customLoadingViewFullPath = GetCustomViewPath(componentPath, customLoadingViewName).TrimStart('~', '/');
                }

                return(customLoadingViewFullPath != null
                                        ? ResolveView(customLoadingViewFullPath)
                                        : string.Empty);
            });

            void SetComponentId()
            {
                var componentPrefix = ViewName.Replace(".cshtml", string.Empty, StringComparison.InvariantCultureIgnoreCase)
                                      .Replace('\\', '_')
                                      .Replace('/', '_')
                                      .Replace('~', '_')
                                      .Replace('.', '_')
                                      .TrimStart('_');

                ComponentId = $"{componentPrefix}_{Guid.NewGuid()}";
            }

            string ResolveView(string customLoadingViewFullPath)
            {
#if DEBUG || FRAMEWORKDEVELOPMENT
                //so it can be changed in the same debugging session
                return(DoResolve());
#else
                return(LoadingViewsCache.GetOrAdd(customLoadingViewFullPath, k => DoResolve()));
#endif
                string DoResolve()
                {
                    var path = Path.Combine(HttpContext.Resolve <IWebHostEnvironment>().ContentRootPath,
                                            customLoadingViewFullPath);

                    if (!File.Exists(path))
                    {
                        Logger.Error(() => $"Could not find loading view at :{path}");
                        return(string.Empty);
                    }
                    return(File.ReadAllText(path).Replace("\"~/", $"\"{HttpContext.GetBaseUrl()}"));
                }
            }

            void UpdateCachedLoaderView()
            {
                if (platformSettings.DeferredComponentLoaderViewEmbeddedResourceName != null &&
                    Template.Key != platformSettings.DeferredComponentLoaderViewEmbeddedResourceName)
                {
                    var textResource = EmbeddedResourceReader.ReadTextResource(
                        platformSettings.DeferredComponentLoaderViewEmbeddedResourceName,
                        GetType().Assembly);
                    Template = new KeyValuePair <string, string>(
                        platformSettings.DeferredComponentLoaderViewEmbeddedResourceName,
                        textResource);
                }
            }
        }
            public void Should_read_entire_resource_content()
            {
                var result = EmbeddedResourceReader.GetResourceString <EmbeddedResourceReaderTests>("IAmAResource.txt");

                result.ShouldBe("I have some content, I promise." + Environment.NewLine + "I am a second line.", StringCompareShould.IgnoreLineEndings);
            }
Ejemplo n.º 21
0
 public TestsForEmbeddedResourceReader()
 {
     _sut = new EmbeddedResourceReader();
 }
Ejemplo n.º 22
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 + "\""));
        }
Ejemplo n.º 23
0
        public void Read()
        {
            var date = EmbeddedResourceReader.ReadDateResource();

            date.ShouldNotBeNull();
        }