Ejemplo n.º 1
0
        /// <summary>
        /// Processes the tag helper context to evaluate if the feature's content should be rendered.
        /// </summary>
        /// <param name="context">The tag helper context.</param>
        /// <param name="output">The tag helper output.</param>
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = null; // We don't want the feature to actually be a part of HTML, so we strip it

            bool enabled = false;

            if (!string.IsNullOrEmpty(Name))
            {
                IEnumerable <string> names = Name.Split(',').Select(n => n.Trim());

                enabled = Requirement == RequirementType.All ?
                          names.All(n => _featureManager.IsEnabled(n)) :
                          names.Any(n => _featureManager.IsEnabled(n));
            }

            if (Negate)
            {
                enabled = !enabled;
            }

            if (!enabled)
            {
                output.SuppressOutput();
            }
        }
Ejemplo n.º 2
0
        // This method is used to generate the description in the swagger UI page, according to the available features
        public string GetSwaggerHomepage(IFeatureManager featureManager)
        {
            var description = new StringBuilder();

            if (featureManager.IsEnabled(Features.Metrics))
            {
                description.Append(HomeGenerator.BasicHtml());
            }
            description.Append("<p>This template provides loads of developer friendly features that makes dotnet core ready for microservices and containers scenarios.</p>");
            description.Append("<ul>");
            if (featureManager.IsEnabled(Features.HttpLogger))
            {
                description.Append("<li><a target='_blank' href='/log?level=all'>/log</a> monitor your beautiful logs from the comfort of your browser </li>");
            }
            if (featureManager.IsEnabled(Features.Healthz))
            {
                description.Append("<li><a target='_blank' href='/healthz'>/healthz</a> url to monitor your application health status </li>");
            }
            if (featureManager.IsEnabled(Features.HealthUI))
            {
                description.Append("<li><a target='_blank' href='/healthchecks-ui'>/healthchecks-ui</a> UI to monitor your application health status </li>");
            }
            description.Append("</ul>");

            return(description.ToString());
        }
 public IActionResult Index()
 {
     if (_featureManager.IsEnabled(nameof(ApplicationFeatureFlags.FeatureC)))
     {
         Debug.WriteLine("Debugging enabled, serving Index.");
     }
     return(View());
 }
        public IndexModel(IFeatureManager featureManager)
        {
            FeatureManager = featureManager;

            // only returns true during provided time window
            bool showBanner = FeatureManager.IsEnabled(FeatureManagement.ConstFeatureFlags.ChristmasBanner);

            bool showFancyFonts = FeatureManager.IsEnabled(FeatureManagement.ConstFeatureFlags.FancyFonts);
        }
Ejemplo n.º 5
0
        private static AgSpotsSerialization ToAgSpot(
            List <Spot> spots,
            List <SalesArea> salesAreas,
            IReadOnlyCollection <BreakWithProgramme> breaks,
            List <Campaign> campaigns,
            List <Demographic> demographics,
            List <BusinessType> businessTypes,
            List <Product> products,
            List <Clash> clashes,
            AgSpot agSpot,
            IFeatureManager featureManager)
        {
            var agSpots = new ConcurrentBag <AgSpot>();

            Dictionary <string, SalesArea> salesAreasByName               = SalesArea.IndexListByName(salesAreas);
            Dictionary <string, Campaign>  campaignsByExternalId          = Campaign.IndexListByExternalId(campaigns);
            Dictionary <string, bool>      businessTypesInclusionSettings = businessTypes
                                                                            .ToDictionary(bt => bt.Code, bt => bt.IncludeConversionIndex);
            Dictionary <string, BreakWithProgramme> breaksWithProgrammeBySalesAreaAndExternalBreakRef = BreakWithProgramme.IndexListBySalesAreaAndExternalBreakRef(breaks);
            IImmutableDictionary <string, Product>  productByExternalId = products.IndexListByExternalID();
            IImmutableDictionary <string, Clash>    clashByExternalRef  = clashes.IndexListByExternalRef();

            var clashRoots = ClashHelper.CalculateClashTopParents(clashByExternalRef);

            var threadSafeSpotsCollection = spots.ToImmutableList();
            var includeNominalPrice       = featureManager.IsEnabled(nameof(ProductFeature.NominalPrice));
            var includePositionInBreak    = featureManager.IsEnabled(nameof(ProductFeature.PositionInBreak));

            _ = Parallel.ForEach(threadSafeSpotsCollection, spot => agSpots.Add(
                                     GetAgSpot(
                                         spot,
                                         threadSafeSpotsCollection,
                                         salesAreasByName,
                                         campaignsByExternalId,
                                         businessTypesInclusionSettings,
                                         breaksWithProgrammeBySalesAreaAndExternalBreakRef,
                                         productByExternalId,
                                         clashByExternalRef,
                                         demographics,
                                         agSpot.Clone(),
                                         includeNominalPrice,
                                         includePositionInBreak,
                                         clashRoots
                                         )
                                     )
                                 );

            var serialization = new AgSpotsSerialization();

            return(serialization.MapFrom(agSpots.ToList()));
        }
        public ScenarioCampaignLevelResultsDataHandler(AWSSettings awsSettings, ICloudStorage cloudStorage,
                                                       IScenarioCampaignResultReportCreator campaignResultReportCreator, IFeatureManager featureManager,
                                                       IAuditEventRepository auditEventRepository, IMapper mapper, IFacilityRepository facilityRepository)
        {
            _campaignResultReportCreator = campaignResultReportCreator;
            _awsSettings          = awsSettings;
            _cloudStorage         = cloudStorage;
            _auditEventRepository = auditEventRepository;
            _mapper             = mapper;
            _facilityRepository = facilityRepository;

            _includeScenarioPerformanceMeasurementKpIs = featureManager.IsEnabled(nameof(ProductFeature.ScenarioPerformanceMeasurementKPIs));
            _saveData = featureManager.IsEnabled(nameof(ProductFeature.PrePostCampaignResults));
        }
