public static HttpContextAccessor CreateHttpContextAccessor(RequestTelemetry requestTelemetry = null, ActionContext actionContext = null)
        {
            var services = new ServiceCollection();

            var request = new DefaultHttpContext().Request;
            request.Method = "GET";
            request.Path = new PathString("/Test");
            var contextAccessor = new HttpContextAccessor() { HttpContext = request.HttpContext };

            services.AddInstance<IHttpContextAccessor>(contextAccessor);

            if (actionContext != null)
            {
                var si = new ActionContextAccessor();
                si.ActionContext = actionContext;
                services.AddInstance<IActionContextAccessor>(si);
            }

            if (requestTelemetry != null)
            {
                services.AddInstance<RequestTelemetry>(requestTelemetry);
            }

            IServiceProvider serviceProvider = services.BuildServiceProvider();
            contextAccessor.HttpContext.RequestServices = serviceProvider;

            return contextAccessor;
        }
        public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
        {
            var user = new TestUser("test");
            var userManager = MockHelpers.MockUserManager<TestUser>();
            var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
            var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero };
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Options).Returns(identityOptions);
            var httpContext = new Mock<HttpContext>();
            var contextAccessor = new Mock<IHttpContextAccessor>();
            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object,
                contextAccessor.Object, claimsManager.Object, options.Object, null);
            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(user).Verifiable();
            signInManager.Setup(s => s.SignInAsync(user, isPersistent, null)).Returns(Task.FromResult(0)).Verifiable();
            var services = new ServiceCollection();
            services.AddInstance(options.Object);
            services.AddInstance(signInManager.Object);
            services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>());
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme);
            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(id), 
                new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow, IsPersistent = isPersistent }, 
                IdentityOptions.ApplicationCookieAuthenticationScheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Principal);
            await
                SecurityStampValidator.ValidatePrincipalAsync(context);
            Assert.NotNull(context.Principal);
            signInManager.VerifyAll();
        }
Esempio n. 3
0
        public void ConfigureServices()
        {
            IServiceProvider mainProv = CallContextServiceLocator.Locator.ServiceProvider;
            IApplicationEnvironment appEnv = mainProv.GetService<IApplicationEnvironment>();
            IRuntimeEnvironment runtimeEnv = mainProv.GetService<IRuntimeEnvironment>();

            ILoggerFactory logFactory = new LoggerFactory();
            logFactory.AddConsole(LogLevel.Information);

            ServiceCollection sc = new ServiceCollection();
            sc.AddInstance(logFactory);
            sc.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
            sc.AddEntityFramework()
                .AddSqlite()
                .AddDbContext<StarDbContext>();

            sc.AddSingleton<ILibraryManager, LibraryManager>(factory => mainProv.GetService<ILibraryManager>() as LibraryManager);
            sc.AddSingleton<ICache, Cache>(factory => new Cache(new CacheContextAccessor()));
            sc.AddSingleton<IExtensionAssemblyLoader, ExtensionAssemblyLoader>();
            sc.AddSingleton<IStarLibraryManager, StarLibraryManager>();
            sc.AddSingleton<PluginLoader>();
            sc.AddSingleton(factory => mainProv.GetService<IAssemblyLoadContextAccessor>());
            sc.AddInstance(appEnv);
            sc.AddInstance(runtimeEnv);

            Services = sc;

            ServiceProvider = sc.BuildServiceProvider();
        }
        public void GetKeyEscrowSink_MultipleKeyEscrowRegistration_ReturnsAggregate()
        {
            // Arrange
            List<string> output = new List<string>();

            var mockKeyEscrowSink1 = new Mock<IKeyEscrowSink>();
            mockKeyEscrowSink1.Setup(o => o.Store(It.IsAny<Guid>(), It.IsAny<XElement>()))
                .Callback<Guid, XElement>((keyId, element) =>
                {
                    output.Add(String.Format(CultureInfo.InvariantCulture, "[sink1] {0:D}: {1}", keyId, element.Name.LocalName));
                });

            var mockKeyEscrowSink2 = new Mock<IKeyEscrowSink>();
            mockKeyEscrowSink2.Setup(o => o.Store(It.IsAny<Guid>(), It.IsAny<XElement>()))
                .Callback<Guid, XElement>((keyId, element) =>
                {
                    output.Add(String.Format(CultureInfo.InvariantCulture, "[sink2] {0:D}: {1}", keyId, element.Name.LocalName));
                });

            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<IKeyEscrowSink>(mockKeyEscrowSink1.Object);
            serviceCollection.AddInstance<IKeyEscrowSink>(mockKeyEscrowSink2.Object);
            var services = serviceCollection.BuildServiceProvider();

            // Act
            var sink = services.GetKeyEscrowSink();
            sink.Store(new Guid("39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b"), XElement.Parse("<theElement />"));

            // Assert
            Assert.Equal(new[] { "[sink1] 39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b: theElement", "[sink2] 39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b: theElement" }, output);
        }
 public static ServiceCollection GetServiceCollectionWithContextAccessor()
 {
     var services = new ServiceCollection();
     IHttpContextAccessor contextAccessor = new HttpContextAccessor();
     services.AddInstance<IHttpContextAccessor>(contextAccessor);
     services.AddInstance<INotifier>(new Notifier(new ProxyNotifierMethodAdapter()));
     return services;
 }
