/// <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 async Task ProcessAsync(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 ?
                          await names.All(async n => await _featureManager.IsEnabledAsync(n).ConfigureAwait(false)) :
                          await names.Any(async n => await _featureManager.IsEnabledAsync(n).ConfigureAwait(false));
            }

            if (Negate)
            {
                enabled = !enabled;
            }

            if (!enabled)
            {
                output.SuppressOutput();
            }
        }
Example #2
0
        public async Task <AssetItem> UploadFormFile(IFormFile file, string root, string path = "")
        {
            path = path.Replace("/", _separator);

            VerifyPath(path);

            var fileName = GetFileName(file.FileName);
            var filePath = string.IsNullOrEmpty(path) ?
                           Path.Combine(Location, fileName) :
                           Path.Combine(Location, path + _separator + fileName);
            var thumbFolder = string.IsNullOrEmpty(path) ?
                              Path.Combine(Location, _thumbs) :
                              Path.Combine(Location, $"{path}{_separator}{_thumbs}");

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);

                if (await _featureManager.IsEnabledAsync(nameof(AppFeatureFlags.GenerateThumbs)))
                {
                    Stream stream = file.OpenReadStream();
                    SaveThumbnail(stream, thumbFolder, fileName);
                }

                return(new AssetItem
                {
                    Title = fileName,
                    Path = TrimFilePath(filePath),
                    Url = GetUrl(filePath, root)
                });
            }
        }
Example #3
0
            public string Login(string username, string password)
            {
                var callApiForLogin = featureManager.IsEnabledAsync("CallAPIForLogin").Result;

                if (!callApiForLogin)
                {
                    var wsUrl            = options.Value.AuthWebServiceURL;
                    var webServiceClient = new AuthWebServiceSoapClient();
                    webServiceClient.Endpoint.Address = new EndpointAddress(wsUrl);
                    var response = webServiceClient.Login(username, password);
                    return($"WebService response from BCL : {response}");
                }
                else
                {
                    var wapiUrl     = options.Value.AuthApiURL;
                    var httpClient  = new HttpClient();
                    var requestBody = System.Text.Json.JsonSerializer.Serialize(new
                    {
                        username = username,
                        password = password
                    });
                    var stringContent = new StringContent(requestBody, encoding: System.Text.Encoding.UTF8, mediaType: "application/json");
                    var httpResponse  = httpClient.PostAsync($"{wapiUrl}/Login", stringContent).Result;
                    var response      = httpResponse.Content.ReadAsStringAsync().Result;
                    return($"WebAPI response from BCL : {response}");
                }
            }
        public async Task <ActionResult <List <Contrato> > > Get([FromServices] DataContext context)
        {
            string MyKey = "Contratos";

            if (_featureManager != null && await _featureManager.IsEnabledAsync(AppFeatureFlags.CacheAtivo))
            {
                if (!_cache.TryGetValue(MyKey, out List <Contrato> cacheEntry))
                {
                    // Key not in cache, so get data.
                    var contratos = await context.Contratos.ToListAsync();

                    DateTime newExpiretion     = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
                    var      cacheEntryOptions = new MemoryCacheEntryOptions()
                                                 .SetAbsoluteExpiration(newExpiretion);

                    _cache.Set(MyKey, contratos, cacheEntryOptions);
                    return(contratos);
                }
                else
                {
                    return(cacheEntry);
                }
            }
            else
            {
                var contratos = await context.Contratos.ToListAsync();

                return(contratos);
            }
        }
Example #5
0
 /// <summary>
 /// Checks whether a given set of features are enabled.
 /// </summary>
 /// <param name="requirementType">
 /// Specifies whether to check if all or any of the given set of features are enabled.
 /// </param>
 /// <param name="features">The features to check.</param>
 /// <returns>True if the features are enabled, otherwise false.</returns>
 public static async Task <bool> IsEnabledAsync <TFeature>(this IFeatureManager <TFeature> featureManager, RequirementType requirementType, IEnumerable <TFeature> features)
     where TFeature : struct, Enum
 {
     return(requirementType == RequirementType.All ?
            await features.AllAsync(async feature => await featureManager.IsEnabledAsync(feature).ConfigureAwait(false)).ConfigureAwait(false) :
            await features.AnyAsync(async feature => await featureManager.IsEnabledAsync(feature).ConfigureAwait(false)).ConfigureAwait(false));
 }
        public async Task UsesContext()
        {
            IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

            var serviceCollection = new ServiceCollection();

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

            ServiceProvider provider = serviceCollection.BuildServiceProvider();

            ContextualTestFilter contextualTestFeatureFilter = (ContextualTestFilter)provider.GetRequiredService <IEnumerable <IFeatureFilterMetadata> >().First(f => f is ContextualTestFilter);

            contextualTestFeatureFilter.ContextualCallback = (ctx, accountContext) =>
            {
                var allowedAccounts = new List <string>();

                ctx.Parameters.Bind("AllowedAccounts", allowedAccounts);

                return(allowedAccounts.Contains(accountContext.AccountId));
            };

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

            AppContext context = new AppContext();

            context.AccountId = "NotEnabledAccount";

            Assert.False(await featureManager.IsEnabledAsync(ContextualFeature, context));

            context.AccountId = "abc";

            Assert.True(await featureManager.IsEnabledAsync(ContextualFeature, context));
        }