Ejemplo n.º 7
0
        /// <summary>Initializes a new instance of the <see cref="CampaignSerializerBase" /> class.</summary>
        /// <param name="auditEventRepository">The audit event repository.</param>
        /// <param name="featureManager">The feature manager.</param>
        /// <param name="clock">The clock.</param>
        /// <param name="mapper">The mapper.</param>
        protected CampaignSerializerBase(
            IAuditEventRepository auditEventRepository,
            IFeatureManager featureManager,
            IClock clock,
            IMapper mapper) : base(auditEventRepository)
        {
            _clock  = clock;
            _mapper = mapper;

            _includeChannelGroup =
                featureManager.IsEnabled(ProductFeature.IncludeChannelGroupFileForOptimiser);
            _mergeUniqueDayParts  = featureManager.IsEnabled(ProductFeature.StrikeWeightDayPartsMerge);
            _includeCampaignPrice = featureManager.IsEnabled(ProductFeature.NominalPrice);
        }
        public void Percentage()
        {
            string feature1 = "feature1";

            Environment.SetEnvironmentVariable($"FeatureManagement:{feature1}:EnabledFor:0:Name", "Percentage");
            Environment.SetEnvironmentVariable($"FeatureManagement:{feature1}:EnabledFor:0:Parameters:Value", "50");

            IConfiguration config = new ConfigurationBuilder().AddEnvironmentVariables().Build();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(config)
            .AddFeatureManagement()
            .AddFeatureFilter <PercentageFilter>();

            ServiceProvider provider = serviceCollection.BuildServiceProvider();

            IFeatureManager featureManager = provider.GetRequiredService <IFeatureManager>();

            int enabledCount = 0;

            for (int i = 0; i < 10; i++)
            {
                if (featureManager.IsEnabled(feature1))
                {
                    enabledCount++;
                }
            }

            Assert.True(enabledCount > 0 && enabledCount < 10);
        }
Ejemplo n.º 9
0
        public async Task <ActionResult <IEnumerable <HighScore> > > Get(int limit = 0)
        {
            logger?.LogInformation("Retrieving score list with a limit of {SearchLimit}.", limit);

            var scores = context.Scores
                         .Select(score => new HighScore()
            {
                Game     = score.Game,
                Points   = score.Points,
                Nickname = score.Gamer.Nickname
            });

            if (featureManager.IsEnabled(nameof(ApiFeatureFlags.LeaderboardListLimit)))
            {
                int searchLimit = limit;

                // This is a demo bug, supposedly "hard" to find
                do
                {
                    searchLimit--;
                }while (searchLimit != 0);

                scores = scores.Take(limit);
            }

            return(Ok(await scores.ToListAsync().ConfigureAwait(false)));
        }
