public void ConfigureConfigServerClientSettingsOptions_WithDefaults()
        {
            // Arrange
            var services = new ServiceCollection().AddOptions();
            var environment = new HostingEnvironment();

            // Act and Assert
            var builder = new ConfigurationBuilder().AddConfigServer(environment);
            var config = builder.Build();

            services.Configure<ConfigServerClientSettingsOptions>(config);
            var service = services.BuildServiceProvider().GetService<IOptions<ConfigServerClientSettingsOptions>>();
            Assert.NotNull(service);
            var options = service.Value;
            Assert.NotNull(options);
            ConfigServerTestHelpers.VerifyDefaults(options.Settings);

            Assert.Equal(ConfigServerClientSettings.DEFAULT_PROVIDER_ENABLED, options.Enabled);
            Assert.Equal(ConfigServerClientSettings.DEFAULT_FAILFAST, options.FailFast);
            Assert.Equal(ConfigServerClientSettings.DEFAULT_URI, options.Uri);
            Assert.Equal(ConfigServerClientSettings.DEFAULT_ENVIRONMENT, options.Environment);
            Assert.Equal(ConfigServerClientSettings.DEFAULT_CERTIFICATE_VALIDATION, options.ValidateCertificates);
            Assert.Null(options.Name);
            Assert.Null(options.Label);
            Assert.Null(options.Username);
            Assert.Null(options.Password);
        }
        public void AddWebEncoders_DoesNotOverrideExistingRegisteredEncoders()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();

            // Act
            serviceCollection.AddSingleton<IHtmlEncoder, CommonTestEncoder>();
            serviceCollection.AddSingleton<IJavaScriptStringEncoder, CommonTestEncoder>();
            // we don't register an existing URL encoder
            serviceCollection.AddWebEncoders(options =>
            {
                options.CodePointFilter = new CodePointFilter().AllowChars("ace"); // only these three chars are allowed
            });

            // Assert
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var htmlEncoder = serviceProvider.GetHtmlEncoder();
            Assert.Equal("HtmlEncode[[abcde]]", htmlEncoder.HtmlEncode("abcde"));

            var javaScriptStringEncoder = serviceProvider.GetJavaScriptStringEncoder();
            Assert.Equal("JavaScriptStringEncode[[abcde]]", javaScriptStringEncoder.JavaScriptStringEncode("abcde"));

            var urlEncoder = serviceProvider.GetUrlEncoder();
            Assert.Equal("a%62c%64e", urlEncoder.UrlEncode("abcde"));
        }
        public void AddMvcServicesTwice_DoesNotAddDuplicates()
        {
            // Arrange
            var services = new ServiceCollection();

            // Act
            MvcCoreServiceCollectionExtensions.AddMvcCoreServices(services);
            MvcCoreServiceCollectionExtensions.AddMvcCoreServices(services);

            // Assert
            var singleRegistrationServiceTypes = SingleRegistrationServiceTypes;
            foreach (var service in services)
            {
                if (singleRegistrationServiceTypes.Contains(service.ServiceType))
                {
                    // 'single-registration' services should only have one implementation registered.
                    AssertServiceCountEquals(services, service.ServiceType, 1);
                }
                else
                {
                    // 'multi-registration' services should only have one *instance* of each implementation registered.
                    AssertContainsSingle(services, service.ServiceType, service.ImplementationType);
                }
            }
        }
Esempio n. 4
0
 public ServiceCollection FetchAll()
 {
     ServiceCollection coll = new ServiceCollection();
     Query qry = new Query(Service.Schema);
     coll.LoadAndCloseReader(qry.ExecuteReader());
     return coll;
 }
Esempio n. 5
0
    public TestBase()
    {
      if (ServiceProvider == null)
      {
        var services = new ServiceCollection();

        // set up empty in-memory test db
        services
          .AddEntityFrameworkInMemoryDatabase()
          .AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase().UseInternalServiceProvider(services.BuildServiceProvider()));

        // add identity service
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<AllReadyContext>();
        var context = new DefaultHttpContext();
        context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
        services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });

        // Setup hosting environment
        IHostingEnvironment hostingEnvironment = new HostingEnvironment();
        hostingEnvironment.EnvironmentName = "Development";
        services.AddSingleton(x => hostingEnvironment);

        // set up service provider for tests
        ServiceProvider = services.BuildServiceProvider();
      }
    }