Esempio n. 6
0
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            ServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddScoped<IOrchardShell, DefaultOrchardShell>();
            serviceCollection.AddScoped<IRouteBuilder, DefaultShellRouteBuilder>();
            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            foreach (var dependency in blueprint.Dependencies
                .Where(t => typeof (IModule).IsAssignableFrom(t.Type))) {

                Logger.Debug("IModule Type: {0}", dependency.Type);

                // TODO: Rewrite to get rid of reflection.
                var instance = (IModule) Activator.CreateInstance(dependency.Type);
                instance.Configure(serviceCollection);
            }

            var p = _serviceProvider.GetService<IOrchardLibraryManager>();
            serviceCollection.AddInstance<IAssemblyProvider>(new DefaultAssemblyProviderTest(p, _serviceProvider, _serviceProvider.GetService<IAssemblyLoaderContainer>()));

            foreach (var dependency in blueprint.Dependencies
                .Where(t => !typeof(IModule).IsAssignableFrom(t.Type)))
            {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                    .Where(itf => typeof(IDependency).IsAssignableFrom(itf)))
                {
                    Logger.Debug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                    else
                    {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                }
            }

            serviceCollection.AddLogging();

            return new WrappingServiceProvider(_serviceProvider, serviceCollection);
        }
Esempio n. 7
0
 public static IServiceProvider RegisterServices(IEnumerable<IViewLocator> viewLocators, IEnumerable<IStaticFileLocator> staticFileLocators)
 {
     // register types for IServiceProvider here
     var serviceCollection = new ServiceCollection();
     serviceCollection.AddInstance(typeof(IEnumerable<IViewLocator>), viewLocators);
     serviceCollection.AddInstance(typeof(IEnumerable<IStaticFileLocator>), staticFileLocators);
     serviceCollection.AddTransient<IViewLocatorService, ViewLocatorService>();
     serviceCollection.AddTransient<IStaticFileGeneratorService, StaticFileGeneratorService>();
     serviceCollection.AddTransient<IControllerRewriterService, ControllerRewriterService>();
     serviceCollection.AddTransient<IControllerGeneratorService, ControllerGeneratorService>();
     serviceCollection.AddTransient<R4MvcGenerator, R4MvcGenerator>();
     return serviceCollection.BuildServiceProvider();
 }