Ejemplo n.º 10
0
        public Facade(IAuthenticationSchemeRetriever authenticationSchemeRetriever, IAuthorizationResolver authorizationResolver, IClientStore clientStore, IDecorationLoader decorationLoader, IEventService events, IOptionsMonitor <ExceptionHandlingOptions> exceptionHandling, IFeatureManager featureManager, IHttpContextAccessor httpContextAccessor, IIdentityFacade identity, IOptionsMonitor <ExtendedIdentityServerOptions> identityServer, IIdentityServerInteractionService interaction, IStringLocalizerFactory localizerFactory, ILoggerFactory loggerFactory, IOptionsMonitor <RequestLocalizationOptions> requestLocalization, IServiceProvider serviceProvider)
        {
            this.AuthenticationSchemeRetriever = authenticationSchemeRetriever ?? throw new ArgumentNullException(nameof(authenticationSchemeRetriever));
            this.AuthorizationResolver         = authorizationResolver ?? throw new ArgumentNullException(nameof(authorizationResolver));
            this.ClientStore         = clientStore ?? throw new ArgumentNullException(nameof(clientStore));
            this.DecorationLoader    = decorationLoader ?? throw new ArgumentNullException(nameof(decorationLoader));
            this.Events              = events ?? throw new ArgumentNullException(nameof(events));
            this.ExceptionHandling   = exceptionHandling ?? throw new ArgumentNullException(nameof(exceptionHandling));
            this.FeatureManager      = featureManager ?? throw new ArgumentNullException(nameof(featureManager));
            this.HttpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
            this.Identity            = identity ?? throw new ArgumentNullException(nameof(identity));
            this.IdentityServer      = identityServer ?? throw new ArgumentNullException(nameof(identityServer));
            this.Interaction         = interaction ?? throw new ArgumentNullException(nameof(interaction));
            this.LocalizerFactory    = localizerFactory ?? throw new ArgumentNullException(nameof(localizerFactory));
            this.LoggerFactory       = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
            this.RequestLocalization = requestLocalization ?? throw new ArgumentNullException(nameof(requestLocalization));

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

            if (featureManager.IsEnabled(Feature.Saml))
            {
                this.SamlInteraction = serviceProvider.GetRequiredService <ISamlInteractionService>();
            }
        }
Ejemplo n.º 11
0
 public async Task OnGetAsync()
 {
     Scores = new List <HighScore>();
     try
     {
         //ILeaderboardClient proxy = RestService.For<ILeaderboardClient>(options.Value.BaseUrl);
         if (featureManager.IsEnabled(nameof(AppFeatureFlags.LeaderboardListLimit)))
         {
             int limit;
             Scores = await proxy.GetHighScores(Int32.TryParse(Request.Query["limit"], out limit)?limit : 5)
                      .ConfigureAwait(false);
         }
         else
         {
             Scores = await proxy.GetHighScores().ConfigureAwait(false);
         }
     }
     catch (HttpRequestException ex)
     {
         logger.LogWarning(ex, "Http request failed.");
     }
     catch (TimeoutRejectedException ex)
     {
         logger.LogWarning(ex, "Timeout occurred when retrieving high score list.");
     }
     catch (Exception ex)
     {
         logger.LogError(ex, "Unknown exception occurred while retrieving high score list");
         throw;
     }
 }
        public IndexModel(IFeatureManager featureManager)
        {
            FeatureManager = featureManager;

            // only returns true during provided time window
            bool showBanner = FeatureManager.IsEnabled(FeatureManagement.ConstFeatureFlags.ChristmasBanner);

            bool showFancyFonts = FeatureManager.IsEnabled(FeatureManagement.ConstFeatureFlags.FancyFonts);

            var isEnabled = FeatureManager.IsEnabled(FeatureManagement.ConstFeatureFlags.Beta);             // may throw!

            // Flags on the main FeatureFlags class are safe to use everywhere
            var isEnabled2 = FeatureManager.IsEnabled(FeatureManagement.ConstFeatureFlags.NewBranding);

            // Flags on the nested Ui class are only safe when HttpContext is available
            var isEnabled3 = FeatureManager.IsEnabled(FeatureManagement.ConstFeatureFlags.Ui.Beta);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Returns true if the specified <see cref="ProductFeature"/> value is enabled, otherwise false.
        /// </summary>
        public static bool IsEnabled(this IFeatureManager featureManager, ProductFeature feature)
        {
            if (featureManager is null)
            {
                throw new ArgumentNullException(nameof(featureManager));
            }

            return(featureManager.IsEnabled(feature.ToString()));
        }
Ejemplo n.º 14
0
        public IEnumerable <FeatureFlag> EnabledFeatures(string actionstepOrg)
        {
            // Required by org key feature flag filter
            HttpContext.SetCurrentOrgKey(actionstepOrg);

            return(Enum.GetValues(typeof(FeatureFlag))
                   .OfType <FeatureFlag>()
                   .Where(f => _featureManager.IsEnabled(f.ToString())));
        }
        public IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var isEnabled = _featureManager.IsEnabled("nonExistentFeature");

            return(new OkObjectResult($"nonExistentFetature enabled status: {isEnabled}"));
        }