Esempio n. 6
0
        internal static IServiceProvider ConfigureStartup(string startupTypeName, Action<IServiceCollection, bool> registerSystemTypes)
        {
            var usingCustomServiceProvider = false;
            IServiceCollection serviceCollection = new ServiceCollection();
            ConfigureServicesBuilder servicesMethod = null;
            Type startupType = null;

            if (!string.IsNullOrWhiteSpace(startupTypeName))
            {
                startupType = Type.GetType(startupTypeName);
                if (startupType == null)
                {
                    throw new InvalidOperationException($"Can not locate the type specified in the configuration file: '{startupTypeName}'.");
                }

                servicesMethod = FindConfigureServicesDelegate(startupType);
                if (servicesMethod != null && !servicesMethod.MethodInfo.IsStatic)
                {
                    usingCustomServiceProvider = true;
                }
            }

            registerSystemTypes(serviceCollection, usingCustomServiceProvider);

            if (usingCustomServiceProvider)
            {
                var instance = Activator.CreateInstance(startupType);
                return servicesMethod.Build(instance, serviceCollection);
            }

            return serviceCollection.BuildServiceProvider();
        }
        public void ExpandViewLocations_SpecificPlugin(
            string pluginName, 
            bool exists,
            IEnumerable<string> viewLocations,
            IEnumerable<string> expectedViewLocations)
        {
            var pluginManagerMock = new Mock<IPluginManager>();
            if(exists)
                pluginManagerMock.Setup(pm => pm[It.IsAny<TypeInfo>()])
                    .Returns(new PluginInfo(new ModuleStub { UrlPrefix = pluginName }, null, null, null));;

            var services = new ServiceCollection();
            services.Add(new ServiceDescriptor(typeof(IPluginManager), pluginManagerMock.Object));

            var target = new PluginViewLocationExtender();
            var actionContext = new ActionContext { HttpContext = new DefaultHttpContext { RequestServices = services.BuildServiceProvider() } };
            actionContext.ActionDescriptor = new ControllerActionDescriptor { ControllerTypeInfo = typeof(object).GetTypeInfo() };
            var context = new ViewLocationExpanderContext(
               actionContext,
               "testView",
               "test-controller",
               "",
               false);

            var result = target.ExpandViewLocations(context, viewLocations);

            Assert.Equal(expectedViewLocations, result);
        }
 /// <summary>
 /// This follows the same initialization that is provided when <see cref="IDataProtectionProvider"/>
 /// is initialized within ASP.NET 5.0 Dependency Injection.
 /// </summary>
 /// <returns>A fully initialized <see cref="IDataProtectionProvider"/>.</returns>
 internal static IDataProtectionProvider GetDataProtectionProvider()
 {
     ServiceCollection serviceCollection = new ServiceCollection();
     serviceCollection.AddDataProtection();
     IServiceProvider services = serviceCollection.BuildServiceProvider();
     return services.GetDataProtectionProvider();
 }
        public void AddWebEncoders_WithOptions_RegistersEncodersWithCustomCodeFilter()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();

            // Act
            serviceCollection.AddWebEncoders(options =>
            {
                options.CodePointFilter = new CodePointFilter().AllowChars("ace"); // only these three chars are allowed
            });

            // Assert
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var htmlEncoder = serviceProvider.GetRequiredService<IHtmlEncoder>();
            Assert.Equal("a&#x62;c&#x64;e", htmlEncoder.HtmlEncode("abcde"));
            Assert.Same(htmlEncoder, serviceProvider.GetRequiredService<IHtmlEncoder>()); // as singleton instance

            var javaScriptStringEncoder = serviceProvider.GetRequiredService<IJavaScriptStringEncoder>();
            Assert.Equal(@"a\u0062c\u0064e", javaScriptStringEncoder.JavaScriptStringEncode("abcde"));
            Assert.Same(javaScriptStringEncoder, serviceProvider.GetRequiredService<IJavaScriptStringEncoder>()); // as singleton instance

            var urlEncoder = serviceProvider.GetRequiredService<IUrlEncoder>();
            Assert.Equal("a%62c%64e", urlEncoder.UrlEncode("abcde"));
            Assert.Same(urlEncoder, serviceProvider.GetRequiredService<IUrlEncoder>()); // as singleton instance
        }
        public void Initializes_all_entity_set_properties_with_setters()
        {
            var setterFactory = new ClrPropertySetterFactory();

            var setFinderMock = new Mock<IDbSetFinder>();
            setFinderMock.Setup(m => m.FindSets(It.IsAny<DbContext>())).Returns(
                new[]
                {
                    new DbSetProperty("One", typeof(string), setterFactory.Create(typeof(JustAContext).GetAnyProperty("One"))),
                    new DbSetProperty("Two", typeof(object), setterFactory.Create(typeof(JustAContext).GetAnyProperty("Two"))),
                    new DbSetProperty("Three", typeof(string), setterFactory.Create(typeof(JustAContext).GetAnyProperty("Three"))),
                    new DbSetProperty("Four", typeof(string), null)
                });

            var customServices = new ServiceCollection()
                .AddInstance<IDbSetInitializer>(new DbSetInitializer(setFinderMock.Object, new DbSetSource()));

            var serviceProvider = TestHelpers.Instance.CreateServiceProvider(customServices);

            using (var context = new JustAContext(serviceProvider, new DbContextOptionsBuilder().Options))
            {
                Assert.NotNull(context.One);
                Assert.NotNull(context.GetTwo());
                Assert.NotNull(context.Three);
                Assert.Null(context.Four);
            }
        }
        public async Task Can_use_GUIDs_end_to_end_async()
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkInMemoryDatabase()
                .BuildServiceProvider();

            var guids = new List<Guid>();
            var guidsHash = new HashSet<Guid>();
            using (var context = new BronieContext(serviceProvider))
            {
                for (var i = 0; i < 10; i++)
                {
                    guids.Add(context.Add(new Pegasus { Name = "Rainbow Dash " + i }).Entity.Id);
                    guidsHash.Add(guids.Last());
                }

                await context.SaveChangesAsync();
            }

            Assert.Equal(10, guidsHash.Count);

            using (var context = new BronieContext(serviceProvider))
            {
                var pegasuses = await context.Pegasuses.OrderBy(e => e.Name).ToListAsync();

                for (var i = 0; i < 10; i++)
                {
                    Assert.Equal(guids[i], pegasuses[i].Id);
                }
            }
        }
        public async Task Can_use_sequential_GUID_end_to_end_async()
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkSqlServer()
                .BuildServiceProvider();

            using (var context = new BronieContext(serviceProvider, "GooieBronies"))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                for (var i = 0; i < 50; i++)
                {
                    context.Add(new Pegasus { Name = "Rainbow Dash " + i });
                }

                await context.SaveChangesAsync();
            }

            using (var context = new BronieContext(serviceProvider, "GooieBronies"))
            {
                var pegasuses = await context.Pegasuses.OrderBy(e => e.Id).ToListAsync();

                for (var i = 0; i < 50; i++)
                {
                    Assert.Equal("Rainbow Dash " + i, pegasuses[i].Name);
                }
            }
        }
        public void ResolvedServiceGetResponseEncoder()
        {
            ServiceCollection services = new ServiceCollection();
            services
                .WithService("Test", "/")
                    .WithEndpoint("{action}")
                        .Post<Payload>((Payload p) => { });

            ResolvedService service = new ServiceResolver(services).Find(MethodType.Post, "foo");
            EncodingLookupResult result = service.GetResponseEncoder("gzip");
            Assert.IsNotNull(result);
            Assert.AreEqual(EncodingType.Empty, result.EncodingType);
            Assert.AreEqual(new IdentityEncoding(), result.Encoding);

            result = service.GetResponseEncoder("gzip, *");
            Assert.IsNotNull(result);
            Assert.AreEqual(EncodingType.Empty, result.EncodingType);
            Assert.AreEqual(new IdentityEncoding(), result.Encoding);

            services.WithHostEncoding(new GzipDeflateEncoding());
            service = new ServiceResolver(services).Find(MethodType.Post, "foo");
            result = service.GetResponseEncoder("gzip, *");
            Assert.IsNotNull(result);
            Assert.AreEqual(EncodingType.Parse("gzip"), result.EncodingType);
            Assert.AreEqual(new GzipDeflateEncoding(), result.Encoding);

            result = service.GetResponseEncoder("gzip;q=0");
            Assert.IsNotNull(result);
            Assert.AreEqual(EncodingType.Empty, result.EncodingType);
            Assert.AreEqual(new IdentityEncoding(), result.Encoding);
        }
        public async Task Can_use_explicit_values()
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkSqlServer()
                .BuildServiceProvider();

            var guids = new List<Guid>();

            using (var context = new BronieContext(serviceProvider, "GooieExplicitBronies"))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                for (var i = 0; i < 50; i++)
                {
                    guids.Add(context.Add(new Pegasus { Name = "Rainbow Dash " + i, Index = i, Id = Guid.NewGuid() }).Entity.Id);
                }

                await context.SaveChangesAsync();
            }

            using (var context = new BronieContext(serviceProvider, "GooieExplicitBronies"))
            {
                var pegasuses = await context.Pegasuses.OrderBy(e => e.Index).ToListAsync();

                for (var i = 0; i < 50; i++)
                {
                    Assert.Equal("Rainbow Dash " + i, pegasuses[i].Name);
                    Assert.Equal(guids[i], pegasuses[i].Id);
                }
            }
        }
        /// <summary>
        /// Creates a child container.
        /// </summary>
        /// <param name="serviceProvider">The service provider to create a child container for.</param>
        /// <param name="serviceCollection">The services to clone.</param>
        public static IServiceCollection CreateChildContainer(this IServiceProvider serviceProvider, IServiceCollection serviceCollection)
        {
            IServiceCollection clonedCollection = new ServiceCollection();

            foreach (var service in serviceCollection) {
                // Register the singleton instances to all containers
                if (service.Lifetime == ServiceLifetime.Singleton) {
                    var serviceTypeInfo = service.ServiceType.GetTypeInfo();

                    // Treat open-generic registrations differently
                    if (serviceTypeInfo.IsGenericType && serviceTypeInfo.GenericTypeArguments.Length == 0) {
                        // There is no Func based way to register an open-generic type, instead of
                        // tenantServiceCollection.AddSingleton(typeof(IEnumerable<>), typeof(List<>));
                        // Right now, we regsiter them as singleton per cloned scope even though it's wrong
                        // but in the actual examples it won't matter.
                        clonedCollection.AddSingleton(service.ServiceType, service.ImplementationType);
                    }
                    else {
                        // When a service from the main container is resolved, just add its instance to the container.
                        // It will be shared by all tenant service providers.
                        clonedCollection.AddInstance(service.ServiceType, serviceProvider.GetService(service.ServiceType));
                    }
                }
                else {
                    clonedCollection.Add(service);
                }
            }

            return clonedCollection;
        }
        public static ILoggerFactory AddOrchardLogging(
            this ILoggerFactory loggingFactory, 
            IServiceProvider serviceProvider)
        {
            /* TODO (ngm): Abstract this logger stuff outta here! */
            var loader = serviceProvider.GetRequiredService<IExtensionLoader>();
            var manager = serviceProvider.GetRequiredService<IExtensionManager>();

            var descriptor = manager.GetExtension("Orchard.Logging.Console");
            var entry = loader.Load(descriptor);
            var loggingInitiatorTypes = entry
                .Assembly
                .ExportedTypes
                .Where(et => typeof(ILoggingInitiator).IsAssignableFrom(et));

            IServiceCollection loggerCollection = new ServiceCollection();
            foreach (var initiatorType in loggingInitiatorTypes) {
                loggerCollection.AddScoped(typeof(ILoggingInitiator), initiatorType);
            }
            var moduleServiceProvider = serviceProvider.CreateChildContainer(loggerCollection).BuildServiceProvider();
            foreach (var service in moduleServiceProvider.GetServices<ILoggingInitiator>()) {
                service.Initialize(loggingFactory);
            }

            return loggingFactory;
        }
        public HomeControllerTests()
        {
            // Database setup
            var services = new ServiceCollection();
            services.AddEntityFramework()
                    .AddSqlServer()
                    .AddInMemoryDatabase()
                    .AddDbContext<DataDbContext>(options =>
                        options.UseInMemoryDatabase()
                    );

            // Dependencies initializations
            _pageConfiguration = new FakePageConfiguration();

            var optionsBuilder = new DbContextOptionsBuilder<DataDbContext>();
            optionsBuilder.UseInMemoryDatabase();
            _dataDbContext = new DataDbContext(optionsBuilder.Options);

            _contentRepository = new ContentRepository(_dataDbContext);
            _humanReadableContentService = new HumanReadableContentService(_pageConfiguration, _contentRepository);

            _languageManipulationService = new LanguageManipulationService();

            // Controller initialization
            _homeController = new PersonalWebsite.Controllers.HomeController(
                _pageConfiguration,
                _humanReadableContentService,
                _languageManipulationService
            );
        }
        public async Task Can_use_sequence_end_to_end_async()
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkSqlServer()
                .BuildServiceProvider();

            using (var context = new BronieContext(serviceProvider, "BroniesAsync"))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();
            }

            await AddEntitiesAsync(serviceProvider, "BroniesAsync");
            await AddEntitiesAsync(serviceProvider, "BroniesAsync");

            // Use a different service provider so a different generator is used but with
            // the same server sequence.
            serviceProvider = new ServiceCollection()
                .AddEntityFrameworkSqlServer()
                .BuildServiceProvider();

            await AddEntitiesAsync(serviceProvider, "BroniesAsync");

            using (var context = new BronieContext(serviceProvider, "BroniesAsync"))
            {
                var pegasuses = await context.Pegasuses.ToListAsync();

                for (var i = 0; i < 10; i++)
                {
                    Assert.Equal(3, pegasuses.Count(p => p.Name == "Rainbow Dash " + i));
                    Assert.Equal(3, pegasuses.Count(p => p.Name == "Fluttershy " + i));
                }
            }
        }
        public void MultiRegistrationServiceTypes_AreRegistered_MultipleTimes()
        {
            // Arrange
            var services = new ServiceCollection();

            // Register a mock implementation of each service, AddMvcServices should add another implemenetation.
            foreach (var serviceType in MutliRegistrationServiceTypes)
            {
                var mockType = typeof(Mock<>).MakeGenericType(serviceType.Key);
                services.Add(ServiceDescriptor.Transient(serviceType.Key, mockType));
            }

            // Act
            MvcCoreServiceCollectionExtensions.AddMvcCoreServices(services);

            // Assert
            foreach (var serviceType in MutliRegistrationServiceTypes)
            {
                AssertServiceCountEquals(services, serviceType.Key, serviceType.Value.Length + 1);

                foreach (var implementationType in serviceType.Value)
                {
                    AssertContainsSingle(services, serviceType.Key, implementationType);
                }
            }
        }