Esempio n. 8
0
        public IServiceCollection ConfigureServices()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance<IAmazonS3>(new AmazonS3Client());
            serviceCollection.AddInstance<IAmazonCodeDeploy>(new AmazonCodeDeployClient());
            serviceCollection.AddInstance<IAmazonECS>(new AmazonECSClient());

            serviceCollection.AddInstance<IApplicationEnvironment>(this._appEnv);
            serviceCollection.AddInstance<IConfiguration>(this.Configuration);
            serviceCollection.AddSingleton<UtilityService>();

            return serviceCollection;
        }
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint) {
            ServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddScoped<IOrchardShell, DefaultOrchardShell>();
            serviceCollection.AddScoped<IRouteBuilder, DefaultShellRouteBuilder>();
            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            serviceCollection.AddMvc();

            serviceCollection.Configure<RazorViewEngineOptions>(options => {
                var expander = new ModuleViewLocationExpander();
                options.ViewLocationExpanders.Add(expander);
            });

            var p = _serviceProvider.GetService<IOrchardLibraryManager>();
            serviceCollection.AddInstance<IAssemblyProvider>(new DefaultAssemblyProviderTest(p, _serviceProvider, _serviceProvider.GetService<IAssemblyLoaderContainer>()));

            foreach (var dependency in blueprint.Dependencies) {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                    .Where(itf => typeof(IDependency).IsAssignableFrom(itf))) {
                    Logger.Debug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof (ITransientDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                    else {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                }
            }

            //foreach (var item in blueprint.Controllers) {
            //    var serviceKeyName = (item.AreaName + "/" + item.ControllerName).ToLowerInvariant();
            //    var serviceKeyType = item.Type;
            //    serviceCollection.AddScoped(serviceKeyType);

            //}

            return BuildFallbackServiceProvider(
                            serviceCollection,
                            _serviceProvider);
        }
 public static ServiceCollection GetServiceCollectionWithContextAccessor()
 {
     var services = new ServiceCollection();
     IHttpContextAccessor contextAccessor = new HttpContextAccessor();
     services.AddInstance<IHttpContextAccessor>(contextAccessor);
     return services;
 }
        private async Task Can_use_connection_string_name_in_OnConfiguring_test(string connectionName)
        {
            var configuration = new Configuration
                {
                    new MemoryConfigurationSource(
                        new Dictionary<string, string>
                            {
                                { "Data:Northwind:ConnectionString", SqlServerTestDatabase.NorthwindConnectionString }
                            })
                };

            var serviceCollection = new ServiceCollection();
            serviceCollection
                .AddInstance<IConfiguration>(configuration)
                .AddEntityFramework()
                .AddSqlServer();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            using (await SqlServerTestDatabase.Northwind())
            {
                using (var context = new NorthwindContext(serviceProvider, connectionName))
                {
                    Assert.Equal(91, await context.Customers.CountAsync());
                }
            }
        }
Esempio n. 12
0
        public void TestHelloNonGenericServiceDecoratorNoInterface()
        {
            var services = new ServiceCollection();

            services.AddInstance<IHelloService>(new HelloService());

            services.AddSingleton<IHelloService>(sp => new HelloService());
            services.AddScoped<IHelloService>(sp => new HelloService());
            services.AddTransient<IHelloService>(sp => new HelloService());

            services.AddSingleton<IHelloService, HelloService>();
            services.AddScoped<IHelloService, HelloService>();
            services.AddTransient<IHelloService, HelloService>();

            services.AddDecorator(typeof(IHelloService), (sp, s) => new HelloServiceDecoratorNoInterface((IHelloService)s));

            var provider = services.BuildServiceProvider();

            var helloServices = provider.GetRequiredServices<IHelloService>();
            Assert.NotNull(helloServices);
            var collection = helloServices as IHelloService[] ?? helloServices.ToArray();
            Assert.Equal(7, collection.Length);
            Assert.NotEmpty(collection);
            foreach (var helloService in collection)
            {
                Assert.NotNull(helloService);
                Assert.Equal("Decorated without interface: Hello world.", helloService.SayHello("world"));
            }
        }
Esempio n. 13
0
        public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails()
        {
            var user = new IdentityUser("test");
            var httpContext = new Mock<HttpContext>();
            var userManager = MockHelpers.MockUserManager<IdentityUser>();
            var authManager = new Mock<IAuthenticationManager>();
            var claimsManager = new Mock<IClaimsIdentityFactory<IdentityUser>>();
            var signInManager = new Mock<SignInManager<IdentityUser>>(userManager.Object,
                authManager.Object, claimsManager.Object);
            signInManager.Setup(s => s.ValidateSecurityStamp(It.IsAny<ClaimsIdentity>(), user.Id)).ReturnsAsync(null).Verifiable();
            var services = new ServiceCollection();
            services.AddInstance(signInManager.Object);
            httpContext.Setup(c => c.ApplicationServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(ClaimsIdentityOptions.DefaultAuthenticationType);
            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow });
            var context = new CookieValidateIdentityContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Identity);
            await
                SecurityStampValidator.OnValidateIdentity<IdentityUser>(TimeSpan.Zero).Invoke(context);
            Assert.Null(context.Identity);
            signInManager.VerifyAll();
        }