Ejemplo n.º 16
0
        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            if (_featureManager.IsEnabled(nameof(MyFeatureFlags.CustomViewData)))
            {
                ViewData["Message"] = $"This is FANCY CONTENT you can see only if '{nameof(MyFeatureFlags.CustomViewData)}' is enabled.";
            }
            ;

            return(View());
        }
        public void ReadsConfiguration()
        {
            IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

            var services = new ServiceCollection();

            services
            .AddSingleton(config)
            .AddFeatureManagement()
            .AddFeatureFilter <TestFilter>();

            ServiceProvider serviceProvider = services.BuildServiceProvider();

            IFeatureManager featureManager = serviceProvider.GetRequiredService <IFeatureManager>();

            Assert.True(featureManager.IsEnabled(OnFeature));

            Assert.False(featureManager.IsEnabled(OffFeature));

            IEnumerable <IFeatureFilter> featureFilters = serviceProvider.GetRequiredService <IEnumerable <IFeatureFilter> >();

            TestFilter testFeatureFilter = (TestFilter)featureFilters.First(f => f is TestFilter);

            bool called = false;

            testFeatureFilter.Callback = (evaluationContext) =>
            {
                called = true;

                Assert.Equal("V1", evaluationContext.Parameters["P1"]);

                Assert.Equal(ConditionalFeature, evaluationContext.FeatureName);

                return(true);
            };

            featureManager.IsEnabled(ConditionalFeature);

            Assert.True(called);
        }
Ejemplo n.º 18
0
        public DataExporter(IConfigurationDbContext configurationDatabaseContext, IFeatureManager featureManager, IIdentityFacade identityFacade, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {
            this.ConfigurationDatabaseContext = configurationDatabaseContext ?? throw new ArgumentNullException(nameof(configurationDatabaseContext));
            this.FeatureManager = featureManager ?? throw new ArgumentNullException(nameof(featureManager));
            this.IdentityFacade = identityFacade ?? throw new ArgumentNullException(nameof(identityFacade));
            this.Logger         = (loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory))).CreateLogger(this.GetType());

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

            if (featureManager.IsEnabled(Feature.Saml))
            {
                this.SamlDatabaseContext = serviceProvider.GetRequiredService <ISamlConfigurationDbContext>();
            }

            if (featureManager.IsEnabled(Feature.WsFederation))
            {
                this.WsFederationDatabaseContext = serviceProvider.GetRequiredService <IWsFederationConfigurationDbContext>();
            }
        }
