public void PerformSearch_WhenFindSpecificationsServiceUnavailable_ThenHttpExceptionThrown()
        {
            // Arrange
            ISpecsApiClient specsClient   = Substitute.For <ISpecsApiClient>();
            ILogger         logger        = Substitute.For <ILogger>();
            IMapper         mapper        = MappingHelper.CreateFrontEndMapper();
            IFeatureToggle  featureToggle = CreateFeatureToggle();

            ISpecificationSearchService SpecificationSearchService = new SpecificationSearchService(specsClient, mapper, logger, featureToggle);

            specsClient
            .When(a => a.FindSpecifications(Arg.Any <SearchFilterRequest>()))
            .Do(x => { throw new HttpRequestException(); });

            SearchRequestViewModel request = new SearchRequestViewModel();

            // Act
            Action pageAction = new Action(() =>
            {
                SpecificationSearchResultViewModel result = SpecificationSearchService.PerformSearch(request).Result;
            });

            // Assert
            pageAction.Should().Throw <HttpRequestException>();
        }
        public async Task WhenUserIsKnown_AndHasNoPermissions_ShouldNotSucceed()
        {
            // Arrange
            string          userId    = Guid.NewGuid().ToString();
            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(Constants.ObjectIdentifierClaimType, userId) }));
            ISpecificationAuthorizationEntity specification = Substitute.For <ISpecificationAuthorizationEntity>();

            specification.GetSpecificationId().Returns(WellKnownSpecificationId);
            AuthorizationHandlerContext authContext = CreateAuthenticationContext(principal, SpecificationActionTypes.CanApproveFunding, specification);

            IUsersApiClient usersApiClient = Substitute.For <IUsersApiClient>();

            usersApiClient.GetEffectivePermissionsForUser(Arg.Is(userId), Arg.Is(WellKnownSpecificationId)).Returns(new ApiResponse <EffectiveSpecificationPermission>(HttpStatusCode.OK, new EffectiveSpecificationPermission()));

            IOptions <PermissionOptions> options = Substitute.For <IOptions <PermissionOptions> >();

            options.Value.Returns(actualOptions);

            IFeatureToggle features = Substitute.For <IFeatureToggle>();

            features.IsRoleBasedAccessEnabled().Returns(true);

            SpecificationPermissionHandler authHandler = new SpecificationPermissionHandler(usersApiClient, options, features);

            // Act
            await authHandler.HandleAsync(authContext);

            // Assert
            authContext.HasSucceeded.Should().BeFalse();
        }
Esempio n. 3
0
        public async Task PerformSearch_StartAndEndItemsNumbersDisplayedCorrectlyOnSecondPageOfItemsWithLessThanPageSize()
        {
            // Arrange
            ICalculationsApiClient calcsClient = Substitute.For <ICalculationsApiClient>();
            ILogger        logger        = Substitute.For <ILogger>();
            IMapper        mapper        = MappingHelper.CreateFrontEndMapper();
            IFeatureToggle featureToggle = CreateFeatureToggle();

            ICalculationSearchService calculationSearchService = new CalculationSearchService(calcsClient, mapper, logger, featureToggle);

            int numberOfItems = 25;

            PagedResult <CalculationSearchResultItem> itemResult = GeneratePagedResult(numberOfItems);

            itemResult.PageNumber = 2;
            itemResult.PageSize   = 50;
            itemResult.TotalItems = 75;

            calcsClient
            .FindCalculations(Arg.Any <SearchFilterRequest>())
            .Returns(itemResult);

            SearchRequestViewModel request = new SearchRequestViewModel()
            {
                PageNumber = 2,
            };

            // Act
            CalculationSearchResultViewModel results = await calculationSearchService.PerformSearch(request);

            // Assert
            results.StartItemNumber.Should().Be(51);
            results.EndItemNumber.Should().Be(75);
        }
        private string GetConnectionStringFromConfig(IFeatureToggle toggle)
        {
            var prefixedToggleConfigName           = ToggleConfigurationSettings.Prefix + toggle.GetType().Name;
            var appSettingsConnectionStringKey     = prefixedToggleConfigName + ".ConnectionString";
            var appSettingsConnectionStringNameKey = prefixedToggleConfigName + ".ConnectionStringName";

            var isConfiguredViaAppSettingsConnectionString     = ConfigurationManager.AppSettings.AllKeys.Contains(appSettingsConnectionStringKey);
            var isConfiguredViaAppSettingsConnectionStringName = ConfigurationManager.AppSettings.AllKeys.Contains(appSettingsConnectionStringNameKey);
            var isConfiguredViaConnectionStrings = ConfigurationManager.ConnectionStrings[prefixedToggleConfigName] != null;

            ValidateConnectionStringSpecifiedOnlyOnce(isConfiguredViaAppSettingsConnectionString, isConfiguredViaAppSettingsConnectionStringName, isConfiguredViaConnectionStrings, prefixedToggleConfigName);
            ValidateConnectionStringNotMissing(isConfiguredViaAppSettingsConnectionString, isConfiguredViaAppSettingsConnectionStringName, isConfiguredViaConnectionStrings, appSettingsConnectionStringKey, appSettingsConnectionStringNameKey, prefixedToggleConfigName);


            if (isConfiguredViaAppSettingsConnectionString)
            {
                return(GetAppSettingsConnectionString(appSettingsConnectionStringKey));
            }

            if (isConfiguredViaAppSettingsConnectionStringName)
            {
                return(GetConnectionStringFromAppSettingsValueThatPointsToNamedConnectionString(appSettingsConnectionStringNameKey));
            }

            return(GetConnectionStringDirectlyFromNamedConnectionStrings(prefixedToggleConfigName));
        }
        private string GetConnectionStringFromConfig(IFeatureToggle toggle)
        {
            var prefixedToggleConfigName = ToggleConfigurationSettings.Prefix + toggle.GetType().Name;
            var appSettingsConnectionStringKey = prefixedToggleConfigName + ".ConnectionString";
            var appSettingsConnectionStringNameKey = prefixedToggleConfigName + ".ConnectionStringName";

            var isConfiguredViaAppSettingsConnectionString = ConfigurationManager.AppSettings.AllKeys.Contains(appSettingsConnectionStringKey);
            var isConfiguredViaAppSettingsConnectionStringName = ConfigurationManager.AppSettings.AllKeys.Contains(appSettingsConnectionStringNameKey);
            var isConfiguredViaConnectionStrings = ConfigurationManager.ConnectionStrings[prefixedToggleConfigName] != null;

            ValidateConnectionStringSpecifiedOnlyOnce(isConfiguredViaAppSettingsConnectionString, isConfiguredViaAppSettingsConnectionStringName, isConfiguredViaConnectionStrings, prefixedToggleConfigName);
            ValidateConnectionStringNotMissing(isConfiguredViaAppSettingsConnectionString, isConfiguredViaAppSettingsConnectionStringName, isConfiguredViaConnectionStrings, appSettingsConnectionStringKey, appSettingsConnectionStringNameKey, prefixedToggleConfigName);


            if (isConfiguredViaAppSettingsConnectionString)
            {
                return GetAppSettingsConnectionString(appSettingsConnectionStringKey);
            }
            
            if (isConfiguredViaAppSettingsConnectionStringName)
            {
                return GetConnectionStringFromAppSettingsValueThatPointsToNamedConnectionString(appSettingsConnectionStringNameKey);
            }

            return GetConnectionStringDirectlyFromNamedConnectionStrings(prefixedToggleConfigName);
        }