Esempio n. 14
0
        public Task<int> Main(string[] args)
        {
            //Add command line configuration source to read command line parameters.
            var config = new Configuration();
            config.AddCommandLine(args);
            
            var serviceCollection = new ServiceCollection();
            serviceCollection.Add(HostingServices.GetDefaultServices(config));
            serviceCollection.AddInstance<IHostingEnvironment>(new HostingEnvironment() { WebRoot = "wwwroot" });
            var services = serviceCollection.BuildServiceProvider(_hostServiceProvider);

            var context = new HostingContext()
            {
                Services = services,
                Configuration = config,
                ServerName = "Microsoft.AspNet.Server.WebListener",
                ApplicationName = "BugTracker"
            };

            var engine = services.GetService<IHostingEngine>();
            if (engine == null)
            {
                throw new Exception("TODO: IHostingEngine service not available exception");
            }

            using (engine.Start(context))
            {
                Console.WriteLine("Started the server..");
                Console.WriteLine("Press any key to stop the server");
                Console.ReadLine();
            }
            return Task.FromResult(0);
        }
Esempio n. 15
0
 public static RoleManager<IdentityRole> CreateRoleManager(InMemoryContext context)
 {
     var services = new ServiceCollection();
     services.AddIdentity<IdentityUser, IdentityRole>();
     services.AddInstance<IRoleStore<IdentityRole>>(new RoleStore<IdentityRole>(context));
     return services.BuildServiceProvider().GetRequiredService<RoleManager<IdentityRole>>();
 }
Esempio n. 16
0
        private static ModelBindingContext GetBindingContext(Type modelType)
        {
            var metadataProvider = new TestModelMetadataProvider();
            metadataProvider.ForType(modelType).BindingDetails(d => d.BindingSource = BindingSource.Services);
            var modelMetadata = metadataProvider.GetMetadataForType(modelType);


            var services = new ServiceCollection();
            services.AddInstance<IService>(new Service());

            var bindingContext = new ModelBindingContext
            {
                ModelMetadata = modelMetadata,
                ModelName = "modelName",
                FieldName = "modelName",
                ModelState = new ModelStateDictionary(),
                OperationBindingContext = new OperationBindingContext
                {
                    ModelBinder = new HeaderModelBinder(),
                    MetadataProvider = metadataProvider,
                    HttpContext = new DefaultHttpContext()
                    {
                        RequestServices = services.BuildServiceProvider(),
                    },
                },
                BinderModelName = modelMetadata.BinderModelName,
                BindingSource = modelMetadata.BindingSource,
                ValidationState = new ValidationStateDictionary(),
            };

            return bindingContext;
        }
        private static IServiceCollection CreateServices()
        {
            var services = new ServiceCollection();

            services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);

            return services;
        }
        public void Ctor_WithEncryptorButNoRepository_IgnoresFallback_FailsWithServiceNotFound()
        {
            // Arrange
            var mockFallback = new Mock<IDefaultKeyServices>();
            mockFallback.Setup(o => o.GetKeyEncryptor()).Returns(new Mock<IXmlEncryptor>().Object);
            mockFallback.Setup(o => o.GetKeyRepository()).Returns(new Mock<IXmlRepository>().Object);

            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<IDefaultKeyServices>(mockFallback.Object);
            serviceCollection.AddInstance<IXmlEncryptor>(new Mock<IXmlEncryptor>().Object);
            serviceCollection.AddInstance<IAuthenticatedEncryptorConfiguration>(new Mock<IAuthenticatedEncryptorConfiguration>().Object);
            var services = serviceCollection.BuildServiceProvider();

            // Act & assert - we don't care about exception type, only exception message
            Exception ex = Assert.ThrowsAny<Exception>(() => new XmlKeyManager(services));
            Assert.Contains("IXmlRepository", ex.Message);
        }
