Example #1
0
        public void DuplicateHubNamesThrows()
        {
            // Arrange
            var mockHub        = new Mock <IHub>();
            var mockHubManager = new Mock <IHubManager>();

            mockHubManager.Setup(m => m.GetHub("foo")).Returns(new HubDescriptor {
                Name = "foo", HubType = mockHub.Object.GetType()
            });

            var serviceProvider = new ServiceCollection()
                                  .Add(OptionsServices.GetDefaultServices())
                                  .Add(HostingServices.GetDefaultServices())
                                  .Add(SignalRServices.GetDefaultServices().Where(descriptor => descriptor.ServiceType != typeof(IHubManager)))
                                  .AddInstance <IHubManager>(mockHubManager.Object)
                                  .BuildServiceProvider();

            var dispatcher  = new HubDispatcher(serviceProvider.GetRequiredService <IOptions <SignalROptions> >());
            var testContext = new TestContext("/ignorePath", new Dictionary <string, string>
            {
                { "connectionData", @"[{name: ""foo""}, {name: ""Foo""}]" },
            });

            // Act & Assert
            dispatcher.Initialize(serviceProvider);
            Assert.Throws <InvalidOperationException>(() => dispatcher.Authorize(testContext.MockRequest.Object));
        }
Example #2
0
        private static DbContext TryCreateContextFromStartup(Type type)
        {
#if ASPNET50 || ASPNETCORE50
            try
            {
                // TODO: Let Hosting do this the right way (See aspnet/Hosting#85)
                var hostingServices = new ServiceCollection()
                                      .Add(HostingServices.GetDefaultServices())
                                      .AddInstance <IHostingEnvironment>(new HostingEnvironment {
                    EnvironmentName = "Development"
                })
                                      .BuildServiceProvider(CallContextServiceLocator.Locator.ServiceProvider);
                var assembly       = type.GetTypeInfo().Assembly;
                var startupType    = assembly.DefinedTypes.FirstOrDefault(t => t.Name.Equals("Startup", StringComparison.Ordinal));
                var instance       = ActivatorUtilities.GetServiceOrCreateInstance(hostingServices, startupType.AsType());
                var servicesMethod = startupType.GetDeclaredMethod("ConfigureServices");
                var services       = new ServiceCollection()
                                     .Add(OptionsServices.GetDefaultServices());
                servicesMethod.Invoke(instance, new[] { services });
                var applicationServices = services.BuildServiceProvider(hostingServices);

                return(applicationServices.GetService(type) as DbContext);
            }
            catch
            {
            }
#endif

            return(null);
        }
Example #3
0
        public void Configure(IBuilder app)
        {
            var configuration = new Configuration();

            configuration.AddEnvironmentVariables();

            // Set up application services
            app.UseServices(services =>
            {
                services.Add(OptionsServices.GetDefaultServices());
                services.SetupOptions <BlobStorageOptions>(options =>
                {
                    options.ConnectionString = configuration.Get("ReversePackageSearch:BlobStorageConnection");
                });
                // Add MVC services to the services container
                services.AddMvc();
            });

            // Add static files
            app.UseStaticFiles(new StaticFileOptions {
                FileSystem = new PhysicalFileSystem("content")
            });
            // Add MVC to the request pipeline
            app.UseMvc();
        }
Example #4
0
        public void SetupCallsSortedInOrder()
        {
            var services = new ServiceCollection {
                OptionsServices.GetDefaultServices()
            };
            var dic = new Dictionary <string, string>
            {
                { "Message", "!" },
            };
            var config = new Configuration {
                new MemoryConfigurationSource(dic)
            };

            services.SetupOptions <FakeOptions>(o => o.Message += "Igetstomped", -100000);
            services.SetupOptions <FakeOptions>(config);
            services.SetupOptions <FakeOptions>(o => o.Message += "a", -100);
            services.AddSetup <FakeOptionsSetupC>();
            services.AddSetup(new FakeOptionsSetupB());
            services.AddSetup(typeof(FakeOptionsSetupA));
            services.SetupOptions <FakeOptions>(o => o.Message += "z", 10000);

            var service = services.BuildServiceProvider().GetService <IOptionsAccessor <FakeOptions> >();

            Assert.NotNull(service);
            var options = service.Options;

            Assert.NotNull(options);
            Assert.Equal("!aABCz", options.Message);
        }