Example #7
0
 private async Task LogFeatureFlags()
 {
     await
     foreach (var f in _featureManager.GetFeatureNamesAsync())
     {
         _logger.LogInformation($"Feature flags: {f} = {await _featureManager.IsEnabledAsync(f)}");
     }
 }
        public void SetUp()
        {
            featureManager = A.Fake <IFeatureManager>();
            A.CallTo(() => featureManager.IsEnabledAsync(FeatureFlags.RefactoredTrackingSystem))
            .Returns(true);
            A.CallTo(() => featureManager.IsEnabledAsync(FeatureFlags.RefactoredSuperAdminInterface))
            .Returns(true);

            SetUpContextWithActionParameter();
        }
Example #9
0
        public async Task <IActionResult> GetPrice()
        {
            decimal price = 100;

            if (await _featureManager.IsEnabledAsync(Features.GetPrice))
            {
                // half done feature
                price = GetPriceBasedOnMetrix();
            }
            return(this.Ok(price));
        }
 async public void OnGet()
 {
     if (await featureManager.IsEnabledAsync("beta"))
     {
         featuredata += "beta ";
     }
     if (await featureManager.IsEnabledAsync("FeatureA"))
     {
         featuredata += "FeatureA";
     }
 }
        public async Task <IActionResult> Get()
        {
            var featureA = await _featureManager.IsEnabledAsync(nameof(Features.FeatureA));

            var featureB = await _featureManager.IsEnabledAsync(nameof(Features.FeatureB));

            var featureC = await _featureManager.IsEnabledAsync(nameof(Features.FeatureC));

            var featureD = await _featureManager.IsEnabledAsync(nameof(Features.FeatureD));

            return(Ok(featureD));
        }
Example #12
0
            public async Task RenderFlags(int clientId)
            {
                var appContext = new AppContext {
                    ClientId = clientId
                };

                await Console.Out.WriteLineAsync($"\r\n{DateTime.Now}");

                await Console.Out.WriteLineAsync($"New Pay Grid:         {await _manager.IsEnabledAsync("NewPayGrid")}");

                await Console.Out.WriteLineAsync($"New Payroll Reports:  {await _manager.IsEnabledAsync("NewPayrollReports", appContext)}");

                await Console.Out.WriteLineAsync($"Use Minimum Wage:     {await _manager.IsEnabledAsync("UseMinimumWage", appContext)}");
            }
        private async Task <bool> ApplicationIsInaccessibleByPage(
            DlsSubApplication application
            )
        {
            if (DlsSubApplication.TrackingSystem.Equals(application) &&
                !await featureManager.IsEnabledAsync(FeatureFlags.RefactoredTrackingSystem) ||
                DlsSubApplication.SuperAdmin.Equals(application) &&
                !await featureManager.IsEnabledAsync(FeatureFlags.RefactoredSuperAdminInterface))
            {
                return(true);
            }

            return(!validApplications.Contains(application));
        }