Esempio n. 19
0
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            // Sure this is right?
            serviceCollection.AddInstance(_loggerFactory);

            IServiceCollection moduleServiceCollection = new ServiceCollection();
            foreach (var dependency in blueprint.Dependencies
                .Where(t => typeof(IModule).IsAssignableFrom(t.Type))) {

                moduleServiceCollection.AddScoped(typeof(IModule), dependency.Type);
            }

            foreach (var service in moduleServiceCollection.BuildServiceProvider().GetServices<IModule>()) {
                service.Configure(serviceCollection);
            }

            foreach (var dependency in blueprint.Dependencies
                .Where(t => !typeof(IModule).IsAssignableFrom(t.Type))) {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                    .Where(itf => typeof(IDependency).IsAssignableFrom(itf))) {
                    _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                    else {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                }
            }

            return serviceCollection.BuildShellServiceProviderWithHost(_serviceProvider);
        }
        public void ThrowsWhenNoServicesAreAvailable()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<IEnumerable<IFoo>>(new List<IFoo>());

            var serviceProvider = serviceCollection.BuildServiceProvider();

            // Act + Assert
            Assert.Throws<InvalidOperationException>(() => serviceProvider.GetRequiredServices<IFoo>());
        }
        public void Encrypt_Decrypt_RoundTrips()
        {
            // Arrange
            var aes = new AesCryptoServiceProvider();
            aes.GenerateKey();

            var serviceCollection = new ServiceCollection();
            var mockInternalEncryptor = new Mock<IInternalCertificateXmlEncryptor>();
            mockInternalEncryptor.Setup(o => o.PerformEncryption(It.IsAny<EncryptedXml>(), It.IsAny<XmlElement>()))
                .Returns<EncryptedXml, XmlElement>((encryptedXml, element) =>
                {
                    encryptedXml.AddKeyNameMapping("theKey", aes); // use symmetric encryption
                    return encryptedXml.Encrypt(element, "theKey");
                });
            serviceCollection.AddInstance<IInternalCertificateXmlEncryptor>(mockInternalEncryptor.Object);

            var mockInternalDecryptor = new Mock<IInternalEncryptedXmlDecryptor>();
            mockInternalDecryptor.Setup(o => o.PerformPreDecryptionSetup(It.IsAny<EncryptedXml>()))
                .Callback<EncryptedXml>(encryptedXml =>
                {
                    encryptedXml.AddKeyNameMapping("theKey", aes); // use symmetric encryption
                });
            serviceCollection.AddInstance<IInternalEncryptedXmlDecryptor>(mockInternalDecryptor.Object);

            var services = serviceCollection.BuildServiceProvider();
            var encryptor = new CertificateXmlEncryptor(services);
            var decryptor = new EncryptedXmlDecryptor(services);

            var originalXml = XElement.Parse(@"<mySecret value='265ee4ea-ade2-43b1-b706-09b259e58b6b' />");

            // Act & assert - run through encryptor and make sure we get back <EncryptedData> element
            var encryptedXmlInfo = encryptor.Encrypt(originalXml);
            Assert.Equal(typeof(EncryptedXmlDecryptor), encryptedXmlInfo.DecryptorType);
            Assert.Equal(XName.Get("EncryptedData", "http://www.w3.org/2001/04/xmlenc#"), encryptedXmlInfo.EncryptedElement.Name);
            Assert.Equal("http://www.w3.org/2001/04/xmlenc#Element", (string)encryptedXmlInfo.EncryptedElement.Attribute("Type"));
            Assert.DoesNotContain("265ee4ea-ade2-43b1-b706-09b259e58b6b", encryptedXmlInfo.EncryptedElement.ToString(), StringComparison.OrdinalIgnoreCase);

            // Act & assert - run through decryptor and make sure we get back the original value
            var roundTrippedElement = decryptor.Decrypt(encryptedXmlInfo.EncryptedElement);
            XmlAssert.Equal(originalXml, roundTrippedElement);
        }