Ejemplo n.º 19
0
        public ScenarioCampaignFailuresDataHandler(AWSSettings awsSettings,
                                                   ICloudStorage cloudStorage,
                                                   IRepositoryFactory repositoryFactory,
                                                   IFeatureManager featureManager,
                                                   IAuditEventRepository auditEventRepository)
        {
            _awsSettings          = awsSettings;
            _cloudStorage         = cloudStorage;
            _repositoryFactory    = repositoryFactory;
            _auditEventRepository = auditEventRepository;

            _saveData = featureManager.IsEnabled(nameof(ProductFeature.PrePostCampaignResults));
        }
        public bool IsEnabled(string feature)
        {
            //
            // First, check local cache
            if (_flagCache.ContainsKey(feature))
            {
                return(_flagCache[feature]);
            }

            bool enabled = _featureManager.IsEnabled(feature);

            _flagCache[feature] = enabled;

            return(enabled);
        }
        public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
        {
            IFeatureManager featureManager = serviceProvider.GetRequiredService <IFeatureManagerSnapshot>();

            if (featureManager.IsEnabled(FeatureName))
            {
                return((IFilterMetadata)ActivatorUtilities.CreateInstance(serviceProvider, typeof(T)));
            }
            else
            {
                //
                // TODO check if null
                return(new DisabledFeatureFilter(FeatureName));
            }
        }
        public void TimeWindow()
        {
            string feature1 = "feature1";
            string feature2 = "feature2";
            string feature3 = "feature3";
            string feature4 = "feature4";

            Environment.SetEnvironmentVariable($"FeatureManagement:{feature1}:EnabledFor:0:Name", "TimeWindow");
            Environment.SetEnvironmentVariable($"FeatureManagement:{feature1}:EnabledFor:0:Parameters:End", DateTimeOffset.UtcNow.AddDays(1).ToString("r"));

            Environment.SetEnvironmentVariable($"FeatureManagement:{feature2}:EnabledFor:0:Name", "TimeWindow");
            Environment.SetEnvironmentVariable($"FeatureManagement:{feature2}:EnabledFor:0:Parameters:End", DateTimeOffset.UtcNow.ToString("r"));

            Environment.SetEnvironmentVariable($"FeatureManagement:{feature3}:EnabledFor:0:Name", "TimeWindow");
            Environment.SetEnvironmentVariable($"FeatureManagement:{feature3}:EnabledFor:0:Parameters:Start", DateTimeOffset.UtcNow.ToString("r"));

            Environment.SetEnvironmentVariable($"FeatureManagement:{feature4}:EnabledFor:0:Name", "TimeWindow");
            Environment.SetEnvironmentVariable($"FeatureManagement:{feature4}:EnabledFor:0:Parameters:Start", DateTimeOffset.UtcNow.AddDays(1).ToString("r"));

            IConfiguration config = new ConfigurationBuilder().AddEnvironmentVariables().Build();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(config)
            .AddFeatureManagement()
            .AddFeatureFilter <TimeWindowFilter>();

            ServiceProvider provider = serviceCollection.BuildServiceProvider();

            IFeatureManager featureManager = provider.GetRequiredService <IFeatureManager>();

            Assert.True(featureManager.IsEnabled(feature1));
            Assert.False(featureManager.IsEnabled(feature2));
            Assert.True(featureManager.IsEnabled(feature3));
            Assert.False(featureManager.IsEnabled(feature4));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Conditionally creates a branch in the request pipeline that is rejoined to the main pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="featureName">The feature that is required to be enabled to take use this application branch</param>
        /// <param name="configuration">Configures a branch to take</param>
        /// <returns></returns>
        public static IApplicationBuilder UseForFeature(this IApplicationBuilder app, string featureName, Action <IApplicationBuilder> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (string.IsNullOrEmpty(featureName))
            {
                throw new ArgumentNullException(nameof(featureName));
            }

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

            //
            // Create and configure the branch builder right away; otherwise,
            // we would end up running our branch after all the components
            // that were subsequently added to the main builder.
            IApplicationBuilder branchBuilder = app.New();

            configuration(branchBuilder);

            return(app.Use(main =>
            {
                // This is called only when the main application builder
                // is built, not per request.
                branchBuilder.Run(main);

                RequestDelegate branch = branchBuilder.Build();

                return async(context) =>
                {
                    IFeatureManager fm = context.RequestServices.GetRequiredService <IFeatureManagerSnapshot>();

                    if (fm.IsEnabled(featureName))
                    {
                        await branch(context);
                    }
                    else
                    {
                        await main(context);
                    }
                };
            }));
        }
Ejemplo n.º 24
0
        public UISettings Get()
        {
            // Only user feature flags should be returned because we aren't setting
            // an org key in the context
            var featureFlags = Enum.GetValues(typeof(FeatureFlag))
                               .OfType <FeatureFlag>()
                               .Where(f => _featureManager.IsEnabled(f.ToString()));

            return(new UISettings()
            {
                BuildNumber = UIDefinitions.BuildNumber,
                YearWcaIncorporated = UIDefinitions.YearWcaIncorporated,
                IsDevEnvironment = UIDefinitions.IsDevEnvironment,
                BackToActionstepURL = _actionstepService.LaunchPadUri.AbsoluteUri,
                UserFeatureFlags = featureFlags
            });
        }
Ejemplo n.º 25
0
        public async Task <string> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req)
        {
            // Signal to refresh the configuration watched keys are modified. This will be no-op
            // if the cache expiration time window is not reached.
            _configRefresher.Refresh(); // Can do sync by adding await

            // CONFIG (standard)
            var configValue = _config[ConfigKeys.FnMessage];

            // CONFIG (from KV)
            var kvConfigValue = _config[ConfigKeys.AKVSourcedSecret];

            // FEATURE
            var featureValue = _features.IsEnabled(Features.FlipFlop);

            return($"Config: {configValue} || Feature: {featureValue} || From KV: {kvConfigValue}");
        }