Esempio n. 20
0
        private static DefaultModelBindingContext 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.AddSingleton<IService>(new Service());

            var bindingContext = new DefaultModelBindingContext
            {
                ActionContext = new ActionContext()
                {
                    HttpContext = new DefaultHttpContext()
                    {
                        RequestServices = services.BuildServiceProvider(),
                    }
                },
                ModelMetadata = modelMetadata,
                ModelName = "modelName",
                FieldName = "modelName",
                ModelState = new ModelStateDictionary(),
                BinderModelName = modelMetadata.BinderModelName,
                BindingSource = modelMetadata.BindingSource,
                ValidationState = new ValidationStateDictionary(),
            };

            return bindingContext;
        }
Esempio n. 21
0
        public async Task Main()
        {
            var services = new ServiceCollection();
            services.AddDefaultServices(defaultProvider);
            services.AddAssembly(typeof(Program).GetTypeInfo().Assembly);
            services.AddOptions();
            services.AddSingleton(x => MemoryCache.INSTANCE);
            services.AddLogging();
            services.AddGlobalConfiguration(environment);

            var provider = services.BuildServiceProvider();

            var logging = provider.GetService<ILoggerFactory>();
            logging.AddProvider(provider.GetService<ISNSLoggerProvider>());
            logging.AddConsole();

            var cancellationSource = new CancellationTokenSource();

            var taskRunner = new TaskRunner(logging.CreateLogger<TaskRunner>(), provider);

            var tasks = taskRunner.RunTasksFromAssembly(typeof(Program).GetTypeInfo().Assembly, cancellationSource.Token);

            Console.CancelKeyPress += (sender, e) =>
            {
                Console.WriteLine("Caught cancel, exiting...");
                cancellationSource.Cancel();
            };

            await Task.WhenAll(tasks);
        }
Esempio n. 22
0
        public void ConfigurationRegistersHookPointsCorrectly()
        {
            IServiceCollection services = new ServiceCollection();
            var configuration = services.BuildApiConfiguration();

            Assert.Null(configuration.GetApiService<IHookA>());
            Assert.Null(configuration.GetApiService<IHookB>());

            var singletonHookPoint = new HookA();
            services.CutoffPrevious<IHookA>(singletonHookPoint);
            configuration = services.BuildApiConfiguration();
            Assert.Same(singletonHookPoint, configuration.GetApiService<IHookA>());
            Assert.Null(configuration.GetApiService<IHookB>());

            var multiCastHookPoint1 = new HookB();
            services.CutoffPrevious<IHookB>(multiCastHookPoint1);
            configuration = services.BuildApiConfiguration();
            Assert.Same(singletonHookPoint, configuration.GetApiService<IHookA>());
            Assert.Equal(multiCastHookPoint1, configuration.GetApiService<IHookB>());

            services = new ServiceCollection()
                .CutoffPrevious<IHookB>(multiCastHookPoint1)
                .ChainPrevious<IHookB, HookB>()
                .AddInstance(new HookB());
            configuration = services.BuildApiConfiguration();
            var multiCastHookPoint2 = configuration.GetApiService<HookB>();
            var handler = configuration.GetApiService<IHookB>();
            Assert.Equal(multiCastHookPoint2, handler);

            var delegateHandler = handler as HookB;
            Assert.NotNull(delegateHandler);
            Assert.Equal(multiCastHookPoint1, delegateHandler.InnerHandler);
        }