Example #14
0
        public async Task <WorkOrderResponse> Execute(int id)
        {
            var workOrder = await _repairsGateway.GetWorkOrder(id);

            var manuallyAssignedOperatives = workOrder.HasManuallyAssignedOperatives();

            if (await _featureManager.IsEnabledAsync(FeatureFlags.UpdateOperativesOnWorkOrderGet) &&
                await _featureManager.IsEnabledAsync(FeatureFlags.DRSIntegration) &&
                await workOrder.ContractorUsingDrs(_sorGateway) &&
                workOrder.StatusCode == WorkStatusCode.Open &&
                !manuallyAssignedOperatives)
            {
                _logger.LogInformation($"Calling DrsService.UpdateWorkOrderDetails from GetWorkOrderUseCase for {workOrder.Id}");

                try
                {
                    await _drsService.UpdateWorkOrderDetails(id);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, $"Failed to update work order {id} from DRS");

                    try
                    {
                        if (e.Message.Contains("Unable to find order in OptiTime Web"))
                        {
                            _logger.LogError(e, $"Couldn't find workorder, creating {id} instead DRS");
                            await _drsService.CreateOrder(workOrder);
                        }
                    }
                    catch (Exception)
                    {
                        //swallow exceptions for create
                    }
                }
            }

            var appointment = await _appointmentGateway.GetAppointment(workOrder.Id);

            var canAssignOperative = await workOrder.CanAssignOperative(_sorGateway);

            var workOrderResponse = workOrder.ToResponse(appointment, _drsOptions.Value.ManagementAddress, canAssignOperative);

            var tasks = await _repairsGateway.GetWorkOrderTasksForWorkOrder(workOrder);

            workOrderResponse.TotalSMVs = tasks is null ? 0 : tasks.Sum(t => t.StandardMinuteValue * t.Quantity);

            return(workOrderResponse);
        }
        public async Task <bool> IsEnabledAsync(string feature)
        {
            //
            // First, check local cache
            if (_flagCache.ContainsKey(feature))
            {
                return(_flagCache[feature]);
            }

            bool enabled = await _featureManager.IsEnabledAsync(feature).ConfigureAwait(false);

            _flagCache[feature] = enabled;

            return(enabled);
        }
Example #16
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            if (!await _featureManager.IsEnabledAsync(BrokerFeature.ProductComplexityWarning))
            {
                await _log.WriteInfoAsync(nameof(CleanupExpiredComplexityService),
                                          nameof(Run),
                                          $"Feature {BrokerFeature.ProductComplexityWarning} is disabled. " +
                                          $"{nameof(CleanupExpiredComplexityService)}.{nameof(Run)} will not be executed");

                return;
            }

            await _log.WriteInfoAsync(nameof(CleanupExpiredComplexityService),
                                      nameof(Run),
                                      $"Feature {BrokerFeature.ProductComplexityWarning} is enabled. " +
                                      $"{nameof(CleanupExpiredComplexityService)}.{nameof(Run)} will be executed");

            var retryForever = Policy.Handle <Exception>()
                               .RetryForeverAsync(onRetry: async ex =>
            {
                await _log.WriteErrorAsync(nameof(CleanupExpiredComplexityService), nameof(Run), ex);
            });

            while (!stoppingToken.IsCancellationRequested)
            {
                await retryForever.ExecuteAsync(Run, stoppingToken);

                await Task.Delay(_settings.ComplexityWarningExpirationCheckPeriod, stoppingToken);
            }
        }
Example #17
0
        public async Task <IEnumerable <Review> > GetReviews(int productId)
        {
            var starsReviewer1 = -1;
            var starsReviewer2 = -1;

            if (await _featureManager.IsEnabledAsync(nameof(FeatureFlags.RatingsEnabled)))
            {
                _logger.LogDebug("RatingsEnabled flag is set to true");
                var ratings = await _ratings.GetRatings(productId);

                starsReviewer1 = ratings.GetValueOrDefault("Reviewer1", -1);
                starsReviewer2 = ratings.GetValueOrDefault("Reviewer2", -1);
            }

            return(new List <Review>
            {
                new Review
                {
                    Reviewer = "Reviewer1",
                    Text = "An extremely entertaining play by Shakespeare. The slapstick humour is refreshing!",
                    Rating = starsReviewer1
                },
                new Review
                {
                    Reviewer = "Reviewer2",
                    Text = "Absolutely fun and entertaining. The play lacks thematic depth when compared to other plays by Shakespeare.",
                    Rating = starsReviewer2
                }
            });
        }