Esempio n. 6
0
 private static CalculationService CreateCalculationService(
     ICalculationsRepository calculationsRepository = null,
     ILogger logger = null,
     ISearchRepository <CalculationIndex> searchRepository = null,
     IValidator <Calculation> calcValidator           = null,
     IBuildProjectsService buildProjectsService       = null,
     ISpecificationRepository specificationRepository = null,
     ICacheProvider cacheProvider = null,
     ICalcsResiliencePolicies resiliencePolicies = null,
     IVersionRepository <CalculationVersion> calculationVersionRepository = null,
     IJobsApiClient jobsApiClient                     = null,
     ISourceCodeService sourceCodeService             = null,
     IFeatureToggle featureToggle                     = null,
     IBuildProjectsRepository buildProjectsRepository = null,
     ICalculationCodeReferenceUpdate calculationCodeReferenceUpdate = null)
 {
     return(new CalculationService
                (calculationsRepository ?? CreateCalculationsRepository(),
                logger ?? CreateLogger(),
                searchRepository ?? CreateSearchRepository(),
                calcValidator ?? CreateCalculationValidator(),
                buildProjectsService ?? CreateBuildProjectsService(),
                specificationRepository ?? CreateSpecificationRepository(),
                cacheProvider ?? CreateCacheProvider(),
                resiliencePolicies ?? CalcsResilienceTestHelper.GenerateTestPolicies(),
                calculationVersionRepository ?? CreateCalculationVersionRepository(),
                jobsApiClient ?? CreateJobsApiClient(),
                sourceCodeService ?? CreateSourceCodeService(),
                featureToggle ?? CreateFeatureToggle(),
                buildProjectsRepository ?? CreateBuildProjectsRepository(),
                calculationCodeReferenceUpdate ?? CreateCalculationCodeReferenceUpdate()));
 }