Example #5
0
        public static IEnumerable <IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
        {
            var describer = new ServiceDescriber(configuration);

            yield return(describer.Transient <IHostingEngine, HostingEngine>());

            yield return(describer.Transient <IServerManager, ServerManager>());

            yield return(describer.Transient <IStartupManager, StartupManager>());

            yield return(describer.Transient <IStartupLoaderProvider, StartupLoaderProvider>());

            yield return(describer.Transient <IApplicationBuilderFactory, ApplicationBuilderFactory>());

            yield return(describer.Transient <IHttpContextFactory, HttpContextFactory>());

            yield return(describer.Singleton <ITypeActivator, TypeActivator>());

            yield return(describer.Instance <IApplicationLifetime>(new ApplicationLifetime()));

            // TODO: Do we expect this to be provide by the runtime eventually?
            yield return(describer.Singleton <ILoggerFactory, LoggerFactory>());

            yield return(describer.Scoped(typeof(IContextAccessor <>), typeof(ContextAccessor <>)));

            foreach (var service in OptionsServices.GetDefaultServices())
            {
                yield return(service);
            }

            foreach (var service in DataProtectionServices.GetDefaultServices())
            {
                yield return(service);
            }
        }
Example #6
0
        public async Task <T> GetValueAsync <T>(string name, int?userid = null, Func <T> defaultValue = null)
        {
            var o = await _data.FetchOneAsync <Option>(e => e.UserId == userid && e.Name == name)
                    ?? await _data.FetchOneAsync <Option>(e => e.UserId == null && e.Name == name);


            return(OptionsServices.GetValueFromString <T>(o?.Value));
        }
Example #7
0
 public QuestionnairesController()
 {
     _questionnaireService = new QuestionnairesServices();
     _categoryService      = new CategoriesServices();
     _questionsServices    = new QuestionsServices();
     _questionsType        = new QuestionsTypeServices();
     _optionsServices      = new OptionsServices();
 }
Example #8
0
        public static IBuilder UseServices(this IBuilder builder, Func <ServiceCollection, IServiceProvider> configureServices)
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.Add(OptionsServices.GetDefaultServices());
            builder.ApplicationServices = configureServices(serviceCollection);

            return(builder.UseMiddleware(typeof(ContainerMiddleware)));
        }
Example #9
0
        public void IdentityOptionsFromConfig()
        {
            const string roleClaimType          = "rolez";
            const string usernameClaimType      = "namez";
            const string useridClaimType        = "idz";
            const string securityStampClaimType = "stampz";
            const string authType = "auth";

            var dic = new Dictionary <string, string>
            {
                { "identity:claimsidentity:authENTICATIONType", authType },
                { "identity:claimsidentity:roleclaimtype", roleClaimType },
                { "identity:claimsidentity:usernameclaimtype", usernameClaimType },
                { "identity:claimsidentity:useridclaimtype", useridClaimType },
                { "identity:claimsidentity:securitystampclaimtype", securityStampClaimType },
                { "identity:user:requireUniqueEmail", "true" },
                { "identity:password:RequiredLength", "10" },
                { "identity:password:RequireNonLetterOrDigit", "false" },
                { "identity:password:RequireUpperCase", "false" },
                { "identity:password:RequireDigit", "false" },
                { "identity:password:RequireLowerCase", "false" },
                { "identity:lockout:EnabledByDefault", "TRUe" },
                { "identity:lockout:MaxFailedAccessAttempts", "1000" }
            };
            var config = new Configuration {
                new MemoryConfigurationSource(dic)
            };

            Assert.Equal(roleClaimType, config.Get("identity:claimsidentity:roleclaimtype"));

            var services = new ServiceCollection {
                OptionsServices.GetDefaultServices()
            };

            services.AddIdentity(config.GetSubKey("identity"));
            var accessor = services.BuildServiceProvider().GetService <IOptionsAccessor <IdentityOptions> >();

            Assert.NotNull(accessor);
            var options = accessor.Options;

            Assert.Equal(authType, options.ClaimsIdentity.AuthenticationType);
            Assert.Equal(roleClaimType, options.ClaimsIdentity.RoleClaimType);
            Assert.Equal(useridClaimType, options.ClaimsIdentity.UserIdClaimType);
            Assert.Equal(usernameClaimType, options.ClaimsIdentity.UserNameClaimType);
            Assert.Equal(securityStampClaimType, options.ClaimsIdentity.SecurityStampClaimType);
            Assert.True(options.User.RequireUniqueEmail);
            Assert.True(options.User.AllowOnlyAlphanumericNames);
            Assert.True(options.User.AllowOnlyAlphanumericNames);
            Assert.False(options.Password.RequireDigit);
            Assert.False(options.Password.RequireLowercase);
            Assert.False(options.Password.RequireNonLetterOrDigit);
            Assert.False(options.Password.RequireUppercase);
            Assert.Equal(10, options.Password.RequiredLength);
            Assert.True(options.Lockout.EnabledByDefault);
            Assert.Equal(1000, options.Lockout.MaxFailedAccessAttempts);
        }