Esempio n. 23
0
        public static void Main(string[] args)
        {
            // serilog provider configuration
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.ColoredConsole()
                .CreateLogger();

            // logger factory for program.cs - startup case
            var log = new LoggerFactory().AddSerilog().CreateLogger(typeof(Program).FullName);
            log.LogInformation("Starting from console launcher... press enter to stop.");

            // load config
            var config = new ConfigurationBuilder()
                            .AddJsonFile("analyserconf.json")
                            .Build();

            // use microsofts built in simple DI container.
            var services = new ServiceCollection();
            configureServices(services, config);
            var sp = services.BuildServiceProvider();

            IDictionary<uint, AircraftBeaconSpeedAndTrack> beaconDisplayBuffer = null;
            var events = new Dictionary<string, List<AircraftTrackEvent>>();

            // disposable pattern to stop on read-line.
            using (var analyser = sp.GetService<Core.OGNAnalyser>())
            {
                attachConsoleDisplay(beaconDisplayBuffer, events, analyser);
                Console.ReadLine();
            }
        }
        public void ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName()
        {
            // Arrange
            var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = metadataProvider.GetMetadataForProperty(typeof(PropertyDisplayNameModel), "MyProperty");

            var attribute = new CompareAttribute("OtherProperty");
            var adapter = new CompareAttributeAdapter(attribute, stringLocalizer: null);

            var serviceCollection = new ServiceCollection();
            var requestServices = serviceCollection.BuildServiceProvider();

            var context = new ClientModelValidationContext(metadata, metadataProvider, requestServices);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent(
                    "'MyPropertyDisplayName' and 'OtherPropertyDisplayName' do not match."),
                rule.ErrorMessage);
        }
        public void AddLocalizationWithLocalizationOptions_AddsNeededServices()
        {
            // Arrange
            var collection = new ServiceCollection();

            // Act
            collection.AddLocalization(options => options.ResourcesPath = "Resources");

            // Assert
            var services = collection.ToList();
            Assert.Equal(4, services.Count);

            Assert.Equal(typeof(IStringLocalizerFactory), services[0].ServiceType);
            Assert.Equal(typeof(ResourceManagerStringLocalizerFactory), services[0].ImplementationType);
            Assert.Equal(ServiceLifetime.Singleton, services[0].Lifetime);

            Assert.Equal(typeof(IStringLocalizer<>), services[1].ServiceType);
            Assert.Equal(typeof(StringLocalizer<>), services[1].ImplementationType);
            Assert.Equal(ServiceLifetime.Transient, services[1].Lifetime);

            Assert.Equal(typeof(IConfigureOptions<LocalizationOptions>), services[2].ServiceType);
            Assert.Equal(ServiceLifetime.Singleton, services[2].Lifetime);

            Assert.Equal(typeof(IOptions<>), services[3].ServiceType);
            Assert.Equal(ServiceLifetime.Singleton, services[3].Lifetime);
        }
        public void CreateNewKey_CallsInternalManager()
        {
            // Arrange - mocks
            DateTimeOffset minCreationDate = DateTimeOffset.UtcNow;
            DateTimeOffset? actualCreationDate = null;
            DateTimeOffset activationDate = minCreationDate + TimeSpan.FromDays(7);
            DateTimeOffset expirationDate = activationDate.AddMonths(1);
            var mockInternalKeyManager = new Mock<IInternalXmlKeyManager>();
            mockInternalKeyManager
                .Setup(o => o.CreateNewKey(It.IsAny<Guid>(), It.IsAny<DateTimeOffset>(), activationDate, expirationDate))
                .Callback<Guid, DateTimeOffset, DateTimeOffset, DateTimeOffset>((innerKeyId, innerCreationDate, innerActivationDate, innerExpirationDate) =>
                {
                    actualCreationDate = innerCreationDate;
                });

            // Arrange - services
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddSingleton<IXmlRepository>(new Mock<IXmlRepository>().Object);
            serviceCollection.AddSingleton<IAuthenticatedEncryptorConfiguration>(new Mock<IAuthenticatedEncryptorConfiguration>().Object);
            serviceCollection.AddSingleton<IInternalXmlKeyManager>(mockInternalKeyManager.Object);
            var services = serviceCollection.BuildServiceProvider();
            var keyManager = new XmlKeyManager(services);

            // Act
            keyManager.CreateNewKey(activationDate, expirationDate);

            // Assert
            Assert.InRange(actualCreationDate.Value, minCreationDate, DateTimeOffset.UtcNow);
        }
        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.AddSingleton<IKeyEscrowSink>(mockKeyEscrowSink1.Object);
            serviceCollection.AddSingleton<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 void SaveChanges_delegates()
        {
            var commandBatchPreparerMock = new Mock<ICommandBatchPreparer>();
            var batchExecutorMock = new Mock<IBatchExecutor>();
            var relationalConnectionMock = new Mock<IRelationalConnection>();

            var fragmentTranslatorMock = new Mock<IExpressionFragmentTranslator>();

            var customServices = new ServiceCollection()
                .AddInstance(commandBatchPreparerMock.Object)
                .AddInstance(batchExecutorMock.Object)
                .AddInstance(relationalConnectionMock.Object)
                .AddInstance(fragmentTranslatorMock.Object)
                .AddScoped<RelationalDatabase>();

            var contextServices = RelationalTestHelpers.Instance.CreateContextServices(customServices);

            var relationalDatabase = contextServices.GetRequiredService<RelationalDatabase>();

            var entries = new List<InternalEntityEntry>();

            relationalDatabase.SaveChanges(entries);

            commandBatchPreparerMock.Verify(c => c.BatchCommands(entries));
            batchExecutorMock.Verify(be => be.Execute(It.IsAny<IEnumerable<ModificationCommandBatch>>(), relationalConnectionMock.Object));
        }
        public async Task SaveChangesAsync_delegates()
        {
            var commandBatchPreparerMock = new Mock<ICommandBatchPreparer>();
            var batchExecutorMock = new Mock<IBatchExecutor>();
            var relationalConnectionMock = new Mock<IRelationalConnection>();
            var fragmentTranslatorMock = new Mock<IExpressionFragmentTranslator>();

            var customServices = new ServiceCollection()
                .AddSingleton(commandBatchPreparerMock.Object)
                .AddSingleton(batchExecutorMock.Object)
                .AddSingleton(relationalConnectionMock.Object)
                .AddSingleton(fragmentTranslatorMock.Object)
                .AddScoped<RelationalDatabase>();

            var contextServices = RelationalTestHelpers.Instance.CreateContextServices(customServices);

            var relationalDatabase = contextServices.GetRequiredService<RelationalDatabase>();

            var entries = new List<InternalEntityEntry>();
            var cancellationToken = new CancellationTokenSource().Token;

            await relationalDatabase.SaveChangesAsync(entries, cancellationToken);

            commandBatchPreparerMock.Verify(c => c.BatchCommands(entries));
            batchExecutorMock.Verify(be => be.ExecuteAsync(It.IsAny<IEnumerable<ModificationCommandBatch>>(), relationalConnectionMock.Object, cancellationToken));
        }
        public void SingletonInstanceIsResolved()
        {
            lock (testLock)
            {
                PrismContainerExtension.Reset();
                GC.Collect();

                var foo             = new Foo();
                var services        = new ServiceCollection(); services.AddSingleton <IFoo>(foo);
                var container       = PrismContainerExtension.Create();
                var serviceProvider = container.CreateServiceProvider(services);

                object service = null;
                var    ex      = Record.Exception(() => service = serviceProvider.GetService(typeof(IFoo)));

                Assert.Null(ex);
                Assert.NotNull(service);
                Assert.IsAssignableFrom <IFoo>(service);
                Assert.IsType <Foo>(service);

                Assert.Same(foo, service);
            }
        }