Esempio n. 7
0
 public AllocationModelDebugRunner(ILogger logger, IFeatureToggle featureToggles, IProviderSourceDatasetsRepository providerSourceDatasetsRepository, IProviderService providerService)
 {
     _logger         = logger;
     _featureToggles = featureToggles;
     _providerSourceDatasetsRepository = providerSourceDatasetsRepository;
     _providerService = providerService;
 }
        public ChoosePageModel(
            ISpecsApiClient specsApiClient,
            ICalculationsApiClient calcsClient,
            IResultsApiClient resultsClient,
            ITestEngineApiClient testEngineClient,
            IMapper mapper,
            IAuthorizationHelper authorizationHelper,
            IFeatureToggle featureToggle)
        {
            Guard.ArgumentNotNull(specsApiClient, nameof(specsApiClient));
            Guard.ArgumentNotNull(calcsClient, nameof(calcsClient));
            Guard.ArgumentNotNull(resultsClient, nameof(resultsClient));
            Guard.ArgumentNotNull(testEngineClient, nameof(testEngineClient));
            Guard.ArgumentNotNull(mapper, nameof(mapper));
            Guard.ArgumentNotNull(authorizationHelper, nameof(authorizationHelper));
            Guard.ArgumentNotNull(featureToggle, nameof(featureToggle));

            _specsClient         = specsApiClient;
            _calcsClient         = calcsClient;
            _resultsClient       = resultsClient;
            _testEngineClient    = testEngineClient;
            _mapper              = mapper;
            _authorizationHelper = authorizationHelper;
            _featureToggle       = featureToggle;
        }
        public async Task PerformSearch_StartAndEndItemsNumbersDisplayedCorrectlyOnSecondPageOfItemsWithMorePagesAvailable()
        {
            // Arrange
            ISpecsApiClient specsClient   = Substitute.For <ISpecsApiClient>();
            ILogger         logger        = Substitute.For <ILogger>();
            IMapper         mapper        = MappingHelper.CreateFrontEndMapper();
            IFeatureToggle  featureToggle = CreateFeatureToggle();

            ISpecificationSearchService SpecificationSearchService = new SpecificationSearchService(specsClient, mapper, logger, featureToggle);

            int numberOfItems = 50;

            PagedResult <SpecificationSearchResultItem> itemResult = GeneratePagedResult(numberOfItems);

            itemResult.PageNumber = 2;
            itemResult.PageSize   = 50;
            itemResult.TotalItems = 175;

            specsClient
            .FindSpecifications(Arg.Any <SearchFilterRequest>())
            .Returns(itemResult);

            SearchRequestViewModel request = new SearchRequestViewModel()
            {
                PageNumber = 2,
            };

            // Act
            SpecificationSearchResultViewModel results = await SpecificationSearchService.PerformSearch(request);

            // Assert
            results.StartItemNumber.Should().Be(51);
            results.EndItemNumber.Should().Be(100);
        }
        public CalculationProviderResultsPageModel(
            ICalculationProviderResultsSearchService resultsSearchService,
            ICalculationsApiClient calculationsApiClient,
            ISpecsApiClient specsApiClient,
            IMapper mapper,
            IDatasetsApiClient datasetsClient,
            ILogger logger,
            IJobsApiClient jobsApiClient,
            IFeatureToggle featureToggle)
        {
            Guard.ArgumentNotNull(resultsSearchService, nameof(resultsSearchService));
            Guard.ArgumentNotNull(calculationsApiClient, nameof(calculationsApiClient));
            Guard.ArgumentNotNull(specsApiClient, nameof(specsApiClient));
            Guard.ArgumentNotNull(mapper, nameof(mapper));
            Guard.ArgumentNotNull(datasetsClient, nameof(datasetsClient));
            Guard.ArgumentNotNull(logger, nameof(logger));
            Guard.ArgumentNotNull(jobsApiClient, nameof(jobsApiClient));
            Guard.ArgumentNotNull(featureToggle, nameof(featureToggle));

            _mapper = mapper;
            _resultsSearchService  = resultsSearchService;
            _calculationsApiClient = calculationsApiClient;
            _specsClient           = specsApiClient;
            _datasetsClient        = datasetsClient;
            _jobsClient            = jobsApiClient;
            _logger = logger;
            ShowExceptionCountAndFacet = featureToggle.IsExceptionMessagesEnabled();
        }
 static void WriteFeatureToggleBegin(this HtmlHelper helper, IFeatureToggle toggle)
 {
     if (!toggle.FeatureEnabled)
     {
         helper.ViewContext.Writer.Write("<span style=\"display:none\">");
     }
 }
 static void WriteFeatureToggleEnd(this HtmlHelper helper, IFeatureToggle toggle)
 {
     if (!toggle.FeatureEnabled)
     {
         helper.ViewContext.Writer.Write("</span>");
     }
 }
 public static IDisposable FeatureToggle(this HtmlHelper helper, IFeatureToggle toggle)
 {
     return(new DisposableHelper(
                () => helper.WriteFeatureToggleBegin(toggle),
                () => helper.WriteFeatureToggleEnd(toggle)
                ));
 }
        public IEnumerable<DayOfWeek> GetDaysOfWeek(IFeatureToggle toggle)
        {
            var toggleNameInConfig = CalculateToggleNameAsItShouldAppearInConfig(toggle);

            AssertThatToggleHasConfiguredValue(toggleNameInConfig);

            var trimmedConfigDays = GetTrimmedDaysFromConfig(toggleNameInConfig);

            foreach (var configValue in trimmedConfigDays)
            {
                DayOfWeek day;

                var isValidDay = DayOfWeek.TryParse(configValue, true, out day);

                if (isValidDay)
                {
                    yield return day;
                }
                else
                {
                    throw new ToggleConfigurationError(
                        string.Format(
                            "The value '{0}' in config key '{1}' is not a valid day of the week. Days should be specified in long format. E.g. Friday and not Fri.",
                            configValue, toggleNameInConfig));
                }
            }
        }
        public ProviderCalculationResultsReIndexerService(
            ILogger logger,
            ISearchRepository <ProviderCalculationResultsIndex> providerCalculationResultsSearchRepository,
            ISpecificationsApiClient specificationsApiClient,
            ICalculationResultsRepository resultsRepository,
            IResultsResiliencePolicies resiliencePolicies,
            IFeatureToggle featureToggle,
            IMessengerService messengerService)
        {
            Guard.ArgumentNotNull(logger, nameof(logger));
            Guard.ArgumentNotNull(providerCalculationResultsSearchRepository, nameof(providerCalculationResultsSearchRepository));
            Guard.ArgumentNotNull(specificationsApiClient, nameof(specificationsApiClient));
            Guard.ArgumentNotNull(resultsRepository, nameof(resultsRepository));
            Guard.ArgumentNotNull(resiliencePolicies?.ResultsRepository, nameof(resiliencePolicies.ResultsRepository));
            Guard.ArgumentNotNull(resiliencePolicies?.SpecificationsApiClient, nameof(resiliencePolicies.SpecificationsApiClient));
            Guard.ArgumentNotNull(resiliencePolicies?.ResultsSearchRepository, nameof(resiliencePolicies.ResultsSearchRepository));
            Guard.ArgumentNotNull(featureToggle, nameof(featureToggle));
            Guard.ArgumentNotNull(messengerService, nameof(messengerService));

            _logger = logger;
            _providerCalculationResultsSearchRepository = providerCalculationResultsSearchRepository;
            _specificationsApiClient       = specificationsApiClient;
            _resultsRepository             = resultsRepository;
            _resultsRepositoryPolicy       = resiliencePolicies.ResultsRepository;
            _specificationsApiClientPolicy = resiliencePolicies.SpecificationsApiClient;
            _resultsSearchRepositoryPolicy = resiliencePolicies.ResultsSearchRepository;
            _featureToggle    = featureToggle;
            _messengerService = messengerService;
        }
Esempio n. 16
0
        public void Execute_GivenAssembly_EnsureDatasetHasValueSet()
        {
            //Arrange
            ILogger logger = CreateLogger();

            IFeatureToggle featureToggle = CreateFeatureToggle();

            Assembly assembly = CreateAssembly("CalculateFunding.Services.Calculator.Resources.Implementation-test-datasets-hasvalue.dll");

            AllocationModel allocationModel = new AllocationFactory(logger, featureToggle).CreateAllocationModel(assembly) as AllocationModel;

            IEnumerable <ProviderSourceDataset> sourceDatasets = CreateProviderSourceDatasetsWithHasValue();

            ProviderSummary providerSummary = CreateProviderSummary();

            //Act
            IEnumerable <CalculationResult> calcResults = allocationModel.Execute(sourceDatasets.ToList(), providerSummary);

            //Assert
            calcResults.Any().Should().BeTrue();

            dynamic instance = allocationModel.Instance as dynamic;

            Assert.IsNotNull(instance.Datasets);
            Assert.IsTrue(instance.Datasets.Providers.HasValue);
        }
Esempio n. 17
0
        public async Task GetPublishedProviderProfileForProviderIdAndSpecificationIdAndFundingStreamId_CallsCorrectly(
            string providerId,
            string specificationId,
            string fundingStreamId)
        {
            IResultsService       resultsService       = Substitute.For <IResultsService>();
            IResultsSearchService resultsSearchService = Substitute.For <IResultsSearchService>();
            ICalculationProviderResultsSearchService calculationProviderResultsSearchService = Substitute.For <ICalculationProviderResultsSearchService>();
            IPublishedResultsService publishedResultsService = Substitute.For <IPublishedResultsService>();
            IProviderCalculationResultsSearchService providerCalculationsResultsSearchService = Substitute.For <IProviderCalculationResultsSearchService>();
            IFeatureToggle featureToggle = Substitute.For <IFeatureToggle>();
            IProviderCalculationResultsReIndexerService providerCalculationResultsReIndexerService = Substitute.For <IProviderCalculationResultsReIndexerService>();

            ResultsController controller = new ResultsController(
                resultsService,
                resultsSearchService,
                calculationProviderResultsSearchService,
                publishedResultsService,
                providerCalculationsResultsSearchService,
                featureToggle,
                providerCalculationResultsReIndexerService);

            await controller.GetPublishedProviderProfileForProviderIdAndSpecificationIdAndFundingStreamId(providerId, specificationId, fundingStreamId);

            await publishedResultsService
            .Received(1)
            .GetPublishedProviderProfileForProviderIdAndSpecificationIdAndFundingStreamId(providerId, specificationId, fundingStreamId);

            //Moq has a .VerifyNoOtherCalls method which would be really useful here to confirm the others weren't called.
        }