Example #10
0
        private static IInlineConstraintResolver GetInlineConstraintResolver()
        {
            var services = new ServiceCollection {
                OptionsServices.GetDefaultServices()
            };
            var serviceProvider = services.BuildServiceProvider();
            var accessor        = serviceProvider.GetRequiredService <IOptions <RouteOptions> >();

            return(new DefaultInlineConstraintResolver(serviceProvider, accessor));
        }
Example #11
0
        public void DeleteAnswersOnCascade(int option_id)
        {
            SelectionAnswersServices selectionAnswerService = new SelectionAnswersServices();
            var option = new OptionsServices().GetById(option_id);

            foreach (var selectiontAnswer in option.SelectionAnswers)
            {
                selectionAnswerService.Delete(selectiontAnswer.Id);
                selectionAnswerService.SaveChanges();
            }
        }
Example #12
0
        public static IServiceProvider CreateServiceProvider(Action <IServiceCollection> configure)
        {
            var collection = new ServiceCollection()
                             .Add(OptionsServices.GetDefaultServices())
                             .Add(HostingServices.GetDefaultServices())
                             .Add(SignalRServices.GetDefaultServices());

            configure(collection);

            return(collection.BuildServiceProvider(CallContextServiceLocator.Locator.ServiceProvider));
        }
Example #13
0
        public CustomDbContext <TUser> GetContext <TUser>() where TUser : class
        {
            var services = new ServiceCollection();

            services.Add(OptionsServices.GetDefaultServices());
            services.AddEntityFramework().AddSqlServer();
            services.SetupOptions <DbContextOptions>(options => options.UseSqlServer(ConnectionString));
            var serviceProvider = services.BuildServiceProvider();

            return(new CustomDbContext <TUser>(serviceProvider));
        }
Example #14
0
 public QuestionnairesController(QuestionnairesServices _questionnaireService,
                                 CategoriesServices _categoryService,
                                 QuestionsServices _questionsServices,
                                 QuestionsTypeServices _questionsType,
                                 OptionsServices _optionsServices)
 {
     this._questionnaireService = _questionnaireService;
     this._categoryService      = _categoryService;
     this._questionsServices    = _questionsServices;
     this._questionsType        = _questionsType;
     this._optionsServices      = _optionsServices;
 }
Example #15
0
        public static IServiceProvider ConfigureStaticProviderServices()
        {
            var services = new ServiceCollection();

            services.Add(OptionsServices.GetDefaultServices());
            services.Configure <FakeOptions>(o =>
            {
                o.Configured  = true;
                o.Environment = "StaticProvider";
            });
            return(services.BuildServiceProvider());
        }
Example #16
0
        public IServiceProvider ConfigureProviderArgsServices(IApplicationBuilder me)
        {
            var services = new ServiceCollection();

            services.Add(OptionsServices.GetDefaultServices());
            services.Configure <FakeOptions>(o =>
            {
                o.Configured  = true;
                o.Environment = "ProviderArgs";
            });
            return(services.BuildServiceProvider());
        }