Esempio n. 31
0
        private void JsonOutputFormatterSupportsHAL()
        {
            var services = new ServiceCollection();
            var manager  = new ApplicationPartManager();
            var builder  = new MvcBuilder(services, manager);

            services.AddOptions();
            services.AddSingleton(typeof(ObjectPoolProvider), new DefaultObjectPoolProvider());
            services
            .AddLogging()
            .AddMvcCore()
            .AddJsonFormatters();

            builder.AddApiExtensions();

            var sp = services.BuildServiceProvider();

            MvcOptions mvcOptions = sp.GetService <IOptions <MvcOptions> >().Value;

            var jsonOutputFormatter = mvcOptions.OutputFormatters.OfType <JsonOutputFormatter>().First();

            Assert.Contains(jsonOutputFormatter.SupportedMediaTypes, x => x == "application/hal+json");
        }
Esempio n. 32
0
        public void GlobalSetup()
        {
            var services = new ServiceCollection();

            services.AddSingleton <StarWarsData>();
            services.AddSingleton <StarWarsQuery>();
            services.AddSingleton <StarWarsMutation>();
            services.AddSingleton <HumanType>();
            services.AddSingleton <HumanInputType>();
            services.AddSingleton <DroidType>();
            services.AddSingleton <CharacterInterface>();
            services.AddSingleton <EpisodeEnum>();
            services.AddSingleton <ISchema, StarWarsSchema>();

            _provider = services.BuildServiceProvider();
            _schema   = _provider.GetRequiredService <ISchema>();
            _schema.Initialize();
            _validator = new DocumentValidator();

            _introspectionDocument = new GraphQLDocumentBuilder().Build(Queries.Introspection);
            _fragmentsDocument     = new GraphQLDocumentBuilder().Build(Queries.Fragments);
            _heroDocument          = new GraphQLDocumentBuilder().Build(Queries.Hero);
        }
        public CSRedisFeatureCachingProviderTest()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddEasyCaching(option =>
            {
                option.UseCSRedis(config =>
                {
                    config.DBConfig = new CSRedisDBOptions
                    {
                        ConnectionStrings = new System.Collections.Generic.List <string>
                        {
                            "127.0.0.1:6388,defaultDatabase=10,poolsize=10"
                        }
                    };
                });
            });

            IServiceProvider serviceProvider = services.BuildServiceProvider();

            _provider  = serviceProvider.GetService <IRedisCachingProvider>();
            _nameSpace = "CSRedisFeature";
        }
Esempio n. 34
0
        private IServiceProvider BuildServices(IHttpRequestSender requestSender)
        {
            var services = new ServiceCollection();

            return(services
                   .AddTransient <IHttpRequestSender>(sp => requestSender)
                   .AddTransient <IHttpRequestSenderFactory>(
                       sp =>
            {
                var factoryMock = new Mock <IHttpRequestSenderFactory>();
                factoryMock.Setup(m => m.CreateRequestSender(
                                      It.IsAny <HttpClient>(),
                                      It.IsAny <IHttpRequestContext>()))
                .Returns <HttpClient, IHttpRequestContext>(
                    (client, context) =>
                {
                    return sp.GetService <IHttpRequestSender>();
                });

                return factoryMock.Object;
            })
                   .BuildServiceProvider());
        }
Esempio n. 35
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            var serviceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase()
                                  .BuildServiceProvider();

            builder.ConfigureServices(services => {
                services.AddDbContext <AlzaDbContext>(options => {
                    options.UseInMemoryDatabase("InMemoryTestingDb");                     //Note: here we can switch to some persistent (testing) database
                    options.UseInternalServiceProvider(serviceProvider);
                    options.ReplaceService <IDbContext, AlzaDbContext>();
                });

                services.AddScoped <IDbContext>(provider => provider.GetRequiredService <AlzaDbContext>());

                using var serviceScope = services.BuildServiceProvider()
                                         .CreateScope();

                var scopedServices    = serviceScope.ServiceProvider;
                var inMemoryDbContext = scopedServices.GetRequiredService <AlzaDbContext>();

                inMemoryDbContext.Database.EnsureCreated();
            }).UseEnvironment("Test");
        }
Esempio n. 36
0
        static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddCore();
            serviceCollection.AddInMemory();
            var serviceProvider     = serviceCollection.BuildServiceProvider();
            var nodeLauncherFactory = serviceProvider.GetService <INodeLauncherFactory>();

            Console.WriteLine("==== Welcome to SimpleBlockChain (SEED NODE) ====");
            var network = MenuHelper.ChooseNetwork();
            var ipBytes = IPAddress.Parse(Constants.DNS_IP_ADDRESS).MapToIPv6().GetAddressBytes();

            _nodeLauncher = nodeLauncherFactory.Build(network, ServiceFlags.NODE_NETWORK);
            var p2pNode = _nodeLauncher.GetP2PNode();

            p2pNode.StartNodeEvent           += StartP2PNodeEvent;
            p2pNode.NewMessageEvent          += NewP2PMessageEvent;
            _nodeLauncher.ConnectP2PEvent    += ConnectP2PEvent;
            _nodeLauncher.DisconnectP2PEvent += DisconnectP2PEvent;
            _nodeLauncher.LaunchP2PNode(ipBytes);
            Console.ReadLine();
        }
Esempio n. 37
0
        protected override void OnStartup(StartupEventArgs e)
        {
#if !DEBUG
            //通过特殊手段运行应用可能导致工作目录与程序文件所在目录不一致,需要调整,否则配置文件和其他数据无法加载(仅限发布模式,调试模式修改工作目录也可能导致配置和其他数据无法加载)
            var pathToExe         = Process.GetCurrentProcess().MainModule.FileName;
            var pathToContentRoot = Path.GetDirectoryName(pathToExe);
            Directory.SetCurrentDirectory(pathToContentRoot);
#endif

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("guiAppsettings.json", optional: false, reloadOnChange: true);

            Configuration = builder.Build();

            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);

            ServiceProvider = serviceCollection.BuildServiceProvider();

            var mainWindow = ServiceProvider.GetRequiredService <MainWindow>();
            mainWindow.Show();
        }