Esempio n. 18
0
        public Tuple <DateTime, DateTime> EvaluateTimePeriod(IFeatureToggle toggle)
        {
            var toggleNameInConfig = AppSettingsKeys.Prefix + "." + toggle.GetType().Name;

            if (!ConfigurationManager.AppSettings.AllKeys.Contains(toggleNameInConfig))
            {
                throw new ConfigurationErrorsException(string.Format("The key '{0}' was not found in AppSettings",
                                                                     toggleNameInConfig));
            }


            DateTime startDate;
            DateTime endDate;

            try
            {
                var configValues = ConfigurationManager.AppSettings[toggleNameInConfig].Split(new[] { '|' });


                startDate = DateTime.ParseExact(configValues[0].Trim(), ExpectedDateFormat, CultureInfo.InvariantCulture);
                endDate   = DateTime.ParseExact(configValues[1].Trim(), ExpectedDateFormat, CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException(string.Format("Configuration for {0} is invalid - date range should be specified like: '02/01/2050 04:05:08 | 07/08/2099 06:05:04'", toggleNameInConfig), ex);
            }

            if (startDate >= endDate)
            {
                throw new ConfigurationErrorsException(string.Format("Configuration for {0} is invalid - the start date must be less then the end date", toggleNameInConfig));
            }

            return(new Tuple <DateTime, DateTime>(startDate, endDate));
        }
        public Tuple<DateTime, DateTime> EvaluateTimePeriod(IFeatureToggle toggle)
        {
            var toggleNameInConfig = AppSettingsKeys.Prefix + "." + toggle.GetType().Name;

            if (!ConfigurationManager.AppSettings.AllKeys.Contains(toggleNameInConfig))
                throw new ConfigurationErrorsException(string.Format("The key '{0}' was not found in AppSettings",
                                                                     toggleNameInConfig));

            DateTime startDate;
            DateTime endDate;

            try
            {
                var configValues = ConfigurationManager.AppSettings[toggleNameInConfig].Split(new[] { '|' });

                startDate = DateTime.ParseExact(configValues[0].Trim(), ExpectedDateFormat, CultureInfo.InvariantCulture);
                endDate = DateTime.ParseExact(configValues[1].Trim(), ExpectedDateFormat, CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException(string.Format("Configuration for {0} is invalid - date range should be specified like: '02/01/2050 04:05:08 | 07/08/2099 06:05:04'", toggleNameInConfig), ex);
            }

            if (startDate >= endDate)
                throw new ConfigurationErrorsException(string.Format("Configuration for {0} is invalid - the start date must be less then the end date",toggleNameInConfig));

            return new Tuple<DateTime, DateTime>(startDate, endDate);
        }
Esempio n. 20
0
        private TValue EvaluateToggleValue <TDocument, TValue>(IFeatureToggle toggle, Func <TDocument, TValue> valueSelector, Func <string, TDocument> documentCreator) where TDocument : FeatureToggleDocument
        {
            var client = GetDocumentClient();

            var toggleName = toggle.GetType().Name;

            TValue toggleValue;

            try
            {
                // Fetch feature toggle
                var response = client.ReadDocumentAsync <TDocument>(
                    UriFactory.CreateDocumentUri(Configuration.DatabaseId, Configuration.CollectionId, toggleName)).Result;

                var document = response.Document;

                toggleValue = valueSelector(document);
            }
            catch (AggregateException ae) when(ae.InnerExceptions.First() is DocumentClientException ex && ex.StatusCode == HttpStatusCode.NotFound)
            {
                Trace.TraceWarning($"Feature toggle '{toggleName}' not found.");

                var newDocument = HandleMissingToggle(toggleName, () => documentCreator(toggleName), client);

                toggleValue = valueSelector(newDocument);
            }

            return(toggleValue);
        }
        public async Task WhenUserIsNotKnown_ShouldNotSucceed()
        {
            // Arrange
            ClaimsPrincipal principal        = new ClaimsPrincipal(new ClaimsIdentity());
            List <string>   fundingStreamIds = new List <string> {
                WellKnownFundingStreamId
            };
            AuthorizationHandlerContext authContext = CreateAuthenticationContext(principal, fundingStreamIds);

            IUsersApiClient usersApiClient = Substitute.For <IUsersApiClient>();

            IOptions <PermissionOptions> options = Substitute.For <IOptions <PermissionOptions> >();

            options.Value.Returns(actualOptions);

            IFeatureToggle features = CreateFeatureToggle(true);

            FundingStreamPermissionHandler authHandler = new FundingStreamPermissionHandler(usersApiClient, options, features);

            // Act
            await authHandler.HandleAsync(authContext);

            // Assert
            authContext.HasSucceeded.Should().BeFalse();
        }
        public async Task WhenRoleBasedFeatureIsNotEnabled_AndUserIsNotKnownToTheSystem_ShouldSucceed()
        {
            // Arrange
            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(Constants.ObjectIdentifierClaimType, Guid.NewGuid().ToString()) }));
            ISpecificationAuthorizationEntity specification = Substitute.For <ISpecificationAuthorizationEntity>();
            AuthorizationHandlerContext       authContext   = CreateAuthenticationContext(principal, SpecificationActionTypes.CanApproveFunding, specification);

            IUsersApiClient usersApiClient = Substitute.For <IUsersApiClient>();

            IOptions <PermissionOptions> options = Substitute.For <IOptions <PermissionOptions> >();

            options.Value.Returns(actualOptions);

            IFeatureToggle features = Substitute.For <IFeatureToggle>();

            features.IsRoleBasedAccessEnabled().Returns(false);

            SpecificationPermissionHandler authHandler = new SpecificationPermissionHandler(usersApiClient, options, features);

            // Act
            await authHandler.HandleAsync(authContext);

            // Assert
            authContext.HasSucceeded.Should().BeTrue();
        }
        private static IFeatureToggle CreateFeatureToggle(bool roleBasedAccessEnabled)
        {
            IFeatureToggle features = Substitute.For <IFeatureToggle>();

            features.IsRoleBasedAccessEnabled().Returns(roleBasedAccessEnabled);
            return(features);
        }
        public async Task WhenUserIsNotKnown_ShouldNotSucceed()
        {
            // Arrange
            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity());
            ISpecificationAuthorizationEntity specification = Substitute.For <ISpecificationAuthorizationEntity>();
            AuthorizationHandlerContext       authContext   = CreateAuthenticationContext(principal, SpecificationActionTypes.CanApproveFunding, specification);

            IUsersApiClient usersApiClient = Substitute.For <IUsersApiClient>();

            IOptions <PermissionOptions> options = Substitute.For <IOptions <PermissionOptions> >();

            options.Value.Returns(actualOptions);

            IFeatureToggle features = Substitute.For <IFeatureToggle>();

            features.IsRoleBasedAccessEnabled().Returns(true);

            SpecificationPermissionHandler authHandler = new SpecificationPermissionHandler(usersApiClient, options, features);

            // Act
            await authHandler.HandleAsync(authContext);

            // Assert
            authContext.HasSucceeded.Should().BeFalse();
        }
        private TValue EvaluateToggleValue <TEntity, TValue>(IFeatureToggle toggle, Func <TEntity, TValue> valueSelector, Func <string, string, TEntity> entityCreator) where TEntity : FeatureToggleEntity
        {
            var table = GetCloudTable();

            var componentName = Configuration.PartitionKeyResolver(toggle); // Defaults to assembly name of the feature toggle (used as partitionkey)
            var toggleName    = toggle.GetType().Name;

            // Fetch feature toggle
            var retrievedResult = table.ExecuteAsync(
                TableOperation.Retrieve <TEntity>(componentName, toggleName)).Result;

            TValue toggleValue;

            if (retrievedResult.Result is TEntity entity)
            {
                toggleValue = valueSelector(entity);
            }
            else
            {
                Trace.TraceWarning($"Feature toggle '{toggleName}' not found.");

                var newEntity = HandleMissingToggle(toggleName, () => entityCreator(componentName, toggleName), table);
                toggleValue = valueSelector(newEntity);
            }

            return(toggleValue);
        }
        public async Task PerformSearch_FirstSearchResultReturnedCorrectly()
        {
            // Arrange
            ISpecsApiClient specsClient   = Substitute.For <ISpecsApiClient>();
            ILogger         logger        = Substitute.For <ILogger>();
            IMapper         mapper        = MappingHelper.CreateFrontEndMapper();
            IFeatureToggle  featureToggle = CreateFeatureToggle();

            ISpecificationSearchService SpecificationSearchService = new SpecificationSearchService(specsClient, mapper, logger, featureToggle);

            int numberOfItems = 25;

            PagedResult <SpecificationSearchResultItem> itemResult = GeneratePagedResult(numberOfItems);

            specsClient
            .FindSpecifications(Arg.Any <SearchFilterRequest>())
            .Returns(itemResult);

            SearchRequestViewModel request = new SearchRequestViewModel();

            // Act
            SpecificationSearchResultViewModel results = await SpecificationSearchService.PerformSearch(request);

            // Assert
            SpecificationSearchResultItemViewModel first = results.Specifications.First();

            first.Should().NotBeNull();
            first.Id.Should().Be("10");
            first.Name.Should().Be("Specification 1");
            first.Status.Should().Be("Draft");
            first.FundingPeriodName.Should().Be("Test Period");
        }