Example #18
0
        public async Task Execute(JobStatusUpdate jobStatusUpdate)
        {
            WorkOrder workOrder = jobStatusUpdate.RelatedWorkOrder;

            workOrder.VerifyCanVary();

            var workElement = jobStatusUpdate.MoreSpecificSORCode;

            await AddCodeCosts(workElement.RateScheduleItem, workOrder.AssignedToPrimary?.ContractorReference);

            // check the user has the require vary spend limit
            var authorised = await _authorizationService.AuthorizeAsync(_currentUserService.GetUser(), jobStatusUpdate, "VarySpendLimit");

            if (await _featureManager.IsEnabledAsync(FeatureFlags.SpendLimits) && !authorised.Succeeded)
            {
                workOrder.StatusCode     = WorkStatusCode.VariationPendingApproval;
                jobStatusUpdate.TypeCode = JobStatusUpdateTypeCode.ContractManagerApprovalNeeded_180;
                await _notifier.Notify(new HighCostVariationCreated(workOrder));
            }
            else
            {
                await _updateSorCodesUseCase.Execute(workOrder, workElement.DeepClone());
            }

            jobStatusUpdate.PrefixComments(Resources.VariationReason);
        }
        public async Task 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 (await featureManager.IsEnabledAsync(feature1))
                {
                    enabledCount++;
                }
            }

            Assert.True(enabledCount > 0 && enabledCount < 10);
        }
        /// <summary>
        ///     Add Authentication Extensions.
        /// </summary>
        public static IServiceCollection AddAuthentication(
            this IServiceCollection services,
            IConfiguration configuration)
        {
            IFeatureManager featureManager = services
                                             .BuildServiceProvider()
                                             .GetRequiredService <IFeatureManager>();

            bool isEnabled = featureManager
                             .IsEnabledAsync(nameof(CustomFeature.Authentication))
                             .ConfigureAwait(false)
                             .GetAwaiter()
                             .GetResult();

            if (isEnabled)
            {
                services.AddScoped <IUserService, UserService>();

                services.AddDefaultIdentity <ApplicationUser>()
                .AddEntityFrameworkStores <DataContext>();
            }
            else
            {
                services.AddScoped <IUserService, UserService>();

                services.AddDefaultIdentity <ApplicationUser>()
                .AddEntityFrameworkStores <DataContextFake>();
            }

            return(services);
        }
Example #21
0
 public void Setup()
 {
     featureManager = A.Fake <IFeatureManager>();
     configuration  = A.Fake <IConfiguration>();
     A.CallTo(() => featureManager.IsEnabledAsync(FeatureFlags.RefactoredTrackingSystem))
     .Returns(true);
 }
Example #22
0
        public static async Task Main(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                                               .AddAzureAppConfiguration(options =>
            {
                //options.Connect(Environment.GetEnvironmentVariable("ConnectionString")).UseFeatureFlags();
                options.Connect(_appConfigConnectionString).UseFeatureFlags();
            }).Build();

            IServiceCollection services = new ServiceCollection();

            services.AddSingleton <IConfiguration>(configuration).AddFeatureManagement().AddFeatureFilter <ringDeploymentFilter>();

            FeatureFilterEvaluationContext context = new FeatureFilterEvaluationContext();
            ringDeploymentFilter           ff      = new ringDeploymentFilter();

            using (ServiceProvider serviceProvider = services.BuildServiceProvider())
            {
                IFeatureManager featureManager = serviceProvider.GetRequiredService <IFeatureManager>();

                var enabled = await featureManager.IsEnabledAsync("ff_RefreshWeatherData", ff);

                if (enabled == true)
                {
                    Console.WriteLine("Welcome to the beta!");
                }
            }

            Console.WriteLine("Hello World!");
        }
Example #23
0
        /// <summary>
        ///     Add Health Checks dependencies varying on configuration.
        /// </summary>
        public static IServiceCollection AddHealthChecks(
            this IServiceCollection services,
            IConfiguration configuration)
        {
            if (services is null)
            {
                throw new System.ArgumentNullException(nameof(services));
            }

            if (configuration is null)
            {
                throw new System.ArgumentNullException(nameof(configuration));
            }

            IHealthChecksBuilder healthChecks = services.AddHealthChecks();

            IFeatureManager featureManager = services
                                             .BuildServiceProvider()
                                             .GetRequiredService <IFeatureManager>();

            bool isEnabled = featureManager
                             .IsEnabledAsync(nameof(CustomFeature.SQLServer))
                             .ConfigureAwait(false)
                             .GetAwaiter()
                             .GetResult();

            if (isEnabled)
            {
                healthChecks.AddDbContextCheck <DataContext>("DataContext");
            }

            return(services);
        }
        /// <summary>
        ///     Add Currency Exchange dependencies varying on configuration.
        /// </summary>
        public static IServiceCollection AddCurrencyExchange(
            this IServiceCollection services,
            IConfiguration configuration)
        {
            IFeatureManager featureManager = services
                                             .BuildServiceProvider()
                                             .GetRequiredService <IFeatureManager>();

            bool isEnabled = featureManager
                             .IsEnabledAsync(nameof(CustomFeature.CurrencyExchange))
                             .ConfigureAwait(false)
                             .GetAwaiter()
                             .GetResult();

            if (isEnabled)
            {
                services.AddHttpClient(CurrencyExchangeService.HttpClientName);
                services.AddScoped <ICurrencyExchange, CurrencyExchangeService>();
            }
            else
            {
                services.AddScoped <ICurrencyExchange, CurrencyExchangeFake>();
            }

            return(services);
        }