Esempio n. 38
0
        private static RouteContext CreateRouteContext(string httpMethod)
        {
            var routeData = new RouteData();

            routeData.Routers.Add(new Mock <IRouter>(MockBehavior.Strict).Object);

            var serviceProvider = new ServiceCollection().BuildServiceProvider();

            var httpContext = new Mock <HttpContext>(MockBehavior.Strict);

            var request = new Mock <HttpRequest>(MockBehavior.Strict);

            request.SetupGet(r => r.Method).Returns(httpMethod);
            request.SetupGet(r => r.Path).Returns(new PathString());
            request.SetupGet(r => r.Headers).Returns(new HeaderDictionary());
            httpContext.SetupGet(c => c.Request).Returns(request.Object);
            httpContext.SetupGet(c => c.RequestServices).Returns(serviceProvider);

            return(new RouteContext(httpContext.Object)
            {
                RouteData = routeData,
            });
        }
        private static void ConfigureLoadBalancingWithInvalidHttpHandler(Action <GrpcChannelOptions> channelOptionsFunc)
        {
            // Arrange
            var services = new ServiceCollection();

            services.AddSingleton <ResolverFactory, ChannelTestResolverFactory>();

            var channelOptions = new GrpcChannelOptions
            {
                ServiceProvider = services.BuildServiceProvider(),
                Credentials     = ChannelCredentials.Insecure
            };

            channelOptionsFunc(channelOptions);

            // Act
            var ex = Assert.Throws <InvalidOperationException>(() => GrpcChannel.ForAddress("test:///localhost", channelOptions)) !;

            // Assert
            Assert.AreEqual("Channel is configured with an HTTP transport doesn't support client-side load balancing or connectivity state tracking. " +
                            "The underlying HTTP transport must be a SocketsHttpHandler with no SocketsHttpHandler.ConnectCallback configured. " +
                            "The HTTP transport must be configured on the channel using GrpcChannelOptions.HttpHandler.", ex.Message);
        }
Esempio n. 40
0
        public async Task Ensure_Executor_Is_Cached()
        {
            // arrange
            IRequestExecutorResolver resolver =
                new ServiceCollection()
                .AddGraphQL()
                .AddStarWarsRepositories()
                .AddStarWarsTypes()
                .Services
                .BuildServiceProvider()
                .GetRequiredService <IRequestExecutorResolver>();

            var innerProxy = new RequestExecutorProxy(resolver, Schema.DefaultName);

            // act
            var proxy = await AutoUpdateRequestExecutorProxy.CreateAsync(innerProxy);

            IRequestExecutor a = proxy.InnerExecutor;
            IRequestExecutor b = proxy.InnerExecutor;

            // assert
            Assert.Same(a, b);
        }
        public void TransientServiceIsRegistered()
        {
            lock (testLock)
            {
                PrismContainerExtension.Reset();
                GC.Collect();

                var services = new ServiceCollection();
                services.AddTransient <IFoo, Foo>();
                var container       = PrismContainerExtension.Create();
                var serviceProvider = container.CreateServiceProvider(services);

                object service = null;
                var    ex      = Record.Exception(() => service = serviceProvider.GetService(typeof(IFoo)));

                Assert.Null(ex);
                Assert.NotNull(service);
                Assert.IsAssignableFrom <IFoo>(service);
                Assert.IsType <Foo>(service);

                Assert.NotSame(service, serviceProvider.GetService(typeof(IFoo)));
            }
        }
Esempio n. 42
0
        public async Task CanRender_NestedAsyncComponents()
        {
            // Arrange
            var expectedHtml = new[]
            {
                "<", "p", ">", "20", "</", "p", ">",
                "<", "p", ">", "80", "</", "p", ">"
            };

            var serviceProvider = new ServiceCollection().AddSingleton <AsyncComponent>().BuildServiceProvider();

            var htmlRenderer = GetHtmlRenderer(serviceProvider);

            // Act
            var result = await htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync <NestedAsyncComponent>(ParameterCollection.FromDictionary(new Dictionary <string, object>
            {
                ["Nested"] = false,
                ["Value"]  = 10
            })));

            // Assert
            Assert.Equal(expectedHtml, result.Tokens);
        }
Esempio n. 43
0
    private static IServiceProvider ConfigureServices()
    {
        IServiceCollection services = new ServiceCollection();

        services.AddSingleton <ITextAreaFactory, TextAreaFactory>();
        services.AddSingleton <ILabelFactory, LabelFactory>();
        services.AddSingleton <IMenuFactory, MenuFactory>();
        services.AddSingleton <ICommandFactory, CommandFactory>();

        services.AddSingleton <ForumData>();
        services.AddTransient <IPostService, PostService>();
        services.AddTransient <IUserService, UserService>();

        services.AddSingleton <ISession, Session>();
        services.AddSingleton <IForumViewEngine, ForumViewEngine>();
        services.AddSingleton <IMainController, MenuController>();

        services.AddTransient <IForumReader, ForumConsoleReader>();

        IServiceProvider serviceProvider = services.BuildServiceProvider();

        return(serviceProvider);
    }
Esempio n. 44
0
        public static IServiceDispatcher BuildDispatcher <TService>(ServiceCollection services, string serviceAddress) where TService : class, ISimpleService
        {
            services.AddServiceModelServices();
            var serverAddressesFeature = new ServerAddressesFeature();

            serverAddressesFeature.Addresses.Add(serviceAddress);
            IServer server = new MockServer();

            server.Features.Set <IServerAddressesFeature>(serverAddressesFeature);
            services.AddSingleton(server);
            var serviceProvider = services.BuildServiceProvider();
            var serviceBuilder  = serviceProvider.GetRequiredService <IServiceBuilder>();

            serviceBuilder.AddService <TService>();
            var binding = new CustomBinding("BindingName", "BindingNS");

            binding.Elements.Add(new MockTransportBindingElement());
            serviceBuilder.AddServiceEndpoint <TService, ISimpleService>(binding, serviceAddress);
            var dispatcherBuilder = serviceProvider.GetRequiredService <IDispatcherBuilder>();
            var dispatchers       = dispatcherBuilder.BuildDispatchers(typeof(TService));

            return(dispatchers[0]);
        }
Esempio n. 45
0
        public static void Main(string[] args)
        {
            IServiceCollection services = new ServiceCollection();

            services.AddSingleton<Manager>();

            services.AddLogger();
            services.AddDatabaseDependencies(new AppConfig
            {
                Database = "output/database.db"
            });

            services.AddImplementingTypes<ICommandHandler>();
            services.AddImplementingTypes<Parser>();

            IServiceProvider provider = services.BuildServiceProvider();

            Manager manager = provider.GetService<Manager>();

            ParserResult<object> parserResult = CommandLine.Parser.Default.ParseArguments(args, manager.GetCommandTypes());

            parserResult.MapResult(x => manager.Handle(x as ICommand), errors => false);
        }
        public void AddGraphQL_ServicesSchemaConfigureBuilder()
        {
            // arrange
            var services  = new ServiceCollection();
            var schema    = "type Query { a: String }";
            var schemaCfg = new Action <ISchemaConfiguration>(
                c => c.Options.StrictValidation = false);
            var cfg = new Action <IQueryExecutionBuilder>(
                c => c.UseDefaultPipeline());

            // act
            ServiceCollectionExtensions.AddGraphQL(
                services,
                schema,
                schemaCfg,
                cfg);

            // assert
            services.Select(t => ReflectionUtils.GetTypeName(t.ServiceType))
            .OrderBy(t => t, StringComparer.Ordinal)
            .ToArray()
            .MatchSnapshot();
        }