Esempio n. 22
0
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            foreach (var dependency in blueprint.Dependencies
                .Where(t => typeof(IModule).IsAssignableFrom(t.Type))) {

                _logger.LogDebug("IModule Type: {0}", dependency.Type);

                ((IModule)ActivatorUtilities
                    .CreateInstance(_serviceProvider, dependency.Type))
                    .Configure(serviceCollection);
            }

            foreach (var dependency in blueprint.Dependencies
                .Where(t => !typeof(IModule).IsAssignableFrom(t.Type))) {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                    .Where(itf => typeof(IDependency).IsAssignableFrom(itf))) {
                    _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                    else {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                }
            }

            return new WrappingServiceProvider(_serviceProvider, serviceCollection);
        }
        public void Ctor_WithoutEncryptorOrRepository_UsesFallback()
        {
            // Arrange
            var expectedEncryptor = new Mock<IXmlEncryptor>().Object;
            var expectedRepository = new Mock<IXmlRepository>().Object;
            var mockFallback = new Mock<IDefaultKeyServices>();
            mockFallback.Setup(o => o.GetKeyEncryptor()).Returns(expectedEncryptor);
            mockFallback.Setup(o => o.GetKeyRepository()).Returns(expectedRepository);

            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<IDefaultKeyServices>(mockFallback.Object);
            serviceCollection.AddInstance<IAuthenticatedEncryptorConfiguration>(new Mock<IAuthenticatedEncryptorConfiguration>().Object);
            var services = serviceCollection.BuildServiceProvider();

            // Act
            var keyManager = new XmlKeyManager(services);

            // Assert
            Assert.Same(expectedEncryptor, keyManager.KeyEncryptor);
            Assert.Same(expectedRepository, keyManager.KeyRepository);
        }
Esempio n. 24
0
        public void ThrowsWhenNoServicesAreAvailable()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance <IEnumerable <IFoo> >(new List <IFoo>());

            var serviceProvider = serviceCollection.BuildServiceProvider();

            // Act + Assert
            Assert.Throws <InvalidOperationException>(() => serviceProvider.GetRequiredServices <IFoo>());
        }
Esempio n. 25
0
 public async Task CanCreateUsingAddRoleManager()
 {
     var services = new ServiceCollection();
     services.AddEntityFramework().AddInMemoryStore();
     var store = new RoleStore<IdentityRole>(new InMemoryContext());
     services.AddInstance<IRoleStore<IdentityRole>>(store);
     services.AddIdentity<IdentityUser,IdentityRole>();
     var provider = services.BuildServiceProvider();
     var manager = provider.GetRequiredService<RoleManager<IdentityRole>>();
     Assert.NotNull(manager);
     IdentityResultAssert.IsSuccess(await manager.CreateAsync(new IdentityRole("arole")));
 }
Esempio n. 26
0
        public void GetActivator_ServiceProviderHasActivator_ReturnsSameInstance()
        {
            // Arrange
            var expectedActivator = new Mock<IActivator>().Object;
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<IActivator>(expectedActivator);

            // Act
            var actualActivator = serviceCollection.BuildServiceProvider().GetActivator();

            // Assert
            Assert.Same(expectedActivator, actualActivator);
        }
        public void Throws_WhenNo_Services_AreAvailable_NonGeneric()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance <IEnumerable <IFoo> >(new List <IFoo>());

            var serviceProvider = serviceCollection.BuildServiceProvider();

            // Act + Assert
            ExceptionAssert.Throws <InvalidOperationException>(() => serviceProvider.GetRequiredServices(typeof(IFoo)),
                                                               $"No service for type '{typeof(IFoo)}' has been registered.");
        }