Esempio n. 27
0
        public IEnumerable <DayOfWeek> GetDaysOfWeek(IFeatureToggle toggle)
        {
            var key = ExpectedAppSettingsKeyFor(toggle);

            ValidateKeyExists(key);

            var configValues = ConfigurationManager.AppSettings[key].Split(new[] { ',' }).Select(x => x.Trim());

            foreach (var configValue in configValues)
            {
                DayOfWeek day;

                var isValidDay = DayOfWeek.TryParse(configValue, true, out day);

                if (isValidDay)
                {
                    yield return(day);
                }
                else
                {
                    throw new ToggleConfigurationError(
                              string.Format(
                                  "The value '{0}' in config key '{1}' is not a valid day of the week. Days should be specified in long format. E.g. Friday and not Fri.",
                                  configValue, key));
                }
            }
        }
Esempio n. 28
0
        public bool EvaluateBooleanToggleValue(IFeatureToggle toggle)
        {
            var toggleName = toggle.GetType().Name;

            var connectionNameInConfig = ToggleConfigurationSettings.Prefix + toggleName;

            // To not create a new document store each time for performance reasons see https://github.com/jason-roberts/FeatureToggle/issues/64
            var documentStore = new DocumentStore
            {
                ConnectionStringName = connectionNameInConfig
            };

            documentStore.Initialize();

            using (var session = documentStore.OpenSession())
            {
                var t = session.Load <BooleanToggleSetting>(toggleName);

                if (t == null)
                {
                    throw new ToggleConfigurationError("No document was found for toggle " + toggleName);
                }

                return(t.Enabled);
            }
        }
        public Tuple<DateTime, DateTime> EvaluateTimePeriod(IFeatureToggle toggle)
        {
            var toggleNameInConfig = toggle.GetType().Name;

            if (!Application.Current.Resources.Contains(toggleNameInConfig))
                throw new Exception(string.Format("The key '{0}' was not found in Application.Current.Resources", toggleNameInConfig));

            DateTime startDate;
            DateTime endDate;

            try
            {
                var configValues = ((string) Application.Current.Resources[toggleNameInConfig]).Split(new[] { '|' });

                const string expectedDateFormat = @"dd/MM/yyyy HH:mm:ss";

                startDate = DateTime.ParseExact(configValues[0].Trim(), expectedDateFormat, CultureInfo.InvariantCulture);
                endDate = DateTime.ParseExact(configValues[1].Trim(), expectedDateFormat, CultureInfo.InvariantCulture);

            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Configuration for {0} is invalid - date range should be specified like: '02/01/2050 04:05:08 | 07/08/2099 06:05:04'", toggleNameInConfig), ex);
            }

            if (startDate >= endDate)
                throw new Exception(string.Format("Configuration for {0} is invalid - the start date must be less then the end date", toggleNameInConfig));

            return new Tuple<DateTime, DateTime>(startDate, endDate);
        }
        public async Task WhenRoleBasedFeatureIsNotEnabled_AndUserIsNotKnownToTheSystem_ShouldSucceed()
        {
            // Arrange
            ClaimsPrincipal principal        = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(Constants.ObjectIdentifierClaimType, Guid.NewGuid().ToString()) }));
            List <string>   fundingStreamIds = new List <string> {
                WellKnownFundingStreamId
            };
            AuthorizationHandlerContext authContext = CreateAuthenticationContext(principal, fundingStreamIds);

            IUsersApiClient usersApiClient = Substitute.For <IUsersApiClient>();

            IOptions <PermissionOptions> options = Substitute.For <IOptions <PermissionOptions> >();

            options.Value.Returns(actualOptions);

            IFeatureToggle features = CreateFeatureToggle(false);

            FundingStreamPermissionHandler authHandler = new FundingStreamPermissionHandler(usersApiClient, options, features);

            // Act
            await authHandler.HandleAsync(authContext);

            // Assert
            authContext.HasSucceeded.Should().BeTrue();
        }
        public async Task WhenUserIsKnown_AndHasNoPermissions_ShouldNotSucceed()
        {
            // Arrange
            string          userId           = Guid.NewGuid().ToString();
            ClaimsPrincipal principal        = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(Constants.ObjectIdentifierClaimType, userId) }));
            List <string>   fundingStreamIds = new List <string> {
                WellKnownFundingStreamId
            };
            AuthorizationHandlerContext authContext = CreateAuthenticationContext(principal, fundingStreamIds);

            IUsersApiClient usersApiClient = Substitute.For <IUsersApiClient>();

            usersApiClient.GetFundingStreamPermissionsForUser(Arg.Is(userId)).Returns(new ApiResponse <IEnumerable <FundingStreamPermission> >(HttpStatusCode.OK, Enumerable.Empty <FundingStreamPermission>()));

            IOptions <PermissionOptions> options = Substitute.For <IOptions <PermissionOptions> >();

            options.Value.Returns(actualOptions);

            IFeatureToggle features = CreateFeatureToggle(true);

            FundingStreamPermissionHandler authHandler = new FundingStreamPermissionHandler(usersApiClient, options, features);

            // Act
            await authHandler.HandleAsync(authContext);

            // Assert
            authContext.HasSucceeded.Should().BeFalse();
        }