Example #25
0
 public async Task <IActionResult> Index()
 {
     return(Ok(new
     {
         IsTestFeatureEnabled = await _featureManager.IsEnabledAsync("TestFeatureEnabled")
     }));
 }
Example #26
0
        public async Task <IEnumerable <WeatherForecast> > GetAsync()
        {
            var rng = new Random();

            if (await _featureManager.IsEnabledAsync(nameof(FeatureManagement.EnableMoreRecords)))
            {
                return(Enumerable.Range(1, 50).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Summaries[rng.Next(Summaries.Length)]
                })
                       .ToArray());
            }
            else
            {
                return(Enumerable.Range(1, 2).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Summaries[rng.Next(Summaries.Length)]
                })
                       .ToArray());
            }
        }
Example #27
0
 public async Task OnGet()
 {
     if (await _featureManager.IsEnabledAsync(nameof(FeatureFlags.RecentPosts)))
     {
         RecentPosts = _blogService.GetRecentPosts();
     }
 }
        /// <summary>
        /// Gets the item from the Cache or invokes given delegate to populate cache and return
        /// </summary>
        public static async Task <IQueryable <T> > GetOrCacheAside <T>(
            this IRedisDatabase cache,
            Func <IQueryable <T> > fetchDelegate,
            string hashKey,
            string hashPattern          = "*",
            Func <T, string> keyBuilder = null,
            ILogger logger           = null,
            IFeatureManager features = null)
            where T : ICacheable
        {
            if (features != null && !(await features.IsEnabledAsync(nameof(Features.Caching))))
            {
                logger?.LogInformation("Caching was disabled");
                return(fetchDelegate.Invoke());
            }

            if (keyBuilder == null)
            {
                keyBuilder = x => x.ToCacheKeyString();
            }

            logger?.LogDebug("Retrieving from cache");
            var items = cache.HashScan <T>(hashKey, hashPattern).Select(x => x.Value).AsQueryable();

            if (!items.Any())
            {
                logger?.LogInformation("No Items were found in the cache, fetching and setting into cache");

                items = fetchDelegate.Invoke();
                await cache.HashSetAsync(hashKey, items.ToDictionary(keyBuilder, x => x));
            }

            logger?.LogDebug($"Retrieving {items.Count()} from cache");
            return(items);
        }
Example #29
0
        public void PopulateFeature(IEnumerable <ApplicationPart> parts, ControllerFeature feature)
        {
            for (int i = feature.Controllers.Count - 1; i >= 0; i--)
            {
                var controller = feature.Controllers[i].AsType();
                foreach (var customAttribute in controller.CustomAttributes)
                {
                    if (customAttribute.AttributeType.FullName == typeof(FeatureGateAttribute).FullName)
                    {
                        var constructorArgument = customAttribute.ConstructorArguments.First();
                        foreach (var argumentValue in constructorArgument.Value as IEnumerable)
                        {
                            var typedArgument      = (CustomAttributeTypedArgument)argumentValue;
                            var typedArgumentValue = (Features)(int)typedArgument.Value;
                            var isFeatureEnabled   = _featureManager.IsEnabledAsync(typedArgumentValue.ToString())
                                                     .ConfigureAwait(false)
                                                     .GetAwaiter()
                                                     .GetResult();

                            if (!isFeatureEnabled)
                            {
                                feature.Controllers.RemoveAt(i);
                            }
                        }
                    }
                }
            }
        }
Example #30
0
        /// <summary>
        ///     Add Persistence dependencies varying on configuration.
        /// </summary>
        public static IServiceCollection AddSQLServer(
            this IServiceCollection services,
            IConfiguration configuration)
        {
            IFeatureManager featureManager = services
                                             .BuildServiceProvider()
                                             .GetRequiredService <IFeatureManager>();

            bool isEnabled = featureManager
                             .IsEnabledAsync(nameof(CustomFeature.SQLServer))
                             .ConfigureAwait(false)
                             .GetAwaiter()
                             .GetResult();

            if (isEnabled)
            {
                services.AddDbContext <DataContext>(
                    options => options.UseSqlServer(
                        configuration.GetValue <string>("PersistenceModule:DefaultConnection")));
                services.AddScoped <IUnitOfWork, UnitOfWork>();

                services.AddScoped <IArticleRepository, ArticleRepository>();
            }
            else
            {
                services.AddSingleton <DataContextFake, DataContextFake>();
                services.AddScoped <IUnitOfWork, UnitOfWorkFake>();
                services.AddScoped <IArticleRepository, ArticleRepositoryFake>();
            }

            services.AddScoped <IArticleFactory, EntityFactory>();

            return(services);
        }