Esempio n. 47
0
        private static void ConfigureServices(ServiceCollection services)
        {
            var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", false, true)
                                .AddEnvironmentVariables()
                                .Build();

            services.AddSingleton <IConfiguration>(configuration);

            services.AddDbContext <ApplicationDbContext>(
                options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"))
                .UseLoggerFactory(new LoggerFactory()));

            services.AddDefaultIdentity <ApplicationUser>(IdentityOptionsProvider.GetIdentityOptions)
            .AddRoles <ApplicationRole>().AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddScoped(typeof(IDeletableEntityRepository <>), typeof(EfDeletableEntityRepository <>));
            services.AddScoped(typeof(IRepository <>), typeof(EfRepository <>));
            services.AddScoped <IDbQueryRunner, DbQueryRunner>();

            // Application services
            services.AddTransient <IEmailSender, NullMessageSender>();
        }
Esempio n. 48
0
        public static void Main(string[] args)
        {
            var container = new ServiceCollection();

            container.AddLogging(x => x.AddConsole());
            container.AddCap(x =>
            {
                //console app does not support dashboard

                x.UseMySql("Server=192.168.3.57;Port=3307;Database=captest;Uid=root;Pwd=123123;");
                x.UseRabbitMQ(z =>
                {
                    z.HostName = "192.168.3.57";
                    z.UserName = "******";
                    z.Password = "******";
                });
            });

            container.AddSingleton <EventSubscriber>();

            var sp = container.BuildServiceProvider();

            sp.GetService <IBootstrapper>().BootstrapAsync(default);
        public void CanCreatePDF()
        {
            var services = new ServiceCollection();

            services.AddNodeServices(options => {
                // Set any properties that you want on 'options' here
            });
            var serviceProvider = services.BuildServiceProvider();
            var nodeServices    = serviceProvider.GetRequiredService <INodeServices>();
            JavaScriptService javaScriptService = new JavaScriptService(nodeServices, SCRIPT_FOLDER_TS);
            var result = javaScriptService.MakePDF("Hello Mike").Result;

            Assert.IsNotNull(result);

            if (File.Exists("test.pdf"))
            {
                File.Delete("test.pdf");
            }

            File.WriteAllBytes("test.pdf", result);

            Assert.IsTrue(File.Exists("test.pdf"));
        }
Esempio n. 50
0
        private TestServiceProvider(string dbName, Action <ServiceCollection> additionalServices = null)
        {
            DatabaseName = dbName;

            ServiceCollection _services = new ServiceCollection();

            _services.AddScoped <IDateTime, TestDateTime>();
            _services.AddScoped <IJsonSerializer, TestJsonSerializer>();

            _services.AddApplication(includeValidators: true);
            _services.AddLogging();


            _services.AddInfrastructureUseInMemory(DatabaseName);
            _services.AddInfrastructure(null);

            if (additionalServices != null)
            {
                additionalServices.Invoke(_services);
            }

            p_ServiceProvider = _services.BuildServiceProvider();
        }
Esempio n. 51
0
        public sealed override void ConfigureDefaultHandlers(ServiceCollection services)
        {
            base.ConfigureDefaultHandlers(services);

            services.AddSingleton <IChromelyMessageRouter, ChromelyMessageRouter>();

            // Add default resource/request handlers
            services.AddSingleton <IChromelyRequestSchemeProvider, DefaultRequestSchemeProvider>();

            services.AddSingleton <CefSchemeHandlerFactory, ChromelyResourceSchemeHandlerFactory>();
            services.AddSingleton <CefSchemeHandlerFactory, ChromelyAssemblyResourceSchemeHandlerFactory>();
            services.AddSingleton <CefSchemeHandlerFactory, ChromelyRequestSchemeHandlerFactory>();
            services.AddSingleton <CefSchemeHandlerFactory, ChromelyExternalRequestSchemeHandlerFactory>();

            // Adde default custom handlers
            services.AddSingleton <CefContextMenuHandler, ChromelyContextMenuHandler>();
            services.AddSingleton <CefDisplayHandler, ChromelyDisplayHandler>();
            services.AddSingleton <CefDownloadHandler, ChromelyDownloadHandler>();
            services.AddSingleton <CefDragHandler, ChromelyDragHandler>();
            services.AddSingleton <CefLifeSpanHandler, ChromelyLifeSpanHandler>();
            services.AddSingleton <CefLoadHandler, ChromelyLoadHandler>();
            services.AddSingleton <CefRequestHandler, ChromelyRequestHandler>();
        }
Esempio n. 52
0
        public TestMvcOptions()
        {
            Value = new MvcOptions();
            MvcCoreMvcOptionsSetup.ConfigureMvc(Value, new TestHttpRequestStreamReaderFactory());
            var collection = new ServiceCollection().AddOptions();

            collection.AddSingleton <ICompositeMetadataDetailsProvider, DefaultCompositeMetadataDetailsProvider>();
            collection.AddSingleton <IModelMetadataProvider, DefaultModelMetadataProvider>();
            collection.AddSingleton <IValidationAttributeAdapterProvider, ValidationAttributeAdapterProvider>();
            MvcDataAnnotationsMvcOptionsSetup.ConfigureMvc(
                Value,
                collection.BuildServiceProvider());

            var loggerFactory      = new LoggerFactory();
            var serializerSettings = SerializerSettingsProvider.CreateSerializerSettings();

            MvcJsonMvcOptionsSetup.ConfigureMvc(
                Value,
                serializerSettings,
                loggerFactory,
                ArrayPool <char> .Shared,
                new DefaultObjectPoolProvider());
        }
Esempio n. 53
0
        public void Get_ThrowsAnExceptionWhenDbContextTypeIsNotAvailable()
        {
            // Arrange
            var services = new ServiceCollection();

            var monitor = Mock.Of <IOptionsMonitor <OpenIddictEntityFrameworkOptions> >(
                mock => mock.CurrentValue == new OpenIddictEntityFrameworkOptions
            {
                DbContextType = null
            });

            var provider = services.BuildServiceProvider();
            var resolver = new OpenIddictApplicationStoreResolver(monitor, provider);

            // Act and assert
            var exception = Assert.Throws <InvalidOperationException>(() => resolver.Get <OpenIddictApplication>());

            Assert.Equal(new StringBuilder()
                         .AppendLine("No Entity Framework 6.x context was specified in the OpenIddict options.")
                         .Append("To configure the OpenIddict Entity Framework 6.x stores to use a specific 'DbContext', ")
                         .Append("use 'options.UseEntityFramework().UseDbContext<TContext>()'.")
                         .ToString(), exception.Message);
        }
Esempio n. 54
0
        public void AppendSameSiteNoneWithoutSecureLogsWarning()
        {
            var headers  = (IHeaderDictionary) new HeaderDictionary();
            var features = MakeFeatures(headers);
            var services = new ServiceCollection();

            var sink          = new TestSink(TestSink.EnableWithTypeName <ResponseCookies>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            services.AddLogging();
            services.AddSingleton <ILoggerFactory>(loggerFactory);

            features.Set <IServiceProvidersFeature>(new ServiceProvidersFeature()
            {
                RequestServices = services.BuildServiceProvider()
            });

            var cookies    = new ResponseCookies(features);
            var testCookie = "TestCookie";

            cookies.Append(testCookie, "value", new CookieOptions()
            {
                SameSite = SameSiteMode.None,
            });

            var cookieHeaderValues = headers.SetCookie;

            Assert.Single(cookieHeaderValues);
            Assert.StartsWith(testCookie, cookieHeaderValues[0]);
            Assert.Contains("path=/", cookieHeaderValues[0]);
            Assert.Contains("samesite=none", cookieHeaderValues[0]);
            Assert.DoesNotContain("secure", cookieHeaderValues[0]);

            var writeContext = Assert.Single(sink.Writes);

            Assert.Equal("The cookie 'TestCookie' has set 'SameSite=None' and must also set 'Secure'.", writeContext.Message);
        }
Esempio n. 55
0
        public void Basic()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddInsql(builder =>
            {
            });

            using (var serviceProvider = serviceCollection.BuildServiceProvider())
            {
                using (var scopeProvider = serviceProvider.CreateScope())
                {
                    var resolver = scopeProvider.ServiceProvider.GetRequiredService <IInsqlScriptResolver>();

                    var result = (bool)resolver.Resolve(TypeCode.Boolean, " userId != null ", new Dictionary <string, object>
                    {
                        { "userId", "aa" }
                    });

                    Assert.True(result);

                    result = (bool)resolver.Resolve(TypeCode.Boolean, " userId == null ", new Dictionary <string, object>
                    {
                        { "userId", null }
                    });

                    Assert.True(result);

                    result = (bool)resolver.Resolve(TypeCode.Boolean, " userId == null ", new Dictionary <string, object>
                    {
                        { "userId", "" }
                    });

                    Assert.False(result);
                }
            }
        }
Esempio n. 56
0
        public static void BuildDispatcherWithConfiguration_Singleton_WellKnown()
        {
            string serviceAddress = "http://localhost/dummy";
            var    services       = new ServiceCollection();

            services.AddLogging();
            services.AddServiceModelServices();
            IServer server = new MockServer();

            services.AddSingleton(server);
            services.AddSingleton(new SimpleSingletonService());
            var serviceProvider = services.BuildServiceProvider();
            var serviceBuilder  = serviceProvider.GetRequiredService <IServiceBuilder>();

            serviceBuilder.BaseAddresses.Add(new Uri(serviceAddress));
            serviceBuilder.AddService <SimpleSingletonService>();
            var binding = new CustomBinding("BindingName", "BindingNS");

            binding.Elements.Add(new MockTransportBindingElement());
            serviceBuilder.AddServiceEndpoint <SimpleSingletonService, ISimpleService>(binding, serviceAddress);
            serviceBuilder.OpenAsync().GetAwaiter().GetResult();
            var dispatcherBuilder = serviceProvider.GetRequiredService <IDispatcherBuilder>();
            var dispatchers       = dispatcherBuilder.BuildDispatchers(typeof(SimpleSingletonService));

            Assert.Single(dispatchers);
            var serviceDispatcher = dispatchers[0];

            Assert.Equal("foo", serviceDispatcher.Binding.Scheme);
            Assert.Equal(serviceAddress, serviceDispatcher.BaseAddress.ToString());
            IChannel mockChannel    = new MockReplyChannel(serviceProvider);
            var      dispatcher     = serviceDispatcher.CreateServiceChannelDispatcherAsync(mockChannel).Result;
            var      requestContext = TestRequestContext.Create(serviceAddress);

            dispatcher.DispatchAsync(requestContext).Wait();
            Assert.True(requestContext.WaitForReply(TimeSpan.FromSeconds(5)), "Dispatcher didn't send reply");
            requestContext.ValidateReply();
        }
Esempio n. 57
0
        static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();

            ConfigureServices(serviceCollection);
            var serviceProvider = serviceCollection.BuildServiceProvider();

            //var quizService = serviceProvider.GetService<IQuizService>();
            //quizService.Add("C# DB");

            //var questionService = serviceProvider.GetService<IQuestionService>();
            //Console.WriteLine(questionService.Add("What is Entity Framework Core", 1));

            //var answerService = serviceProvider.GetService<IAnswerService>();
            //Console.WriteLine(answerService.Add("It is a ORM", 5, true, 1));
            //var userAnswerService = serviceProvider.GetService<IUserAnswerService>();
            //userAnswerService.AddUserAnswer("598bab03-e71d-42ec-bba1-264fba7e632c", 1,1,1);

            //var quizService = serviceProvider.GetService<IQuizService>();
            //var quiz = quizService.GetQuizById(1);
            // Console.WriteLine(quiz.Title);
            //foreach (var question in quiz.Questions)
            //{
            //    Console.WriteLine(question.Title);

            //    foreach (var answer in question.Answers)
            //    {
            //        Console.WriteLine(answer.Title);
            //    }
            //}


            var userAnswerService = serviceProvider.GetService <IUserAnswerService>();
            var quiz = userAnswerService.GetUserResult("598bab03-e71d-42ec-bba1-264fba7e632c", 1);

            Console.WriteLine(quiz);
        }