Example #17
0
        protected override RoleManager <IdentityRole> CreateRoleManager(object context)
        {
            if (context == null)
            {
                context = CreateTestContext();
            }
            var services = new ServiceCollection();

            services.Add(OptionsServices.GetDefaultServices());
            services.AddEntityFramework().AddInMemoryStore();
            services.AddIdentityInMemory((InMemoryContext)context);
            return(services.BuildServiceProvider().GetService <RoleManager <IdentityRole> >());
        }
Example #18
0
        public async Task <T> GetValueAsync <T>(string name, int?userid = null, Func <T> defaultValue = null)
        {
            return(await Task.Run(() =>
            {
                using var rk = Registry.CurrentUser.OpenSubKey(@"Software\" + Options.OptionsPath);
                if (rk == null)
                {
                    return defaultValue == null?default:defaultValue();
                }
                var s = rk.GetValue(name)?.ToString();

                return OptionsServices.GetValueFromString(s, defaultValue);
            }).ConfigureAwait(false));
        }
Example #19
0
        public ApplicationDbContext CreateAppContext()
        {
            CreateContext();
            var services = new ServiceCollection();

            services.AddEntityFramework().AddSqlServer();
            services.Add(OptionsServices.GetDefaultServices());
            var serviceProvider = services.BuildServiceProvider();

            var db = new ApplicationDbContext(serviceProvider, serviceProvider.GetService <IOptionsAccessor <DbContextOptions> >());

            db.Database.EnsureCreated();
            return(db);
        }
Example #20
0
        public void ShouldBeIgnoredTests(string property)
        {
            var dic = new Dictionary <string, string>
            {
                { property, "stuff" },
            };
            var config = new Configuration {
                new MemoryConfigurationSource(dic)
            };
            var options = new ComplexOptions();

            OptionsServices.ReadProperties(options, config);
            Assert.Null(options.GetType().GetProperty(property).GetValue(options));
        }
Example #21
0
        public void DropDb()
        {
            var services = new ServiceCollection();

            services.AddEntityFramework().AddSqlServer();
            services.Add(OptionsServices.GetDefaultServices());
            services.SetupOptions <DbContextOptions>(options =>
                                                     options.UseSqlServer(ConnectionString));
            var serviceProvider = services.BuildServiceProvider();
            var db = new ApplicationDbContext(serviceProvider,
                                              serviceProvider.GetService <IOptionsAccessor <DbContextOptions> >());

            db.Database.EnsureDeleted();
        }
Example #22
0
        private static IInlineConstraintResolver GetConstraintResolver()
        {
            var services = new ServiceCollection {
                OptionsServices.GetDefaultServices()
            };

            services.Configure <RouteOptions>(options =>
                                              options
                                              .ConstraintMap
                                              .Add("test", typeof(TestRouteConstraint)));
            var serviceProvider = services.BuildServiceProvider();
            var accessor        = serviceProvider.GetRequiredService <IOptions <RouteOptions> >();

            return(new DefaultInlineConstraintResolver(serviceProvider, accessor));
        }
Example #23
0
        protected override UserManager <IdentityUser> CreateManager(object context)
        {
            var services = new ServiceCollection();

            services.Add(OptionsServices.GetDefaultServices());
            services.AddIdentity().AddInMemory();
            services.SetupOptions <IdentityOptions>(options =>
            {
                options.Password.RequireDigit            = false;
                options.Password.RequireLowercase        = false;
                options.Password.RequireNonLetterOrDigit = false;
                options.Password.RequireUppercase        = false;
                options.User.AllowOnlyAlphanumericNames  = false;
            });
            return(services.BuildServiceProvider().GetService <UserManager <IdentityUser> >());
        }
Example #24
0
        public static UserManager <TUser> CreateManager <TUser>(Func <IUserStore <TUser> > storeFunc) where TUser : class
        {
            var services = new ServiceCollection();

            services.Add(OptionsServices.GetDefaultServices());
            services.AddIdentity <TUser>().AddUserStore(storeFunc);
            services.SetupOptions <IdentityOptions>(options =>
            {
                options.Password.RequireDigit            = false;
                options.Password.RequireLowercase        = false;
                options.Password.RequireNonLetterOrDigit = false;
                options.Password.RequireUppercase        = false;
                options.User.AllowOnlyAlphanumericNames  = false;
            });
            return(services.BuildServiceProvider().GetService <UserManager <TUser> >());
        }
Example #25
0
        public IdentityDbContext CreateContext(bool ensureCreated = false)
        {
            var services = new ServiceCollection();

            services.Add(OptionsServices.GetDefaultServices());
            services.AddEntityFramework().AddSqlServer();
            services.SetupOptions <DbContextOptions>(options => options.UseSqlServer(ConnectionString));
            var serviceProvider = services.BuildServiceProvider();
            var db = new IdentityDbContext(serviceProvider,
                                           serviceProvider.GetService <IOptionsAccessor <DbContextOptions> >().Options);

            if (ensureCreated)
            {
                db.Database.EnsureCreated();
            }
            return(db);
        }
Example #26
0
        public void CanReadComplexProperties()
        {
            var dic = new Dictionary <string, string>
            {
                { "Integer", "-2" },
                { "Boolean", "TRUe" },
                { "Nested:Integer", "11" }
            };
            var config = new Configuration {
                new MemoryConfigurationSource(dic)
            };
            var options = new ComplexOptions();

            OptionsServices.ReadProperties(options, config);
            Assert.True(options.Boolean);
            Assert.Equal(-2, options.Integer);
            Assert.Equal(11, options.Nested.Integer);
        }
        private static SelectionAnswer GenerateSelectionAnswer(FormCollection collection, Evaluation evaluation, Question question, string aux)
        {
            SelectionAnswer s = new SelectionAnswer();

            s.Evaluation_Id = evaluation.Id;
            s.CreationDate  = DateTime.Now;
            s.Option_Id     = Int32.Parse(collection["q[" + question.Id + aux + "]"]);
            int value = new OptionsServices().GetById(s.Option_Id).Value;

            if (!question.Positive)
            {
                value = (new OptionsServices().GetOptionsCount(question.Category.Questionnaire_Id.Value) + 1) - value;
                int questionnaire = (evaluation.Test.Questionnaire_Id.HasValue) ? evaluation.Test.Questionnaire_Id.Value : GetQuestionnaireIdFromEvaluation(evaluation);
                s.Option_Id = new OptionsServices().GetByValue(value, questionnaire).Id;
            }
            s.Question_Id = question.Id;
            return(s);
        }
        public void GetHubContextRejectsInvalidTypes()
        {
            //var resolver = new DefaultDependencyResolver();
            var serviceProvider = new ServiceCollection()
                                  .Add(OptionsServices.GetDefaultServices())
                                  .Add(HostingServices.GetDefaultServices())
                                  .Add(SignalRServices.GetDefaultServices())
                                  .BuildServiceProvider(CallContextServiceLocator.Locator.ServiceProvider);

            var manager = serviceProvider.GetService <IConnectionManager>();

            Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IDontReturnVoidOrTask>());
            Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IHaveOutParameter>());
            Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IHaveRefParameter>());
            Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IHaveProperties>());
            Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IHaveIndexer>());
            Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, IHaveEvent>());
            Assert.Throws <InvalidOperationException>(() => manager.GetHubContext <DemoHub, NotAnInterface>());
        }
