public void BuildReturnsCallableDelegate() { var builder = new ApplicationBuilder(null); var app = builder.Build(); var mockHttpContext = new Moq.Mock<HttpContext>(); var mockHttpResponse = new Moq.Mock<HttpResponse>(); mockHttpContext.SetupGet(x => x.Response).Returns(mockHttpResponse.Object); mockHttpResponse.SetupProperty(x => x.StatusCode); app.Invoke(mockHttpContext.Object); Assert.Equal(mockHttpContext.Object.Response.StatusCode, 404); }
//<inheritdoc /> public RequestDelegate CreatePipeline() { _logger.LogTrace("Creating new ApplicationBuilder."); IApplicationBuilder app = new ApplicationBuilder(_serviceProvider); app.Properties["host.AppName"] = _tenant.TenantId; _logger.LogTrace("Registering middlewares."); foreach (var middlewareProvider in _middlewareProviders) { middlewareProvider.Configure(app); } var routeBuilder = new RouteBuilder(app) { DefaultHandler = new MvcRouteHandler() }; _logger.LogDebug("Registering route providers."); foreach (var routeProvider in _routeProviders.OrderBy(t => t.RouterPriority)) { routeProvider.ConfigureRoutes(routeBuilder); } _logger.LogTrace("Building tenant router."); app.UseRouter(routeBuilder.Build()); app.Run(async context => { await context.Response.WriteAsync("You in tenant pipeline! " + _tenant.TenantId); }); _logger.LogTrace("Building pipeline"); var pipeline = app.Build(); return pipeline; }
public void AppBld_BuildApplication() { Assert.IsTrue(sig.Parameters[3].Storage is OutArgumentStorage); ab = new ApplicationBuilder(arch, frame, new CallSite(4, 0), new Identifier("foo", PrimitiveType.Word32, null), sig, false); var instr = ab.CreateInstruction(); Assert.AreEqual("eax = foo(Mem0[esp + 4:word32], Mem0[esp + 8:word16], Mem0[esp + 12:byte], out edx)", instr.ToString()); }
public Task ActivatingAsync() { // Build the middleware pipeline for the current tenant IApplicationBuilder appBuilder = new ApplicationBuilder(_serviceProvider); var orderedMiddlewares = _middlewareProviders .SelectMany(p => p.GetMiddlewares()) .OrderBy(obj => obj.Priority) .ToArray(); foreach (var middleware in orderedMiddlewares) { middleware.Configure(appBuilder); } // Orchard is always the last middleware appBuilder.UseMiddleware<OrchardMiddleware>(); var pipeline = appBuilder.Build(); _routePublisher.Publish( _routeProviders.SelectMany(provider => provider.GetRoutes()), pipeline ); return Task.CompletedTask; }
public void UseMiddlewareWithIvokeWithOutAndRefThrows() { var mockServiceProvider = new DummyServiceProvider(); var builder = new ApplicationBuilder(mockServiceProvider); builder.UseMiddleware(typeof(MiddlewareInjectWithOutAndRefParams)); var exception = Assert.Throws<NotSupportedException>(() => builder.Build()); }
public void UseMiddleware_NonTaskReturnType_ThrowsException() { var mockServiceProvider = new DummyServiceProvider(); var builder = new ApplicationBuilder(mockServiceProvider); builder.UseMiddleware(typeof(MiddlewareNonTaskReturnStub)); var exception = Assert.Throws<InvalidOperationException>(() => builder.Build()); Assert.Equal(Resources.FormatException_UseMiddlewareNonTaskReturnType("Invoke", nameof(Task)), exception.Message); }
public void NullArguments_ArgumentNullException() { var builder = new ApplicationBuilder(serviceProvider: null); var noMiddleware = new ApplicationBuilder(serviceProvider: null).Build(); var noOptions = new MapOptions(); Assert.Throws<ArgumentNullException>(() => builder.Map("/foo", configuration: null)); Assert.Throws<ArgumentNullException>(() => new MapMiddleware(noMiddleware, null)); }
public void UseMiddlewareWithInvokeArg() { var mockServiceProvider = new DummyServiceProvider(); var builder = new ApplicationBuilder(mockServiceProvider); builder.UseMiddleware(typeof(MiddlewareInjectInvoke)); var app = builder.Build(); app(new DefaultHttpContext()); }
public void UseMiddleware_MutlipleInvokeMethods_ThrowsException() { var mockServiceProvider = new DummyServiceProvider(); var builder = new ApplicationBuilder(mockServiceProvider); builder.UseMiddleware(typeof(MiddlewareMultipleInvokesStub)); var exception = Assert.Throws<InvalidOperationException>(() => builder.Build()); Assert.Equal(Resources.FormatException_UseMiddleMutlipleInvokes("Invoke"), exception.Message); }
public DefaultPocoTest() { var services = new ServiceCollection(); var store = this.NewDocumentStore(); SetupIdentityServices(services, store); var provider = services.BuildServiceProvider(); _builder = new ApplicationBuilder(provider); }
public async Task UseMiddleware_ThrowsIfArgCantBeResolvedFromContainer() { var mockServiceProvider = new DummyServiceProvider(); var builder = new ApplicationBuilder(mockServiceProvider); builder.UseMiddleware(typeof(MiddlewareInjectInvokeNoService)); var app = builder.Build(); var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => app(new DefaultHttpContext())); Assert.Equal(Resources.FormatException_InvokeMiddlewareNoService(typeof(object), typeof(MiddlewareInjectInvokeNoService)), exception.Message); }
public void UseMiddleware_WithNoParameters_ThrowsException() { var mockServiceProvider = new DummyServiceProvider(); var builder = new ApplicationBuilder(mockServiceProvider); builder.UseMiddleware(typeof(MiddlewareNoParametersStub)); var exception = Assert.Throws<InvalidOperationException>(() => builder.Build()); Assert.Equal(Resources.FormatException_UseMiddlewareNoParameters("Invoke", nameof(HttpContext)), exception.Message); }
// Build the middleware pipeline for the current tenant public RequestDelegate BuildTenantPipeline(ShellSettings shellSettings, IServiceProvider serviceProvider) { var startups = serviceProvider.GetServices<IStartup>(); var inlineConstraintResolver = serviceProvider.GetService<IInlineConstraintResolver>(); IApplicationBuilder appBuilder = new ApplicationBuilder(serviceProvider); string routePrefix = ""; if (!string.IsNullOrWhiteSpace(shellSettings.RequestUrlPrefix)) { routePrefix = shellSettings.RequestUrlPrefix + "/"; } var routeBuilder = new RouteBuilder(appBuilder) { DefaultHandler = serviceProvider.GetRequiredService<MvcRouteHandler>() }; var prefixedRouteBuilder = new PrefixedRouteBuilder(routePrefix, routeBuilder, inlineConstraintResolver); // Register one top level TenantRoute per tenant. Each instance contains all the routes // for this tenant. // In the case of several tenants, they will all be checked by ShellSettings. To optimize // the TenantRoute resolution we can create a single Router type that would index the // TenantRoute object by their ShellSetting. This way there would just be one lookup. // And the ShellSettings test in TenantRoute would also be useless. foreach (var startup in startups) { startup.Configure(appBuilder, prefixedRouteBuilder, serviceProvider); } // The default route is added to each tenant as a template route, with a prefix prefixedRouteBuilder.Routes.Add(new Route( prefixedRouteBuilder.DefaultHandler, "Default", "{area:exists}/{controller}/{action}/{id?}", null, null, null, inlineConstraintResolver) ); // Add home page route routeBuilder.Routes.Add(new HomePageRoute(shellSettings.RequestUrlPrefix, routeBuilder, inlineConstraintResolver)); var router = prefixedRouteBuilder.Build(); appBuilder.UseRouter(router); var pipeline = appBuilder.Build(); return pipeline; }
public void BuildReturnsCallableDelegate() { var builder = new ApplicationBuilder(null); var app = builder.Build(); var httpContext = new DefaultHttpContext(); app.Invoke(httpContext); Assert.Equal(httpContext.Response.StatusCode, 404); }
public void NullArguments_ArgumentNullException() { var builder = new ApplicationBuilder(serviceProvider: null); var noMiddleware = new ApplicationBuilder(serviceProvider: null).Build(); var noOptions = new MapOptions(); // TODO: [NotNull] Assert.Throws<ArgumentNullException>(() => builder.Map(null, ActionNotImplemented)); // TODO: [NotNull] Assert.Throws<ArgumentNullException>(() => builder.Map("/foo", (Action<IBuilder>)null)); // TODO: [NotNull] Assert.Throws<ArgumentNullException>(() => new MapMiddleware(null, noOptions)); // TODO: [NotNull] Assert.Throws<ArgumentNullException>(() => new MapMiddleware(noMiddleware, null)); }
public void PredicateTrueAction_BranchTaken() { HttpContext context = CreateRequest(); var builder = new ApplicationBuilder(serviceProvider: null); builder.MapWhen(TruePredicate, UseSuccess); var app = builder.Build(); app.Invoke(context).Wait(); Assert.Equal(200, context.Response.StatusCode); }
public void NullArguments_ArgumentNullException() { var builder = new ApplicationBuilder(serviceProvider: null); var noMiddleware = new ApplicationBuilder(serviceProvider: null).Build(); var noOptions = new MapWhenOptions(); Assert.Throws<ArgumentNullException>(() => builder.MapWhen(null, UseNotImplemented)); Assert.Throws<ArgumentNullException>(() => builder.MapWhen(NotImplementedPredicate, configuration: null)); Assert.Throws<ArgumentNullException>(() => new MapWhenMiddleware(null, noOptions)); Assert.Throws<ArgumentNullException>(() => new MapWhenMiddleware(noMiddleware, null)); Assert.Throws<ArgumentNullException>(() => new MapWhenMiddleware(null, noOptions)); Assert.Throws<ArgumentNullException>(() => new MapWhenMiddleware(noMiddleware, null)); }
public void PathMatchFunc_BranchTaken(string matchPath, string basePath, string requestPath) { HttpContext context = CreateRequest(basePath, requestPath); var builder = new ApplicationBuilder(serviceProvider: null); builder.Map(matchPath, UseSuccess); var app = builder.Build(); app.Invoke(context).Wait(); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(basePath, context.Request.PathBase.Value); Assert.Equal(requestPath, context.Request.Path.Value); }
public void PathMatchAction_BranchTaken(string matchPath, string basePath, string requestPath) { HttpContext context = CreateRequest(basePath, requestPath); var builder = new ApplicationBuilder(serviceProvider: null); builder.Map(matchPath, subBuilder => subBuilder.Run(Success)); var app = builder.Build(); app.Invoke(context).Wait(); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(basePath + matchPath, context.Items["test.PathBase"]); Assert.Equal(requestPath.Substring(matchPath.Length), context.Items["test.Path"]); }
public void AppBld_BindByteToRegister() { var caller = new Procedure("caller", new Frame(PrimitiveType.Pointer32)); var callee = new Procedure("callee", new Frame(PrimitiveType.Pointer32)); var ab = new ApplicationBuilder( arch, callee.Frame, new CallSite(4, 0), new Identifier("foo", PrimitiveType.Pointer32, null), new ProcedureSignature(new Identifier("bRet", PrimitiveType.Byte, Registers.eax)), true); var instr = ab.CreateInstruction(); Assert.AreEqual("eax = DPB(eax, foo(), 0, 8)", instr.ToString()); }
public void StartupClassMayHaveHostingServicesInjected() { var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton<IFakeStartupCallback>(this); var services = serviceCollection.BuildServiceProvider(); var type = StartupLoader.FindStartupType("Microsoft.AspNetCore.Hosting.Tests", "WithServices"); var startup = StartupLoader.LoadMethods(services, type, "WithServices"); var app = new ApplicationBuilder(services); app.ApplicationServices = startup.ConfigureServicesDelegate(serviceCollection); startup.ConfigureDelegate(app); Assert.Equal(2, _configurationMethodCalledList.Count); }
/// <summary> /// Rewrites CALL instructions to function applications. /// </summary> /// <remarks> /// Converts an opcode: /// <code> /// call procExpr /// </code> /// to one of: /// <code> /// ax = procExpr(bindings); /// procEexpr(bindings); /// </code> /// </remarks> /// <param name="proc">Procedure in which the CALL instruction exists</param> /// <param name="stm">The particular statement of the call instruction</param> /// <param name="call">The actuall CALL instruction.</param> /// <returns>True if the conversion was possible, false if the procedure didn't have /// a signature yet.</returns> public bool RewriteCall(Procedure proc, Statement stm, CallInstruction call) { var callee = call.Callee as ProcedureConstant; if (callee == null) return false; //$REVIEW: what happens with indirect calls? var procCallee = callee.Procedure; var sigCallee = GetProcedureSignature(procCallee); var fn = new ProcedureConstant(Program.Platform.PointerType, procCallee); if (sigCallee == null || !sigCallee.ParametersValid) return false; var ab = new ApplicationBuilder(Program.Architecture, proc.Frame, call.CallSite, fn, sigCallee, true); stm.Instruction = ab.CreateInstruction(); return true; }
public void NullArguments_ArgumentNullException() { var builder = new ApplicationBuilder(serviceProvider: null); var noMiddleware = new ApplicationBuilder(serviceProvider: null).Build(); var noOptions = new MapWhenOptions(); // TODO: [NotNull] Assert.Throws<ArgumentNullException>(() => builder.MapWhen(null, UseNotImplemented)); // TODO: [NotNull] Assert.Throws<ArgumentNullException>(() => builder.MapWhen(NotImplementedPredicate, (Action<IBuilder>)null)); // TODO: [NotNull] Assert.Throws<ArgumentNullException>(() => new MapWhenMiddleware(null, noOptions)); // TODO: [NotNull] Assert.Throws<ArgumentNullException>(() => new MapWhenMiddleware(noMiddleware, null)); // TODO: [NotNull] Assert.Throws<ArgumentNullException>(() => builder.MapWhenAsync(null, UseNotImplemented)); // TODO: [NotNull] Assert.Throws<ArgumentNullException>(() => builder.MapWhenAsync(NotImplementedPredicateAsync, (Action<IBuilder>)null)); // TODO: [NotNull] Assert.Throws<ArgumentNullException>(() => new MapWhenMiddleware(null, noOptions)); // TODO: [NotNull] Assert.Throws<ArgumentNullException>(() => new MapWhenMiddleware(noMiddleware, null)); }
public void ExtpBind() { var sig = new ProcedureSignature( new Identifier(Registers.ax.Name, PrimitiveType.Word16, Registers.ax), new Identifier [] { new Identifier(Registers.bx.Name, PrimitiveType.Word16, Registers.bx), new Identifier(Registers.cl.Name, PrimitiveType.Byte, Registers.cl) } ); var ep = new ExternalProcedure("foo", sig); Assert.AreEqual("Register word16 foo(Register word16 bx, Register byte cl)", ep.ToString()); var fn = new ProcedureConstant(PrimitiveType.Pointer32, ep); var arch = new FakeArchitecture(); var frame = arch.CreateFrame(); var ab = new ApplicationBuilder(new FakeArchitecture(), frame, new CallSite(0, 0), fn, ep.Signature, false); var instr = ab.CreateInstruction(); Assert.AreEqual("ax = foo(bx, cl)", instr.ToString()); }
public void StartupClassAddsConfigureServicesToApplicationServices(string environment) { var services = new ServiceCollection().BuildServiceProvider(); var type = StartupLoader.FindStartupType("Microsoft.AspNetCore.Hosting.Tests", environment); var startup = StartupLoader.LoadMethods(services, type, environment); var app = new ApplicationBuilder(services); app.ApplicationServices = startup.ConfigureServicesDelegate(new ServiceCollection()); startup.ConfigureDelegate(app); var options = app.ApplicationServices.GetRequiredService<IOptions<FakeOptions>>().Value; Assert.NotNull(options); Assert.True(options.Configured); Assert.Equal(environment, options.Environment); }
private void AssemblyNullInOptionsNeemtCallingAssembly() { var callingAssembly = typeof(UseCodetableDiscoveryTests).GetTypeInfo().Assembly; // Voor de toolbox is de calling assembly de executing assembly van deze test var codetableProvider = new Mock<ICodetableProvider>(); codetableProvider.Setup(ctp => ctp.Load(callingAssembly)).Verifiable(); var codetableDiscoveryOptions = new CodetableDiscoveryOptions() { ControllerAssembly = callingAssembly }; var serviceProvider = MockServiceProvider(codetableProvider: codetableProvider.Object, option: codetableDiscoveryOptions); var appBuilder = new ApplicationBuilder(serviceProvider); appBuilder.UseCodetableDiscovery(); codetableProvider.Verify(); }
private void CodetablesWordenGeladen() { var assembly = typeof(UseCodetableDiscoveryTests).GetTypeInfo().Assembly; var codetableProvider = new Mock<ICodetableProvider>(); codetableProvider.Setup(ctp => ctp.Load(assembly)).Verifiable(); var options = new CodetableDiscoveryOptions(); options.ControllerAssembly = assembly; var serviceProvider = MockServiceProvider(codetableProvider: codetableProvider.Object, option: options); var appBuilder = new ApplicationBuilder(serviceProvider); appBuilder.UseCodetableDiscovery(); codetableProvider.Verify(); }
public async Task VerifyAccountControllerSignIn(bool isPersistent) { var context = new Mock<HttpContext>(); var auth = new Mock<AuthenticationManager>(); context.Setup(c => c.Authentication).Returns(auth.Object).Verifiable(); auth.Setup(a => a.SignInAsync(new IdentityCookieOptions().ApplicationCookieAuthenticationScheme, It.IsAny<ClaimsPrincipal>(), It.IsAny<AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable(); // REVIEW: is persistant mocking broken //It.Is<AuthenticationProperties>(v => v.IsPersistent == isPersistent))).Returns(Task.FromResult(0)).Verifiable(); var contextAccessor = new Mock<IHttpContextAccessor>(); contextAccessor.Setup(a => a.HttpContext).Returns(context.Object); var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(contextAccessor.Object); services.AddIdentity<TestUser, TestRole>(); services.AddSingleton<IUserStore<TestUser>, InMemoryStore<TestUser, TestRole>>(); services.AddSingleton<IRoleStore<TestRole>, InMemoryStore<TestUser, TestRole>>(); var app = new ApplicationBuilder(services.BuildServiceProvider()); app.UseCookieAuthentication(); // Act var user = new TestUser { UserName = "******" }; const string password = "******"; var userManager = app.ApplicationServices.GetRequiredService<UserManager<TestUser>>(); var signInManager = app.ApplicationServices.GetRequiredService<SignInManager<TestUser>>(); IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password)); var result = await signInManager.PasswordSignInAsync(user, password, isPersistent, false); // Assert Assert.True(result.Succeeded); context.VerifyAll(); auth.VerifyAll(); contextAccessor.VerifyAll(); }
private void AssemblyNullInOptionsNeemtCallingAssembly() { var callingAssembly = typeof(UseCodetableDiscoveryTests).GetTypeInfo().Assembly; // Voor de toolbox is de calling assembly de executing assembly van deze test var codetableProvider = new Mock <ICodetableProvider>(); codetableProvider.Setup(ctp => ctp.Load(callingAssembly)).Verifiable(); var codetableDiscoveryOptions = new CodetableDiscoveryOptions() { ControllerAssembly = callingAssembly }; var serviceProvider = MockServiceProvider(codetableProvider: codetableProvider.Object, option: codetableDiscoveryOptions); var appBuilder = new ApplicationBuilder(serviceProvider); appBuilder.UseCodetableDiscovery(); codetableProvider.Verify(); }
private void CodetablesLoadedWithCustomRoute() { var assembly = typeof(UseCodetableDiscoveryTests).GetTypeInfo().Assembly; var codetableProvider = new Mock <ICodetableProvider>(); codetableProvider.Setup(ctp => ctp.Load(assembly)).Verifiable(); var options = new CodetableDiscoveryOptions(); options.ControllerAssembly = assembly; options.Route = "custom/Route"; var serviceProvider = MockServiceProvider(codetableProvider: codetableProvider.Object, option: options); var appBuilder = new ApplicationBuilder(serviceProvider); appBuilder.UseCodetableDiscovery(); codetableProvider.Verify(); }
public void Sqlite_Test() { var services = new ServiceCollection(); services.AddSqliteDatabaseContext(builder => builder.UseSqlite(Global.Configuration.GetConnectionString("SQLite"))); var applicationBuilder = new ApplicationBuilder(services.BuildServiceProvider()); applicationBuilder.UseSqliteDatabaseContext(); // ReSharper disable ConvertToUsingDeclaration using (var scope = applicationBuilder.ApplicationServices.CreateScope()) { var sqliteDatabaseContext = scope.ServiceProvider.GetRequiredService <SqliteDatabaseContext>(); Assert.IsFalse(sqliteDatabaseContext.Documents.Any()); sqliteDatabaseContext.Database.EnsureDeleted(); } // ReSharper restore ConvertToUsingDeclaration }
public static void RegisterFeatures(ApplicationBuilder builder) { builder.UsePageBuilder(new PageBuilderOptions() { DefaultSectionIdentifier = "LearningKit.Sections.DefaultSection", RegisterDefaultSection = false }); builder.UseDataAnnotationsLocalization(); builder.UseCampaignLogger(); builder.UseActivityTracking(); builder.UseEmailTracking(); builder.UseABTesting(); builder.UseWebAnalytics(); builder.UsePageRouting(new PageRoutingOptions { EnableAlternativeUrls = true }); PageBuilderFilters.PageTemplates.Add(new LandingPageTemplateFilter()); }
public void placeholders_should_be_replaced_with_empty() { var startupOptions = new StartupConfiguration { BeginConfiguration = builder => builder.AddInMemoryCollection(new[] { new KeyValuePair <string, string>("Configuration:Property", "Value"), new KeyValuePair <string, string>("Configuration:PropertyWithPlaceholder", "${configurationValue:Placeholders:Value}"), }), CommandLineArgs = new CommandLineArgs(new[] { "--Placeholders:OtherValue", "ValueFromPlaceholder" }), //Not evaluated value should be null or empty string //ReplaceNotEvaluatedValuesWith = "" }; var serviceProvider = new ApplicationBuilder().Build(startupOptions).ServiceProvider; var configuration = serviceProvider.GetService <IConfiguration>(); configuration.Should().NotBeNull(); configuration["Configuration:Property"].Should().Be("Value"); configuration["Configuration:PropertyWithPlaceholder"].Should().Be(""); }
public void UseOpenIddict_AnExceptionIsThrownWhenAuthorizationEndpointIsDisabled(string flow) { // Arrange var services = new ServiceCollection(); services.AddOpenIddict() .AddSigningCertificate( assembly: typeof(OpenIddictProviderTests).GetTypeInfo().Assembly, resource: "OpenIddict.Tests.Certificate.pfx", password: "******") .Configure(options => options.GrantTypes.Add(flow)) .Configure(options => options.AuthorizationEndpointPath = PathString.Empty); var builder = new ApplicationBuilder(services.BuildServiceProvider()); // Act and assert var exception = Assert.Throws <InvalidOperationException>(() => builder.UseOpenIddict()); Assert.Equal("The authorization endpoint must be enabled to use " + "the authorization code and implicit flows.", exception.Message); }
public void AddCloudFoundryActuators_ConfiguresCorsCustom() { // arrange Action <CorsPolicyBuilder> customCors = (myPolicy) => myPolicy.WithOrigins("http://google.com"); var hostBuilder = new WebHostBuilder().Configure(config => { }); // act var host = hostBuilder.ConfigureServices((context, services) => services.AddCloudFoundryActuators(context.Configuration, customCors)).Build(); var options = new ApplicationBuilder(host.Services) .ApplicationServices.GetService(typeof(IOptions <CorsOptions>)) as IOptions <CorsOptions>; // assert Assert.NotNull(options); var policy = options.Value.GetPolicy("SteeltoeManagement"); Assert.True(policy.IsOriginAllowed("http://google.com")); Assert.False(policy.IsOriginAllowed("http://bing.com")); Assert.False(policy.IsOriginAllowed("*")); Assert.Contains(policy.Methods, m => m.Equals("GET")); Assert.Contains(policy.Methods, m => m.Equals("POST")); }
public void UseAzureSignalRWithConnectionStringNotSpecified() { var services = new ServiceCollection(); var config = new ConfigurationBuilder().Build(); var serviceProvider = services.AddLogging() .AddSignalR() .AddAzureSignalR() .AddMessagePackProtocol() .Services .AddSingleton <IHostApplicationLifetime>(new EmptyApplicationLifetime()) .AddSingleton <IConfiguration>(config) .BuildServiceProvider(); var app = new ApplicationBuilder(serviceProvider); var exception = Assert.Throws <ArgumentException>(() => app.UseAzureSignalR(routes => { routes.MapHub <TestHub>("/chat"); })); Assert.StartsWith("No connection string was specified.", exception.Message); }
public void ReadTypedConfigurationAsWrappers() { var startupOptions = new StartupConfiguration { ConfigurationPath = "TestsConfiguration/Bootstrap", Profile = null }; var serviceProvider = new ApplicationBuilder().BuildAndStart(startupOptions); var sampleOptions = serviceProvider.GetService <IOptions <SampleOptions> >(); sampleOptions.Value.ShouldBeWithDefaultValues(); var sampleOptionsSnapshot = serviceProvider.GetService <IOptionsSnapshot <SampleOptions> >(); sampleOptionsSnapshot.Value.ShouldBeWithDefaultValues(); var sampleOptionsMonitor = serviceProvider.GetService <IOptionsMonitor <SampleOptions> >(); sampleOptionsMonitor.CurrentValue.ShouldBeWithDefaultValues(); }
public MaxKeyLengthSchemaTest(ScratchDatabaseFixture fixture) { var services = new ServiceCollection(); services .AddSingleton <IConfiguration>(new ConfigurationBuilder().Build()) .AddDbContext <VerstappenDbContext>(o => o.UseSqlite(fixture.Connection) .ConfigureWarnings(b => b.Log(CoreEventId.ManyServiceProvidersCreatedWarning))) .AddIdentity <IdentityUser, IdentityRole>(o => o.Stores.MaxLengthForKeys = 128) .AddEntityFrameworkStores <VerstappenDbContext>(); services.AddLogging(); _builder = new ApplicationBuilder(services.BuildServiceProvider()); using (var scope = _builder.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope()) { scope.ServiceProvider.GetRequiredService <VerstappenDbContext>().Database.EnsureCreated(); } }
public void Basic_Resolution() { IServiceCollection services = new ServiceCollection(); services.AddMvcCore(); services.AddXPikeDependencyInjection((options) => { }) .LoadPackage(new TestPackage()); IServiceProvider provider = services.BuildServiceProvider(); IApplicationBuilder app = new ApplicationBuilder(provider); IDependencyProvider dependencyProvider = app.UseXPikeDependencyInjection((options) => { }); dependencyProvider.Verify(); var config = dependencyProvider.ResolveDependency <IFoo>(); Assert.IsInstanceOfType(config, typeof(Foo)); }
public ModelApplicationBase GetMasterModel(bool tryToUseCurrentTypesInfo, Action <ITypesInfo> action = null) { if (!File.Exists(_moduleName)) { throw new UserFriendlyException(_moduleName + " not found in path"); } ModelApplicationBase masterModel = null; Retry.Do(() => { _typesInfo = TypesInfoBuilder.Create() .FromModule(_moduleName) .Build(tryToUseCurrentTypesInfo); _xafApplication = ApplicationBuilder.Create(). UsingTypesInfo(s => _typesInfo). FromModule(_moduleName). Build(); masterModel = GetMasterModel(_xafApplication, action); }, TimeSpan.FromTicks(1), 2); return(masterModel); }
public static void Main(string[] args) { var services = new ServiceCollection(); var app = new ApplicationBuilder(services.BuildServiceProvider()); var factory = new LoggerFactory(); factory.MinimumLevel = Microsoft.Extensions.Logging.LogLevel.Debug; factory.AddLogstashHttp(app, options => { options.Index = "index"; options.Url = "url"; }); var logger = factory.CreateLogger("MyLog"); for (int i = 0; i < 500; i++) { Task.Run(() => logger.Log(Microsoft.Extensions.Logging.LogLevel.Debug, 100, BuildLogMessage(), null, null)); } System.Console.ReadLine(); }
protected override void Context() { base.Context(); var observerBuildingBlock1 = new EventGroupBuildingBlock().WithName("Tada"); IEventGroupBuilder observerBuilderA = new ApplicationBuilder().WithName("EGA"); var observerBuilderB = new ApplicationBuilder().WithName("EGB"); observerBuildingBlock1.Add(observerBuilderA); observerBuildingBlock1.Add(observerBuilderB); var observerBuildingBlock2 = new EventGroupBuildingBlock().WithName("Tada"); observerBuilderA = new EventGroupBuilder().WithName("EGA"); observerBuilderB = new ApplicationBuilder().WithName("EGB"); observerBuildingBlock2.Add(observerBuilderA); observerBuildingBlock2.Add(observerBuilderB); _object1 = observerBuildingBlock1; _object2 = observerBuildingBlock2; }
protected override void Context() { base.Context(); var eg1 = new ApplicationBuilder().WithName("Events"); eg1.MoleculeName = "Drug"; var am1 = new ApplicationMoleculeBuilder().WithName("Start").WithParentContainer(eg1); am1.RelativeContainerPath = new ObjectPath("..", "C1"); var eg2 = new ApplicationBuilder().WithName("Events"); eg2.MoleculeName = "Drug"; var am2 = new ApplicationMoleculeBuilder().WithName("Start").WithParentContainer(eg2); am2.RelativeContainerPath = new ObjectPath("..", "C2"); _object1 = eg1; _object2 = eg2; }
public static void AddKnownTypes(string modulePath) { InterfaceBuilder.SkipAssemblyCleanup = true; var instance = XafTypesInfo.Instance; var modelLoader = new ModelLoader(modulePath, instance); modulePath = Path.GetFullPath(modulePath); var typesInfo = TypesInfoBuilder.Create().FromModule(modulePath).Build(false); var xafApplication = ApplicationBuilder.Create() .UsingTypesInfo(s => typesInfo) .FromModule(modulePath) .FromAssembliesPath(Path.GetDirectoryName(modulePath)) .WithOutObjectSpaceProvider() .Build(); modelLoader.GetMasterModel(xafApplication); AddKnownTypesForAll(typesInfo); instance.AssignAsInstance(); xafApplication.Dispose(); InterfaceBuilder.SkipAssemblyCleanup = true; }
public DefaultPocoTest(ScratchDatabaseFixture fixture) { var services = new ServiceCollection(); services .AddDbContext <IdentityDbContext>(o => o.UseSqlServer(fixture.ConnectionString)) .AddIdentity <IdentityUser, IdentityRole>() .AddEntityFrameworkStores <IdentityDbContext>(); services.AddLogging(); var provider = services.BuildServiceProvider(); _builder = new ApplicationBuilder(provider); using (var scoped = provider.GetRequiredService <IServiceScopeFactory>().CreateScope()) using (var db = scoped.ServiceProvider.GetRequiredService <IdentityDbContext>()) { db.Database.EnsureCreated(); } }
public void ConfigureMustNotConfigureHstsWhenEnvironmentIsNotProduction() { IConfiguration configuration = new ConfigurationFactory().Create(); IServiceCollection services = new ServiceCollection(); IWebHostEnvironment environment = new FakeHostingEnvironment(); StubStartup startup = new StubStartup(configuration, environment); startup.ConfigureServices(services); DiagnosticListener listener = new DiagnosticListener("Test"); services.AddSingleton(listener); services.AddSingleton <DiagnosticSource>(listener); services.AddSingleton(environment); IApplicationBuilder app = new ApplicationBuilder(services.BuildServiceProvider()); startup.Configure(app, environment); List <Func <RequestDelegate, RequestDelegate> > delegates = ReflectionHelper.GetFieldOrDefault(app, "_components") as List <Func <RequestDelegate, RequestDelegate> >; Assert.NotNull(delegates); Assert.Null(delegates.FirstOrDefault(x => (ReflectionHelper.GetFieldOrDefault(x.Target, "middleware") as Type)?.Name == "HstsMiddleware")); }
public static Tye.Hosting.Model.Application ToHostingApplication(this ApplicationBuilder application) { var services = new Dictionary <string, Tye.Hosting.Model.Service>(); foreach (var service in application.Services) { RunInfo?runInfo; int replicas; var env = new List <ConfigurationSource>(); if (service is ExternalServiceBuilder) { runInfo = null; replicas = 1; } else if (service is ContainerServiceBuilder container) { var dockerRunInfo = new DockerRunInfo(container.Image, container.Args); foreach (var mapping in container.Volumes) { dockerRunInfo.VolumeMappings[mapping.Source !] = mapping.Target !;
public void WhenITryToSaveADuplicateFeature_ThenSaveFeatureExceptionIsThrown() { var saveFeature = new CreateFeatureFake(); var saveApplication = new CreateApplicationFake(); var getApplicationByName = new GetApplicationByName(); var application = new ApplicationBuilder() .WithName("Test12345") .Build(); saveApplication.Execute(application); application = getApplicationByName.Execute(application.Name); var feature = new FeatureBuilder() .WithName("MyTestFeature") .WithApplication(application).Build(); saveFeature.Execute(feature); Assert.Throws <CreateFeatureException>(() => saveFeature.Execute(feature)); }
public async Task <HttpContext> ExecuteAsync(HttpRequestFeature requestFeature, Action <FeatureCollection> featureCollectionAction = null) { var serviceCollection = new ServiceCollection(); serviceCollection.AddLogging(); serviceCollection.AddRouting(); _serviceCollectionAction?.Invoke(serviceCollection); var featureCollection = new FeatureCollection(); featureCollection.Set <IHttpRequestFeature>(requestFeature); featureCollection.Set <IHttpResponseFeature>(new HttpResponseFeature { Body = new MemoryStream(), Headers = new HeaderDictionary() }); featureCollectionAction?.Invoke(featureCollection); var appBuilder = new ApplicationBuilder(serviceCollection.BuildServiceProvider(), featureCollection); _applicationBuilderAction?.Invoke(appBuilder); var entryDelegate = appBuilder.Build(); using (var serviceScope = appBuilder.ApplicationServices.CreateScope()) { var context = new DefaultHttpContext(featureCollection) { RequestServices = serviceScope.ServiceProvider }; await entryDelegate(context); context.Response.Body.Position = 0; return(context); } }
public async Task VerifyAccountControllerSignIn(bool isPersistent) { var context = new DefaultHttpContext(); var auth = MockAuth(context); auth.Setup(a => a.SignInAsync(context, IdentityConstants.ApplicationScheme, It.IsAny<ClaimsPrincipal>(), It.IsAny<AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable(); // REVIEW: is persistant mocking broken //It.Is<AuthenticationProperties>(v => v.IsPersistent == isPersistent))).Returns(Task.FromResult(0)).Verifiable(); var contextAccessor = new Mock<IHttpContextAccessor>(); contextAccessor.Setup(a => a.HttpContext).Returns(context); var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()) .AddLogging() .AddSingleton(contextAccessor.Object); services.AddIdentity<PocoUser, PocoRole>(); services.AddSingleton<IUserStore<PocoUser>, InMemoryStore<PocoUser, PocoRole>>(); services.AddSingleton<IRoleStore<PocoRole>, InMemoryStore<PocoUser, PocoRole>>(); var app = new ApplicationBuilder(services.BuildServiceProvider()); // Act var user = new PocoUser { UserName = "******" }; const string password = "******"; var userManager = app.ApplicationServices.GetRequiredService<UserManager<PocoUser>>(); var signInManager = app.ApplicationServices.GetRequiredService<SignInManager<PocoUser>>(); IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password)); var result = await signInManager.PasswordSignInAsync(user, password, isPersistent, false); // Assert Assert.True(result.Succeeded); auth.VerifyAll(); contextAccessor.VerifyAll(); }
public async Task VerifyAccountControllerSignIn(bool isPersistent) { var app = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider); app.UseCookieAuthentication(); var context = new Mock <HttpContext>(); var response = new Mock <HttpResponse>(); context.Setup(c => c.Response).Returns(response.Object).Verifiable(); response.Setup(r => r.SignIn(It.Is <AuthenticationProperties>(v => v.IsPersistent == isPersistent), It.IsAny <ClaimsIdentity>())).Verifiable(); var contextAccessor = new Mock <IHttpContextAccessor>(); contextAccessor.Setup(a => a.Value).Returns(context.Object); app.UseServices(services => { services.AddInstance(contextAccessor.Object); services.AddIdentity <ApplicationUser, IdentityRole>(); services.AddSingleton <IUserStore <ApplicationUser>, InMemoryUserStore <ApplicationUser> >(); services.AddSingleton <IRoleStore <IdentityRole>, InMemoryRoleStore <IdentityRole> >(); }); // Act var user = new ApplicationUser { UserName = "******" }; const string password = "******"; var userManager = app.ApplicationServices.GetRequiredService <UserManager <ApplicationUser> >(); var signInManager = app.ApplicationServices.GetRequiredService <SignInManager <ApplicationUser> >(); IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password)); var result = await signInManager.PasswordSignInAsync(user, password, isPersistent, false); // Assert Assert.True(result.Succeeded); context.VerifyAll(); response.VerifyAll(); contextAccessor.VerifyAll(); }
public bool StartPing() { if (_listConfigProtocols.ListConfProtocols == null) { throw new NullReferenceException(string.Format("Параметр {0} не задан!", nameof(_listConfigProtocols.ListConfProtocols))); } foreach (var confProtocol in _listConfigProtocols.ListConfProtocols) { if (confProtocol.NameProt == EnumProtocols.Icmp) { _serviceCollection.AddSingleton <IBasePingProtocol>(x => ActivatorUtilities.CreateInstance <ICMP>(x, confProtocol)); } if (confProtocol.NameProt == EnumProtocols.Http) { _serviceCollection.AddSingleton <IBasePingProtocol>(x => ActivatorUtilities.CreateInstance <HTTP>(x, confProtocol)); } if (confProtocol.NameProt == EnumProtocols.Tcp) { _serviceCollection.AddSingleton <IBasePingProtocol>(x => ActivatorUtilities.CreateInstance <TCP>(x, confProtocol)); } var serviceProvider = _serviceCollection.BuildServiceProvider(); var appBuild = new ApplicationBuilder(serviceProvider); var pingProtocol = appBuild.ApplicationServices.GetService <IBasePingProtocol>(); if (pingProtocol != null) { pingProtocol.PingCompleted += PrintAnswerLog; pingProtocol.StartAsyncPing(); } } return(true); }
public async Task ItForwardsToNextMiddlewareForUnrecognizedChallenge() { var servicesCollection = new ServiceCollection() .AddLogging() .AddScoped <IMiddlewareFactory, MiddlewareFactory>() .AddLettuceEncrypt() .Services; var mockChallenge = new Mock <IHttpChallengeResponseStore>(); mockChallenge .Setup(s => s.TryGetResponse("unknown", out It.Ref <string> .IsAny)) .Returns(false) .Verifiable(); servicesCollection.Replace(ServiceDescriptor.Singleton(mockChallenge.Object)); var services = servicesCollection.BuildServiceProvider(validateScopes: true); var appBuilder = new ApplicationBuilder(services); appBuilder.UseHttpChallengeResponseMiddleware(); var app = appBuilder.Build(); using var scope = services.CreateScope(); var context = new DefaultHttpContext { RequestServices = scope.ServiceProvider, Request = { Path = "/.well-known/acme-challenge/unknown", }, }; await app.Invoke(context); Assert.Equal(StatusCodes.Status404NotFound, context.Response.StatusCode); mockChallenge.VerifyAll(); }
public void ChainedRoutes_Success() { var builder = new ApplicationBuilder(serviceProvider: null); builder.Map("/route1", map => { map.Map("/subroute1", UseSuccess); map.Run(NotImplemented); }); builder.Map("/route2/subroute2", UseSuccess); var app = builder.Build(); HttpContext context = CreateRequest(string.Empty, "/route1"); Assert.Throws <AggregateException>(() => app.Invoke(context).Wait()); context = CreateRequest(string.Empty, "/route1/subroute1"); app.Invoke(context).Wait(); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(string.Empty, context.Request.PathBase.Value); Assert.Equal("/route1/subroute1", context.Request.Path.Value); context = CreateRequest(string.Empty, "/route2"); app.Invoke(context).Wait(); Assert.Equal(404, context.Response.StatusCode); Assert.Equal(string.Empty, context.Request.PathBase.Value); Assert.Equal("/route2", context.Request.Path.Value); context = CreateRequest(string.Empty, "/route2/subroute2"); app.Invoke(context).Wait(); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(string.Empty, context.Request.PathBase.Value); Assert.Equal("/route2/subroute2", context.Request.Path.Value); context = CreateRequest(string.Empty, "/route2/subroute2/subsub2"); app.Invoke(context).Wait(); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(string.Empty, context.Request.PathBase.Value); Assert.Equal("/route2/subroute2/subsub2", context.Request.Path.Value); }
public void SpringBootAdminClient_EndToEnd() { var appsettings = new Dictionary <string, string>() { ["management:endpoints:path"] = "/management", ["management:endpoints:health:path"] = "myhealth", ["URLS"] = "http://localhost:8080;https://localhost:8082", ["spring:boot:admin:client:url"] = "http://springbootadmin:9090", ["spring:application:name"] = "MySteeltoeApplication", }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.AddInMemoryCollection(appsettings); var config = configurationBuilder.Build(); var services = new ServiceCollection(); var appLifeTime = new MyAppLifeTime(); services.TryAddSingleton <IHostApplicationLifetime>(appLifeTime); services.TryAddSingleton <IConfiguration>(config); var provider = services.BuildServiceProvider(); var appBuilder = new ApplicationBuilder(provider); var builder = new WebHostBuilder(); builder.UseStartup <TestStartup>(); using (var server = new TestServer(builder)) { var client = server.CreateClient(); appBuilder.RegisterWithSpringBootAdmin(config, client); appLifeTime.AppStartTokenSource.Cancel(); // Trigger application lifetime start Assert.NotNull(SpringBootAdminApplicationBuilderExtensions.RegistrationResult); Assert.Equal("1234567", SpringBootAdminApplicationBuilderExtensions.RegistrationResult.Id); appLifeTime.AppStopTokenSource.Cancel(); // Trigger application lifetime stop } }
public UserOnlyTest(ScratchDatabaseFixture fixture) { var services = new ServiceCollection(); services .AddSingleton <IConfiguration>(new ConfigurationBuilder().Build()) .AddDbContext <TestUserDbContext>(o => o.UseSqlServer(fixture.ConnectionString)) .AddIdentityCore <IdentityUser>(o => { }) .AddEntityFrameworkStores <TestUserDbContext>(); services.AddLogging(); var provider = services.BuildServiceProvider(); _builder = new ApplicationBuilder(provider); using (var scoped = provider.GetRequiredService <IServiceScopeFactory>().CreateScope()) using (var db = scoped.ServiceProvider.GetRequiredService <TestUserDbContext>()) { db.Database.EnsureCreated(); } }
public async Task UseMiddlewareWithIMiddlewareThrowsIfMiddlewareFactoryCreateReturnsNull() { var mockServiceProvider = new DummyServiceProvider(); var builder = new ApplicationBuilder(mockServiceProvider); builder.UseMiddleware(typeof(Middleware)); var app = builder.Build(); var exception = await Assert.ThrowsAsync <InvalidOperationException>(async() => { var context = new DefaultHttpContext(); var sp = new DummyServiceProvider(); sp.AddService(typeof(IMiddlewareFactory), new BadMiddlewareFactory()); context.RequestServices = sp; await app(context); }); Assert.Equal( Resources.FormatException_UseMiddlewareUnableToCreateMiddleware( typeof(BadMiddlewareFactory), typeof(Middleware)), exception.Message); }
public MaxKeyLengthSchemaTest(ScratchDatabaseFixture fixture) { var services = new ServiceCollection(); services .AddSingleton <IConfiguration>(new ConfigurationBuilder().Build()) .AddDbContext <IdentityDbContext>(o => o.UseSqlServer(fixture.ConnectionString)) .AddIdentity <IdentityUser, IdentityRole>(o => o.Stores.MaxLengthForKeys = 128) .AddEntityFrameworkStores <IdentityDbContext>(); services.AddLogging(); var provider = services.BuildServiceProvider(); _builder = new ApplicationBuilder(provider); using (var scoped = provider.GetRequiredService <IServiceScopeFactory>().CreateScope()) using (var db = scoped.ServiceProvider.GetRequiredService <IdentityDbContext>()) { db.Database.EnsureCreated(); } }
public void CapturesServiceExceptionDetails() { var methodInfo = GetType().GetMethod(nameof(InjectedMethod), BindingFlags.NonPublic | BindingFlags.Static); Assert.NotNull(methodInfo); var services = new ServiceCollection() .AddSingleton<CrasherService>() .BuildServiceProvider(); var applicationBuilder = new ApplicationBuilder(services); var builder = new ConfigureBuilder(methodInfo); Action<IApplicationBuilder> action = builder.Build(instance:null); var ex = Assert.Throws<Exception>(() => action.Invoke(applicationBuilder)); Assert.NotNull(ex); Assert.Equal($"Could not resolve a service of type '{typeof(CrasherService).FullName}' for the parameter" + $" 'service' of method '{methodInfo.Name}' on type '{methodInfo.DeclaringType.FullName}'.", ex.Message); // the inner exception contains the root cause Assert.NotNull(ex.InnerException); Assert.Equal("Service instantiation failed", ex.InnerException.Message); Assert.Contains(nameof(CrasherService), ex.InnerException.StackTrace); }
public void FrBindMixedParameters() { Frame f = new Frame(PrimitiveType.Word16); Identifier ax = f.EnsureRegister(Registers.ax); Identifier cx = f.EnsureRegister(Registers.cx); int stack = PrimitiveType.Word16.Size; Identifier arg1 = f.EnsureStackLocal(-stack, PrimitiveType.Word16); ProcedureSignature sig = new ProcedureSignature( ax, cx, new Identifier("arg0", PrimitiveType.Word16, new StackArgumentStorage(0, PrimitiveType.Word16))); var cs = new CallSite(stack, 0); ProcedureConstant fn = new ProcedureConstant(PrimitiveType.Pointer32, new PseudoProcedure("bar", sig)); ApplicationBuilder ab = new ApplicationBuilder(arch, f, cs, fn, sig, true); Instruction instr = ab.CreateInstruction(); using (FileUnitTester fut = new FileUnitTester("Core/FrBindMixedParameters.txt")) { f.Write(fut.TextWriter); fut.TextWriter.WriteLine(instr.ToString()); fut.AssertFilesEqual(); } }