Esempio n. 28
0
        public static IServiceProvider CreateServices(string applicationWebSiteName)
        {
            var originalProvider = CallContextServiceLocator.Locator.ServiceProvider;
            var appEnvironment = originalProvider.GetService<IApplicationEnvironment>();

            // When an application executes in a regular context, the application base path points to the root
            // directory where the application is located, for example MvcSample.Web. However, when executing
            // an aplication as part of a test, the ApplicationBasePath of the IApplicationEnvironment points
            // to the root folder of the test project.
            // To compensate for this, we need to calculate the original path and override the application
            // environment value so that components like the view engine work properly in the context of the
            // test.
            var appBasePath = CalculateApplicationBasePath(appEnvironment, applicationWebSiteName);
            var services = new ServiceCollection();
            services.AddInstance(
                typeof(IApplicationEnvironment),
                new TestApplicationEnvironment(appEnvironment, appBasePath));

            // Injecting a custom assembly provider via configuration setting. It's not good enough to just
            // add the service directly since it's registered by MVC. 
            var providerType = CreateAssemblyProviderType(applicationWebSiteName);

            var configuration = new TestConfigurationProvider();
            configuration.Configuration.Set(
                typeof(IControllerAssemblyProvider).FullName,
                providerType.AssemblyQualifiedName);

            services.AddInstance(
                typeof(ITestConfigurationProvider),
                configuration);

            services.AddInstance(
                typeof(ILoggerFactory),
                NullLoggerFactory.Instance);

            return services.BuildServiceProvider(originalProvider);
        }
        public void NonGeneric_GetServices_WithBuildServiceProvider_Returns_EmptyList_WhenNoServicesAvailable()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance <IEnumerable <IFoo> >(new List <IFoo>());
            var serviceProvider = serviceCollection.BuildServiceProvider();

            // Act
            var services = serviceProvider.GetServices(typeof(IFoo));

            // Assert
            Assert.Empty(services);
            Assert.IsType <List <IFoo> >(services);
        }
        public void ValidationAttribute_ForwardsCallToValidateAntiForgeryTokenAuthorizationFilter()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<AntiForgery>(GetAntiForgeryInstance());
            var serviceProvider = serviceCollection.BuildServiceProvider();
            var attribute = new ValidateAntiForgeryTokenAttribute();

            // Act
            var filter = attribute.CreateInstance(serviceProvider);

            // Assert
            var validationFilter = filter as ValidateAntiForgeryTokenAuthorizationFilter;
            Assert.NotNull(validationFilter);
        }
Esempio n. 31
0
        public void StartupClassMayHaveHostingServicesInjected()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<IFakeStartupCallback>(this);
            var services = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List<string>();
            var startup = ApplicationStartup.LoadStartupMethods(services, "Microsoft.AspNet.Hosting.Tests", "WithServices", diagnosticMessages);

            var app = new ApplicationBuilder(services);
            app.ApplicationServices = startup.ConfigureServicesDelegate(serviceCollection);
            startup.ConfigureDelegate(app);

            Assert.Equal(2, _configurationMethodCalledList.Count);
        }
Esempio n. 32
0
        private static IServiceProvider CreateServices()
        {
            var options = new OptionsManager<MvcOptions>(new IConfigureOptions<MvcOptions>[] { });
            options.Value.OutputFormatters.Add(new StringOutputFormatter());
            options.Value.OutputFormatters.Add(new JsonOutputFormatter());

            var services = new ServiceCollection();
            services.AddInstance(new ObjectResultExecutor(
                options,
                new ActionBindingContextAccessor(),
                new TestHttpResponseStreamWriterFactory(),
                NullLoggerFactory.Instance));

            return services.BuildServiceProvider();
        }
        /// <summary>
        /// Provides a default implementation of required services, calls the developer's
        /// configuration overrides, then creates an <see cref="IDataProtectionProvider"/>.
        /// </summary>
        internal IDataProtectionProvider InternalConfigureServicesAndCreateProtectionProvider()
        {
            // Configure the default implementation, passing in our custom discriminator
            var services = new ServiceCollection();
            services.AddDataProtection();
            services.AddInstance<IApplicationDiscriminator>(new SystemWebApplicationDiscriminator());

            // Run user-specified configuration and get an instance of the provider
            ConfigureServices(services);
            var provider = CreateDataProtectionProvider(services.BuildServiceProvider());
            if (provider == null)
            {
                throw new InvalidOperationException(Resources.Startup_CreateProviderReturnedNull);
            }

            // And we're done!
            return provider;
        }