Esempio n. 32
0
        public IEnumerable <DayOfWeek> GetDaysOfWeek(IFeatureToggle toggle)
        {
            var toggleNameInConfig = CalculateToggleNameAsItShouldAppearInConfig(toggle);

            AssertThatToggleHasConfiguredValue(toggleNameInConfig);


            var trimmedConfigDays = GetTrimmedDaysFromConfig(toggleNameInConfig);

            foreach (var configValue in trimmedConfigDays)
            {
                DayOfWeek day;

                var isValidDay = DayOfWeek.TryParse(configValue, true, out day);

                if (isValidDay)
                {
                    yield return(day);
                }
                else
                {
                    throw new ToggleConfigurationError(
                              string.Format(
                                  "The value '{0}' in config key '{1}' is not a valid day of the week. Days should be specified in long format. E.g. Friday and not Fri.",
                                  configValue, toggleNameInConfig));
                }
            }
        }
        public bool EvaluateBooleanToggleValue(IFeatureToggle toggle)
        {                        
            var toggleName = toggle.GetType().Name;

            var connectionNameInConfig = ToggleConfigurationSettings.Prefix + toggleName;

            // TODO: need to consider not creating a new document store each time for performance reasons
            var documentStore = new DocumentStore
            {
                ConnectionStringName = connectionNameInConfig
            };

            documentStore.Initialize();

            using (var session = documentStore.OpenSession())
            {
                var t = session.Load<BooleanToggleSetting>(toggleName);

                if (t == null)
                {
                    throw new ToggleConfigurationError("No document was found for toggle " + toggleName);
                }

                return t.Enabled;
            }
        }