Example #29
0
        public void Configure(IBuilder app)
        {
            app.UseFileServer();
#if NET45
            var configuration = new Configuration()
                                .AddJsonFile(@"App_Data\config.json")
                                .AddEnvironmentVariables();

            string diSystem;

            if (configuration.TryGet("DependencyInjection", out diSystem) &&
                diSystem.Equals("AutoFac", StringComparison.OrdinalIgnoreCase))
            {
                app.UseMiddleware <MonitoringMiddlware>();

                var services = new ServiceCollection();

                services.AddMvc();
                services.AddSingleton <PassThroughAttribute>();
                services.AddSingleton <UserNameService>();
                services.AddTransient <ITestService, TestService>();
                services.Add(OptionsServices.GetDefaultServices());

                // Create the autofac container
                ContainerBuilder builder = new ContainerBuilder();

                // Create the container and use the default application services as a fallback
                AutofacRegistration.Populate(
                    builder,
                    services,
                    fallbackServiceProvider: app.ApplicationServices);

                builder.RegisterModule <MonitoringModule>();

                IContainer container = builder.Build();

                app.UseServices(container.Resolve <IServiceProvider>());
            }
            else
#endif
            {
                app.UseServices(services =>
                {
                    services.AddMvc();
                    services.AddSingleton <PassThroughAttribute>();
                    services.AddSingleton <UserNameService>();
                    services.AddTransient <ITestService, TestService>();
                });
            }

            app.UseMvc(routes =>
            {
                routes.MapRoute("areaRoute", "{area:exists}/{controller}/{action}");

                routes.MapRoute(
                    "controllerActionRoute",
                    "{controller}/{action}",
                    new { controller = "Home", action = "Index" });

                routes.MapRoute(
                    "controllerRoute",
                    "{controller}",
                    new { controller = "Home" });
            });
        }