Esempio n. 58
0
        public void TestServicesReconnectToSchemaContext()
        {
            var schema = SchemaBuilder.FromObject <TestDataContext>();

            // Linking a type from a service back to the schema context
            schema.AddType <User>("User").AddAllFields();
            schema.Type <User>().AddField("projects",
                                          (user) => WithService((TestDataContext db) => db.Projects.Where(p => p.Owner.Id == user.Id)),
                                          "Peoples projects");

            schema.AddField("user", ctx => WithService((UserService users) => users.GetUser()), "Get current user");

            var gql = new QueryRequest
            {
                Query = @"{ user { projects { id } } }"
            };

            var context = new TestDataContext
            {
                Projects = new List <Project>(),
                People   = new List <Person>
                {
                    new Person
                    {
                        Projects = new List <Project>()
                    }
                },
            };
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(new UserService());
            serviceCollection.AddSingleton(context);

            var res = schema.ExecuteQuery(gql, context, serviceCollection.BuildServiceProvider(), null);

            Assert.Null(res.Errors);
        }
Esempio n. 59
0
        // Кнопка LogIn
        public void button1_Click(object sender, EventArgs e)
        {
            ServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddAudioBypass();
            api = new VkApi(serviceCollection);
            bool auth = false;

            // Авторизация
            try // Обработка неправильного логина или пароля
            {
                api.Authorize(new ApiAuthParams
                {
                    Login    = textBox1.Text,
                    Password = textBox2.Text,
                    TwoFactorAuthorization = () =>
                    {
                        return(api.Token);
                    }
                });

                auth              = true;
                label4.Visible    = false;
                groupAuth.Visible = false;
            }
            catch (VkNet.AudioBypassService.Exceptions.VkAuthException)
            {
                label4.Visible = true;
            }
            if (auth != true)
            {
                return;
            }
            var res = api.Groups.Get(new GroupsGetParams());

            GetAudio();
        }
        public void ClientRulesWithMaxLengthAttribute_StringLocalizer_ReturnsLocalizedErrorString()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");
            var errorKey = metadata.GetDisplayName();
            var attribute = new MaxLengthAttribute(10);
            attribute.ErrorMessage = errorKey;

            var localizedString = new LocalizedString(errorKey, "Longueur est invalide");
            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s[errorKey]).Returns(localizedString);

            var adapter = new MaxLengthAttributeAdapter(attribute, stringLocalizer.Object);
            var serviceCollection = new ServiceCollection();
            var requestServices = serviceCollection.BuildServiceProvider();
            var context = new ClientModelValidationContext(metadata, provider, requestServices);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("maxlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(10, rule.ValidationParameters["max"]);
            Assert.Equal("Longueur est invalide", rule.ErrorMessage);
        }