Esempio n. 34
0
        public ProviderResultsRepository(
            ICosmosRepository cosmosRepository,
            ISearchRepository <CalculationProviderResultsIndex> searchRepository,
            ISpecificationsRepository specificationsRepository,
            ILogger logger,
            ISearchRepository <ProviderCalculationResultsIndex> providerCalculationResultsSearchRepository,
            IFeatureToggle featureToggle,
            EngineSettings engineSettings)
        {
            Guard.ArgumentNotNull(cosmosRepository, nameof(cosmosRepository));
            Guard.ArgumentNotNull(searchRepository, nameof(searchRepository));
            Guard.ArgumentNotNull(specificationsRepository, nameof(specificationsRepository));
            Guard.ArgumentNotNull(logger, nameof(logger));
            Guard.ArgumentNotNull(providerCalculationResultsSearchRepository, nameof(providerCalculationResultsSearchRepository));
            Guard.ArgumentNotNull(featureToggle, nameof(featureToggle));
            Guard.ArgumentNotNull(engineSettings, nameof(engineSettings));

            _cosmosRepository         = cosmosRepository;
            _searchRepository         = searchRepository;
            _specificationsRepository = specificationsRepository;
            _logger = logger;
            _providerCalculationResultsSearchRepository = providerCalculationResultsSearchRepository;
            _featureToggle  = featureToggle;
            _engineSettings = engineSettings;
        }
        public async Task WhenUserIsAdmin_ShouldSucceed()
        {
            // Arrange
            List <Claim> claims = new List <Claim>
            {
                new Claim(Constants.ObjectIdentifierClaimType, Guid.NewGuid().ToString()),
                new Claim(Constants.GroupsClaimType, actualOptions.AdminGroupId.ToString())
            };
            ClaimsPrincipal principal        = new ClaimsPrincipal(new ClaimsIdentity(claims));
            List <string>   fundingStreamIds = new List <string> {
                WellKnownFundingStreamId
            };
            AuthorizationHandlerContext authContext = CreateAuthenticationContext(principal, fundingStreamIds);

            IUsersApiClient usersApiClient = Substitute.For <IUsersApiClient>();

            IOptions <PermissionOptions> options = Substitute.For <IOptions <PermissionOptions> >();

            options.Value.Returns(actualOptions);

            IFeatureToggle features = CreateFeatureToggle(true);

            FundingStreamPermissionHandler authHandler = new FundingStreamPermissionHandler(usersApiClient, options, features);

            // Act
            await authHandler.HandleAsync(authContext);

            // Assert
            authContext.HasSucceeded.Should().BeTrue();
        }
        public void GetFeatureTogglesReturnsFeatureToggles(IFeatureToggle[] featureToggles)
        {
            var sut = new FeatureToggleProvider(featureToggles);

            IEnumerable<IFeatureToggle> result = sut.GetFeatureToggles();

            Assert.Same(featureToggles, result);
        }
        private string GetCommandTextFromAppConfig(IFeatureToggle toggle)
        {
            var toggleNameInConfig = ToggleConfigurationSettings.Prefix + toggle.GetType().Name + ".SqlStatement";

            if (!ConfigurationManager.AppSettings.AllKeys.Contains(toggleNameInConfig))
                throw new ToggleConfigurationError(string.Format("The key '{0}' was not found in AppSettings",
                                                                     toggleNameInConfig));

            return ConfigurationManager.AppSettings[toggleNameInConfig];
        }
        private string GetConnectionStringFromConfig(IFeatureToggle toggle)
        {
            var toggleNameInConfig = AppSettingsKeys.Prefix + "." + toggle.GetType().Name + ".ConnectionString";

            if (!ConfigurationManager.AppSettings.AllKeys.Contains(toggleNameInConfig))
                throw new ConfigurationErrorsException(string.Format("The key '{0}' was not found in AppSettings",
                                                                     toggleNameInConfig));

            return ConfigurationManager.AppSettings[toggleNameInConfig];
        }
        public bool EvaluateBooleanToggleValue(IFeatureToggle toggle)
        {
            var toggleNameInConfig = CalculateToggleNameAsItShouldAppearInConfig(toggle);

            AssertThatToggleHasConfiguredValue(toggleNameInConfig);

            bool toggleValue = bool.Parse(Application.Current.Resources[toggleNameInConfig].ToString());

            return toggleValue;
        }
        public DateTime EvaluateDateTimeToggleValue(IFeatureToggle toggle)
        {
            var toggleNameInConfig = CalculateToggleNameAsItShouldAppearInConfig(toggle);

            AssertThatToggleHasConfiguredValue(toggleNameInConfig);

            var parser = new ConfigurationDateParser();

            return parser.ParseDateTimeConfigString((string) Application.Current.Resources[toggleNameInConfig],
                toggleNameInConfig);
        }
        public DateTime EvaluateDateTimeToggleValue(IFeatureToggle toggle)
        {
            var toggleNameInConfig = toggle.GetType().Name;

            if (!Application.Current.Resources.Contains(toggleNameInConfig))
                throw new Exception(string.Format("The key '{0}' was not found in Application.Current.Resources", toggleNameInConfig));

            DateTime toggleValue = (DateTime)Application.Current.Resources[toggleNameInConfig];

            return toggleValue;
        }
        public DateTime EvaluateDateTimeToggleValue(IFeatureToggle toggle)
        {
            var toggleNameInConfig = AppSettingsKeys.Prefix + "." + toggle.GetType().Name;

            if (!ConfigurationManager.AppSettings.AllKeys.Contains(toggleNameInConfig))
                throw new ConfigurationErrorsException(string.Format("The key '{0}' was not found in AppSettings",
                                                                     toggleNameInConfig));

            var configValue = ConfigurationManager.AppSettings[toggleNameInConfig];

            return ParseDateTimeConfigString(configValue, toggleNameInConfig);
        }
Esempio n. 43
0
        public DateTime EvaluateDateTimeToggleValue(IFeatureToggle toggle)
        {
            var key = ExpectedAppSettingsKeyFor(toggle);

            ValidateKeyExists(key);

            var configValue = ConfigurationManager.AppSettings[key];

            var parser = new ConfigurationDateParser();

            return parser.ParseDateTimeConfigString(configValue, key);
        }
Esempio n. 44
0
        /// <summary>
        /// Adds the specified feature toggle.
        /// </summary>
        /// <param name="toggle">The toggle to add to this configuration.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="toggle"></paramref> is <c>null</c>.</exception>
        public void Add(IFeatureToggle toggle)
        {
            if (toggle == null)
            {
                throw new ArgumentNullException("toggle");
            }

            toggle.AssertConfigurationIsValid();
            toggle.Freeze();

            features.AddOrUpdate(toggle.Name, toggle, (key, value) => toggle);
        }
Esempio n. 45
0
        public void IsEnabledCallsIsEnabledOnToggle([Frozen] IFeatureToggleProvider toggleProvider, IFeature feature,
            IFeatureToggle featureToggle, bool expected, FeatureContext sut)
        {
            A.CallTo(() => featureToggle.IsEnabled(feature))
                .Returns(expected);
            A.CallTo(() => toggleProvider.GetFeatureToggles())
                .Returns(new[] {featureToggle});

            bool result = sut.IsEnabled(feature);

            A.CallTo(() => featureToggle.IsEnabled(feature))
                .MustHaveHappened();
            Assert.Equal(expected, result);
        }
        public bool EvaluateBooleanToggleValue(IFeatureToggle toggle)
        {
            var connectionString = GetConnectionStringFromConfig(toggle);
            var sqlCommandText = GetCommandTextFromAppConfig(toggle);

            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommand(sqlCommandText, connection))
                {
                    return (bool)cmd.ExecuteScalar();
                }
            }
        }
        public bool EvaluateBooleanToggleValue(IFeatureToggle toggle)
        {
            var cmdText = GetCommandTextFromAppConfig(toggle);

            var cnString = GetConnectionStringFromConfig(toggle);

            using (var cn = new SqlConnection(cnString))
            {
                cn.Open();

                using (var cmd = new SqlCommand(cmdText, cn))
                {
                    return bool.Parse((string)cmd.ExecuteScalar());
                }
            }
        }
Esempio n. 48
0
        public void ApplyToggle()
        {
            ValidateProperties();
            Boolean reversed = string.IsNullOrWhiteSpace(EnabledBy);
            string featureName = reversed ? RemovedBy : EnabledBy;

            _featureToggle = _featureFactory.GetFeatureToggle(featureName, reversed);
            if (!_featureToggle.IsOn)
            {
                if (Controls.Count == 0)
                    throw new InvalidMarkupException(
                        "There are no controls to remove. Controls will not be present if you have inline script within your markup.  A possible workaround it to move script to code behind.");

                Controls.Clear();
            }
        }
        public FallbackValueDecorator(IFeatureToggle primaryToggle, IFeatureToggle fallbackToggle,
            Action<Exception> logAction = null)
        {
            if (primaryToggle == null)
            {
                throw new ArgumentNullException(nameof(primaryToggle));
            }

            if (fallbackToggle == null)
            {
                throw new ArgumentNullException(nameof(fallbackToggle));
            }

            PrimaryToggle = primaryToggle;
            FallbackToggle = fallbackToggle;
            _logAction = logAction;
        }