Example #30
0
        public void Initalize(IConfiguration configuration)
        {
            _options = new MSBuildOptions();
            OptionsServices.ReadProperties(_options, configuration);

            var solutionFilePath = _env.SolutionFilePath;

            if (string.IsNullOrEmpty(solutionFilePath))
            {
                var solutions = Directory.GetFiles(_env.Path, "*.sln");
                var result    = SolutionPicker.ChooseSolution(_env.Path, solutions);

                if (result.Message != null)
                {
                    _logger.LogInformation(result.Message);
                }

                if (result.Solution == null)
                {
                    return;
                }

                solutionFilePath = result.Solution;
            }

            SolutionFile solutionFile = null;

            _context.SolutionPath = solutionFilePath;

            using (var stream = File.OpenRead(solutionFilePath))
            {
                using (var reader = new StreamReader(stream))
                {
                    solutionFile = SolutionFile.Parse(reader);
                }
            }
            _logger.LogInformation($"Detecting projects in '{solutionFilePath}'.");

            foreach (var block in solutionFile.ProjectBlocks)
            {
                if (!_supportsProjectTypes.Contains(block.ProjectTypeGuid))
                {
                    if (UnityTypeGuid(block.ProjectName) != block.ProjectTypeGuid)
                    {
                        _logger.LogWarning("Skipped unsupported project type '{0}'", block.ProjectPath);
                        continue;
                    }
                }

                if (_context.ProjectGuidToWorkspaceMapping.ContainsKey(block.ProjectGuid))
                {
                    continue;
                }

                var projectFilePath = Path.GetFullPath(Path.GetFullPath(Path.Combine(_env.Path, block.ProjectPath.Replace('\\', Path.DirectorySeparatorChar))));

                _logger.LogInformation($"Loading project from '{projectFilePath}'.");

                var projectFileInfo = CreateProject(projectFilePath);

                if (projectFileInfo == null)
                {
                    continue;
                }

                var compilationOptions = new CSharpCompilationOptions(projectFileInfo.OutputKind);
#if DNX451
                compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
#endif

                if (projectFileInfo.AllowUnsafe)
                {
                    compilationOptions = compilationOptions.WithAllowUnsafe(true);
                }

                var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(projectFileInfo.Name),
                                                     VersionStamp.Create(),
                                                     projectFileInfo.Name,
                                                     projectFileInfo.AssemblyName,
                                                     LanguageNames.CSharp,
                                                     projectFileInfo.ProjectFilePath,
                                                     compilationOptions: compilationOptions);

                _workspace.AddProject(projectInfo);

                projectFileInfo.WorkspaceId = projectInfo.Id;

                _context.Projects[projectFileInfo.ProjectFilePath]        = projectFileInfo;
                _context.ProjectGuidToWorkspaceMapping[block.ProjectGuid] = projectInfo.Id;

                _watcher.Watch(projectFilePath, OnProjectChanged);
            }

            foreach (var projectFileInfo in _context.Projects.Values)
            {
                UpdateProject(projectFileInfo);
            }
        }