Esempio n. 50
0
        public bool EvaluateBooleanToggleValue(IFeatureToggle toggle)
        {
            var key = ExpectedAppSettingsKeyFor(toggle);

            ValidateKeyExists(key);

            var configValue = ConfigurationManager.AppSettings[key];

            // TODO: don't really like this, in v3 providers and toggles will be broken apart more
            if (toggle is HttpJsonFeatureToggle)
            {
                return GetJsonBoolFromServer(configValue);
            }
            else
            {
                return ParseConfigString(configValue, key);    
            }

            
        }
        private string GetCommandTextFromAppConfig(IFeatureToggle toggle)
        {
            var sqlCommandKey = ToggleConfigurationSettings.Prefix + toggle.GetType().Name + ".SqlStatement";

            var sqlCommandIsMissing = !ConfigurationManager.AppSettings.AllKeys.Contains(sqlCommandKey);

            if (sqlCommandIsMissing)
            {
                throw new ToggleConfigurationError(string.Format("The appSettings key '{0}' was not found.",
                    sqlCommandKey));
            }

            var configuredSqlCommand = ConfigurationManager.AppSettings[sqlCommandKey];

            if (string.IsNullOrWhiteSpace(configuredSqlCommand))
            {
                throw new ToggleConfigurationError(string.Format("The <appSettings> value for key '{0}' is empty.", sqlCommandKey));
            }

            return configuredSqlCommand;
        }
        public Tuple<DateTime, DateTime> EvaluateTimePeriod(IFeatureToggle toggle)
        {
            var toggleNameInConfig = CalculateToggleNameAsItShouldAppearInConfig(toggle);

            AssertThatToggleHasConfiguredValue(toggleNameInConfig);

            DateTime startDate;
            DateTime endDate;

            var configValues = ((string) Application.Current.Resources[toggleNameInConfig]).Split(new[] {'|'});

            var parser = new ConfigurationDateParser();

            startDate = parser.ParseDateTimeConfigString(configValues[0].Trim(), toggleNameInConfig);
            endDate = parser.ParseDateTimeConfigString(configValues[1].Trim(), toggleNameInConfig);

            var v = new ConfigurationValidator();

            v.ValidateStartAndEndDates(startDate, endDate, toggleNameInConfig);

            return new Tuple<DateTime, DateTime>(startDate, endDate);
        }
        public FixedTimeCacheDecorator(IFeatureToggle toggleToWrap, TimeSpan cacheDuration,
            Func<DateTime> alternativeNowProvider = null)
        {
            if (toggleToWrap == null)
            {
                throw new ArgumentNullException("toggleToWrap");
            }

            WrappedToggle = toggleToWrap;

            _cacheDuration = cacheDuration;

            if (alternativeNowProvider == null)
            {
                NowProvider = () => DateTime.Now;
            }
            else
            {
                NowProvider = alternativeNowProvider;
            }

            SetCachedValue();
        }
        public bool EvaluateBooleanToggleValue(IFeatureToggle toggle)
        {
            var toggleNameInConfig = toggle.GetType().Name;

            var localSettings = ApplicationData.Current.LocalSettings;

            if (! localSettings.Values.ContainsKey(toggleNameInConfig))
            {
                throw new ArgumentOutOfRangeException("toggle",
                    string.Format("No toggle value with the key '{0}' was found in local application settings. Ensure you set a boolean value into ApplicationData.Current.LocalSettings with a key that is the same as the name of your feature toggle class.", toggleNameInConfig));
            }

            try
            {
                return (bool) localSettings.Values[toggleNameInConfig];
            }
            catch (Exception ex)
            {
                throw new Exception(
                    string.Format("The value in local application settings for the feature toggle with the key '{0}' is incorrect, it should be a non-nullable boolean value.", toggleNameInConfig),
                    ex);
            }
        }
Esempio n. 55
0
        /// <summary>
        /// Adds the specified feature toggle as a dependency to this one.
        /// </summary>
        /// <param name="toggle">The toggle to add as a dependency.</param>
        public void AddDependency(IFeatureToggle toggle)
        {
            if (IsFrozen)
            {
                throw new ToggleFrozenException("Toggle is frozen and can not be modified.");
            }

            dependencies.Add(toggle);
        }
Esempio n. 56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DependencyToggle" /> class.
 /// </summary>
 /// <param name="innerToggle">The inner toggle for evaluation of this toggle.</param>
 public DependencyToggle(IFeatureToggle innerToggle)
     : this(innerToggle, new IFeatureToggle[0])
 {
 }
Esempio n. 57
0
 public bool IsEnabled(IFeatureToggle featureToggle)
 {
     return IsEnabled(featureToggle.Id);
 }
Esempio n. 58
0
        public IEnumerable<DayOfWeek> GetDaysOfWeek(IFeatureToggle toggle)
        {
            var key = ExpectedAppSettingsKeyFor(toggle);

            ValidateKeyExists(key);

            var configValues = ConfigurationManager.AppSettings[key].Split(new[] {','}).Select(x => x.Trim());

            foreach (var configValue in configValues)
            {
                DayOfWeek day;

                var isValidDay = DayOfWeek.TryParse(configValue, true, out day);

                if (isValidDay)
                {
                    yield return day;
                }
                else
                {
                    throw new ToggleConfigurationError(
                        string.Format(
                            "The value '{0}' in config key '{1}' is not a valid day of the week. Days should be specified in long format. E.g. Friday and not Fri.",
                            configValue, key));
                }
            }
        }
 /// <summary>
 /// Decorator constructor that allows the wrapping of another toggle
 /// </summary>
 /// <param name="toggle">The toggle to wrap (decorate)</param>
 /// <param name="logAction">Optional action that gets called if an exception is thrown by the wrapped toggle before returning enabled = false</param>
 public DefaultToDisabledOnErrorDecorator(IFeatureToggle toggle, Action<Exception> logAction = null)
 {            
     Toggle = toggle;
     _logAction = logAction;
 }
Esempio n. 60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DependencyToggle" /> class.
 /// </summary>
 /// <param name="innerToggle">The inner toggle for evaluation of this toggle.</param>
 /// <param name="dependencies">The feature toggles that this toggle depends on.</param>
 public DependencyToggle(IFeatureToggle innerToggle, params IFeatureToggle[] dependencies)
     : base(innerToggle.Name)
 {
     this.innerToggle = innerToggle;
     this.dependencies = new ConcurrentBag<IFeatureToggle>(dependencies);
 }