예제 #1
0
 GetCommands()
 {
     return(DictionaryBuilder
            .Create <string, ICommand>()
            .Add("login", new Command(nameof(Login), Login))
            .Dictionary);
 }
        public async Task <IDictionary <Type, Guid> > WhoAmIAsync()
        {
            using (ITransaction transaction = _transactionManager.Create())
            {
                if (!_currentIdentityProvider.IsAuthenticated)
                {
                    return(new Dictionary <Type, Guid>());
                }

                Identity identity = await _identityQueryRepository.GetByIdAsync(_currentIdentityProvider.Id);

                if (identity == null || identity.Session.IsRevoked)
                {
                    throw new BusinessApplicationException(ExceptionType.Unauthorized, "Current identity token is not valid");
                }

                DictionaryBuilder <Type, Guid> whoAmI = DictionaryBuilder <Type, Guid> .Create();

                whoAmI.Add(typeof(Identity), identity.Id);

                if (_currentUserProvider.Id.HasValue)
                {
                    User user = await _userQueryRepository.GetByIdAsync(_currentUserProvider.Id.Value);

                    if (user != null)
                    {
                        whoAmI.Add(typeof(User), user.Id);
                    }
                }

                transaction.Commit();

                return(whoAmI.Build());
            }
        }
예제 #3
0
        public void ContainsKey_returns()
        {
            var sut = DictionaryBuilder <int, string> .Create(Setup());

            Assert.True(sut.ContainsKey(4));
            Assert.False(sut.ContainsKey(6));
        }
        public async Task <IClientCredentialAuthenticationResult> Validate(
            AuthenticationGrantTypeGoogle authenticationGrantTypeGoogle,
            ValidateClientCredentialAdto validateClientCredentialAdto)
        {
            try
            {
                GoogleAccessTokenResponse appAccessTokenResponse = await _httpJson.PostAsync <GoogleAccessTokenResponse>(
                    new Uri(authenticationGrantTypeGoogle.GrantAccessTokenUrl.Format(
                                DictionaryBuilder <string, object> .Create()
                                .Add("clientId", authenticationGrantTypeGoogle.ClientId)
                                .Add("clientSecret", authenticationGrantTypeGoogle.ClientSecret)
                                .Add("redirectUri", validateClientCredentialAdto.RedirectUri)
                                .Add("code", validateClientCredentialAdto.Token)
                                .Build()
                                )), _jsonSerializerSettings
                    );

                ValidateAccessTokenResponse validateAccessTokenResponse = await _httpJson.GetAsync <ValidateAccessTokenResponse>(new Uri(
                                                                                                                                     authenticationGrantTypeGoogle.ValidateAccessTokenUrl.Format(
                                                                                                                                         DictionaryBuilder <string, object> .Create()
                                                                                                                                         .Add("accessToken", appAccessTokenResponse.AccessToken)
                                                                                                                                         .Build()
                                                                                                                                         )), _jsonSerializerSettings);

                return(ClientCredentialAuthenticationResult.Succeed(validateAccessTokenResponse.Id));
            }
            catch (BadRequestException)
            {
                return(ClientCredentialAuthenticationResult.Fail);
            }
            catch (ServiceUnavailableExcpetion)
            {
                return(ClientCredentialAuthenticationResult.Fail);
            }
        }
예제 #5
0
        public void Contains_returns()
        {
            var sut = DictionaryBuilder <int, string> .Create(Setup());

            Assert.True(sut.Contains(new KeyValuePair <int, string>(4, "D")));
            Assert.False(sut.Contains(new KeyValuePair <int, string>(5, "D")));
        }
예제 #6
0
 public IndexRazor()
 {
     ComponentDictionary = DictionaryBuilder
                           .Create <string, IDictionary <string, object> >()
                           .Add("CounterComponent", DictionaryBuilder.Create <string, object>().ToDictionary())
                           .Add("CustomerComponent", DictionaryBuilder.Create <string, object>(builder => { builder.Add("CustomerId", 3); }).ToDictionary())
                           .ToDictionary();
 }
 GetCommands()
 {
     return(DictionaryBuilder
            .Create <string, ICommand>()
            .Add("echo", new Command(nameof(Echo), Echo))
            .Add("quit", new Command(nameof(Quit), Quit))
            .Dictionary);
 }
예제 #8
0
        public void Create_with_KeyValuePair_parameter_includes_existing_entries()
        {
            var sut = DictionaryBuilder <int, string> .Create(Setup());

            Assert.Contains(1, sut.ToDictionary());
            Assert.Contains(2, sut.ToDictionary());
            Assert.Contains(3, sut.ToDictionary());
            Assert.Contains(4, sut.ToDictionary());
        }
예제 #9
0
        private static IDictionary <string, object> _buildMeta(IEnumerable <Property> properties, bool includeExtendedMeta)
        {
            DictionaryBuilder <string, object> metaBuilder = DictionaryBuilder <string, object> .Create();

            foreach (Property property in properties)
            {
                metaBuilder.Add(property.Name, _buildPropertyMeta(property, includeExtendedMeta));
            }

            return(metaBuilder.Build());
        }
예제 #10
0
        public static ICommand Create <T>(string name, Action <IDictionaryBuilder <string, object> > commandParameters)
        {
            if (commandParameters == null)
            {
                throw new ArgumentNullException(nameof(commandParameters));
            }

            var parameters = DictionaryBuilder.Create <string, object>();

            commandParameters(parameters);
            return(new DefaultCommand <T>(name, parameters.ToDictionary()));
        }
예제 #11
0
        public static IDictionary <TKey, TValue> Add <TKey, TValue>(this IDictionary <TKey, TValue> dictionary, Action <IDictionaryBuilder <TKey, TValue> > builderAction)
        {
            var dictionaryBuilder = DictionaryBuilder <TKey, TValue> .Create();

            builderAction(dictionaryBuilder);
            foreach (var(key, value) in dictionaryBuilder.Dictionary)
            {
                dictionary.TryAdd(key, value);
            }

            return(dictionary);
        }
예제 #12
0
        private IDictionary <string, object> _getAdditionalParams(ISortTemplate sortTemplate)
        {
            DictionaryBuilder <string, object> dictionaryBuilder = DictionaryBuilder <string, object> .Create();

            List <string> handledProperties = new List <string>
            {
                nameof(sortTemplate.Sort)
            };

            foreach (PropertyInfo propertyInfo in sortTemplate.GetType().GetProperties().Where(p => !handledProperties.Contains(p.Name)))
            {
                dictionaryBuilder.Add(propertyInfo.Name, propertyInfo.GetValue(sortTemplate).ToString());
            }

            return(dictionaryBuilder.Build());
        }
예제 #13
0
        public async Task <ActionResult> Details([FromRoute] string reference, [FromQuery] int pageSize = 8, [FromQuery] int pageNumber = 1)
        {
            var response = await MediatorService
                           .Send(new RetrieveBudgetPlannerRequest {
                AccountId = (await CurrentAccount).Id,
                Reference = reference
            });

            if (!response.IsSuccessful)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var budgetStatsResponse = await MediatorService.Send(new BudgetPlannerStatsRequest
            {
                BudgetId = response.Result.Id,
                FromDate = DateTime.Now.AddDays(-7),
                ToDate   = DateTime.Now
            });

            if (!budgetStatsResponse.IsSuccessful)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var budgetPlannerDetailsViewModel = Map <Budget, BudgetPlannerDetailsViewModel>(response.Result);

            budgetPlannerDetailsViewModel.PageSize   = pageSize;
            budgetPlannerDetailsViewModel.PageNumber = pageNumber;
            budgetPlannerDetailsViewModel.FromDate   = DateTime.Now.AddDays(-30);
            budgetPlannerDetailsViewModel.ToDate     = DateTime.Now;
            budgetPlannerDetailsViewModel.Balance    = response.Amount;
            budgetPlannerDetailsViewModel.BudgetStatisticsRequest = new BudgetStatisticRequestViewModel
            {
                AccountId = (await CurrentAccount).Id,
                FromDate  = DateTime.Now.AddDays(-5),
                ToDate    = DateTime.Now,
                BudgetId  = response.Result.Id
            };

            return(await ViewWithContent(ContentConstants.DetailsContentPath, budgetPlannerDetailsViewModel,
                                         DictionaryBuilder.Create <string, string>(dictionaryBuilder => dictionaryBuilder
                                                                                   .Add("startDate", budgetPlannerDetailsViewModel.FromDate.ToString(FormatConstants.LongDateFormat))
                                                                                   .Add("endDate", budgetPlannerDetailsViewModel.ToDate.ToString(FormatConstants.LongDateFormat)))
                                         .ToDictionary()));
        }
예제 #14
0
        public static FormattedArrayResponse Create(BuiltCollectionResource builtCollectionResource, HttpRequest httpRequest)
        {
            bool includeExtendedMeta = httpRequest.Headers.ContainsKey(HeaderType.ExtendedMeta);

            DictionaryBuilder <string, object> metaBuilder = DictionaryBuilder <string, object> .Create();

            metaBuilder.Add(MetaType.TotalResults, builtCollectionResource.TotalResults);

            if (builtCollectionResource.BuiltResources.Any(
                    r => r.Properties.Any(p => p.Constraints.IsSortable ?? false)))
            {
                DictionaryBuilder <string, object> sortBuilder = DictionaryBuilder <string, object> .Create();

                sortBuilder.Add(MetaType.Values, builtCollectionResource.BuiltResources.First().Properties.Where(p => p.Constraints.IsSortable ?? false).Select(p => p.Name.ToCamelCase()));

                metaBuilder.Add(MetaType.Sort, sortBuilder.Build());
            }

            return(new FormattedArrayResponse
            {
                Data = builtCollectionResource.BuiltResources.Select(r =>
                {
                    DictionaryBuilder <string, object> attributeBuilder = DictionaryBuilder <string, object> .Create();

                    foreach (Property builtResourceProperty in r.Properties)
                    {
                        attributeBuilder.Add(builtResourceProperty.Name, builtResourceProperty.Value);
                    }

                    return new Data
                    {
                        Type = GetResourceTypeName(r.Type),
                        Id = r.Id,
                        Attributes = attributeBuilder.Build(),
                        Links = _buildLinks(r.Links),
                        Meta = _buildMeta(r.Properties, includeExtendedMeta)
                    };
                }
                                                                     ),
                Links = _buildLinks(builtCollectionResource.Links),
                Meta = metaBuilder.Build()
            });
        }
        private static string BuildClientAccessUrl(
            AuthenticationGrantTypeClientCredential authenticationGrantTypeClientCredential,
            GetAuthenticationServicesAdto getAuthenticationServicesAdto)
        {
            IDictionaryBuilder <string, object> builder = DictionaryBuilder <string, object> .Create()
                                                          .Add("clientId", authenticationGrantTypeClientCredential.ClientId);

            if (!string.IsNullOrWhiteSpace(getAuthenticationServicesAdto.State))
            {
                builder.Add("state", getAuthenticationServicesAdto.State);
            }

            if (!string.IsNullOrWhiteSpace(getAuthenticationServicesAdto.RedirectUri))
            {
                builder.Add("redirectUri", getAuthenticationServicesAdto.RedirectUri);
            }

            return(authenticationGrantTypeClientCredential.ClientGrantAccessTokenUrl.Format(builder.Build()));
        }
예제 #16
0
        private static IDictionary <string, Link> _buildLinks(Links.Links links)
        {
            DictionaryBuilder <string, Link> linkBuilder = DictionaryBuilder <string, Link> .Create();

            if (links.Self != null)
            {
                linkBuilder.Add(links.Self.Name, LinkFactory.Create(links.Self));
            }

            if (links.PagingLinks != null)
            {
                if (links.PagingLinks.First != null)
                {
                    linkBuilder.Add(links.PagingLinks.First.Name, LinkFactory.Create(links.PagingLinks.First));
                }

                if (links.PagingLinks.Previous != null)
                {
                    linkBuilder.Add(links.PagingLinks.Previous.Name, LinkFactory.Create(links.PagingLinks.Previous));
                }

                if (links.PagingLinks.Next != null)
                {
                    linkBuilder.Add(links.PagingLinks.Next.Name, LinkFactory.Create(links.PagingLinks.Next));
                }

                if (links.PagingLinks.Last != null)
                {
                    linkBuilder.Add(links.PagingLinks.Last.Name, LinkFactory.Create(links.PagingLinks.Last));
                }
            }

            if (links.RelatedLinks != null)
            {
                foreach (ILink relatedLink in links.RelatedLinks)
                {
                    linkBuilder.Add(relatedLink.Name, LinkFactory.Create(relatedLink));
                }
            }

            return(linkBuilder.Build());
        }
예제 #17
0
        public async Task <string> CalculateNewBalance(int budgetId, int transactionTypeId, decimal amount)
        {
            var response = await MediatorService.Send(new RetrieveBudgetPlannerRequest
            {
                BudgetPlannerId = budgetId,
                AccountId       = (await CurrentAccount).Id
            });

            var newBalance = response.Amount - amount;

            if (transactionTypeId == 1)
            {
                newBalance = response.Amount + amount;
            }

            return(await GetContent(ContentConstants.TransactionEditorPath,
                                    ContentConstants.EstimatedCostCalculatorLabel,
                                    DictionaryBuilder.Create <string, string>(builder => builder
                                                                              .Add("newBalance", newBalance.ToString(FormatConstants.CurrencyFormat)))
                                    .ToDictionary()));
        }
예제 #18
0
        private static IDictionary <string, object> _buildPropertyMeta(Property property, bool includeExtendedMeta)
        {
            DictionaryBuilder <string, object> propertyMetaBuilder = DictionaryBuilder <string, object> .Create();

            propertyMetaBuilder.Add(MetaType.Type, property.FieldType ?? FieldTypeMapper.GetFieldType(property.Type));

            if (property.Constraints != null)
            {
                if (property.Constraints.IsHidden.HasValue)
                {
                    propertyMetaBuilder.Add(MetaType.IsHidden, property.Constraints.IsHidden);
                }

                if (property.Constraints.IsReadonly.HasValue)
                {
                    propertyMetaBuilder.Add(MetaType.IsReadonly, property.Constraints.IsReadonly);
                }
            }

            if (property.ValidationConstraints != null && includeExtendedMeta)
            {
                if (property.ValidationConstraints.IsRequired.HasValue)
                {
                    propertyMetaBuilder.Add(MetaType.IsRequired, property.ValidationConstraints.IsRequired);
                }

                if (property.ValidationConstraints.MaxLength.HasValue)
                {
                    propertyMetaBuilder.Add(MetaType.MaxLength, property.ValidationConstraints.MaxLength);
                }

                if (property.ValidationConstraints.MinLenth.HasValue)
                {
                    propertyMetaBuilder.Add(MetaType.MinLenth, property.ValidationConstraints.MinLenth);
                }
            }

            return(propertyMetaBuilder.Build());
        }
예제 #19
0
        public async Task <LoginResponse> Login(string emailAddress, string password, CancellationToken cancellationToken)
        {
            var requestToken = await GetRequestToken();

            var token = await _cookieValidationService.CreateCookieToken(configure => { }, EncryptionKeyConstants.Api,
                                                                         DictionaryBuilder.Create <string, string>().Add(ClaimConstants.RequestTokenClaim, requestToken).ToDictionary(),
                                                                         _applicationSettings.SessionExpiryInMinutes, cancellationToken);

            _accountHttpClient.DefaultRequestHeaders.Add("payload", token);

            var httpContent = CreateForm(DictionaryBuilder.Create <string, object>()
                                         .Add("emailAddress", emailAddress)
                                         .Add("password", emailAddress)
                                         .ToDictionary());

            var response = await _accountHttpClient.PostAsync(HttpServiceConstants.AuthenticateAccount, httpContent);

            if (response.IsSuccessStatusCode)
            {
                return(await response.Content.ToObject <LoginResponse>());
            }

            return(default);
예제 #20
0
        public static FormattedResponse Create(BuiltResource builtResource, HttpRequest httpRequest)
        {
            bool includeExtendedMeta = httpRequest.Headers.ContainsKey(HeaderType.ExtendedMeta);

            DictionaryBuilder <string, object> attributeBuilder = DictionaryBuilder <string, object> .Create();

            foreach (Property builtResourceProperty in builtResource.Properties)
            {
                attributeBuilder.Add(builtResourceProperty.Name, builtResourceProperty.Value);
            }

            return(new FormattedResponse
            {
                Data = new Data
                {
                    Type = GetResourceTypeName(builtResource.Type),
                    Id = builtResource.Id,
                    Attributes = attributeBuilder.Build(),
                    Meta = _buildMeta(builtResource.Properties, includeExtendedMeta)
                },
                Links = _buildLinks(builtResource.Links)
            });
        }
예제 #21
0
        private async Task <IViewComponentResult> List(BudgetPanelDashboardListViewModel model)
        {
            var budgetPanelDashboardViewModel = new BudgetPanelDashboardViewModel();

            var retrieveBudgetPlannersRequest = Map <BudgetPanelDashboardListViewModel, RetrieveBudgetPlannersRequest>(model);

            var response = await MediatorService
                           .Send(retrieveBudgetPlannersRequest);

            budgetPanelDashboardViewModel.BudgetPlanners = Map <Domains.Dto.Budget, BudgetPanelDashboardItemViewModel>(response.Result);

            return(await ViewWithContent(
                       (response.Result.Any())
                       ?ContentConstants.Dashboard
                       : ContentConstants.EmptyDashboard, "List", budgetPanelDashboardViewModel, DictionaryBuilder
                       .Create <string, string>(dictionaryBuilder => dictionaryBuilder.Add("date", model.LastUpdated.ToString(FormatConstants.LongDateFormat)))
                       .ToDictionary()));
        }
예제 #22
0
        public void Create_with_empty_parameter_generates_empty_list()
        {
            var sut = DictionaryBuilder <string, int> .Create();

            Assert.Empty(sut);
        }
예제 #23
0
        public void Indexer_returns()
        {
            var sut = DictionaryBuilder <int, string> .Create(Setup());

            Assert.Equal("A", sut[1]);
        }
예제 #24
0
        public void ToKeyValuePairs_returns()
        {
            var sut = DictionaryBuilder <int, string> .Create(Setup());

            Assert.Equal(Setup(), sut.ToKeyValuePairs());
        }
예제 #25
0
 public async Task <string> CreateCookieToken(Action <SecurityTokenDescriptor> setupSecurityTokenDescriptor,
                                              Account account, int expiryPeriodInMinutes, CancellationToken cancellationToken)
 {
     return(await CreateCookieToken(setupSecurityTokenDescriptor, EncryptionKeyConstants.Default, DictionaryBuilder.Create <string, string>(builder => builder
                                                                                                                                            .Add(ClaimConstants.AccountIdClaim, account.Id.ToString())).ToDictionary(), expiryPeriodInMinutes, cancellationToken));
 }
        public override async Task <bool> RunAsync(CancellationToken cancellationToken)
        {
            var solutionAddProjectCommand = await GetCommandByKey("Solution.Add", cancellationToken);

            var projectAddCommand = await GetCommandByKey("Project.Add", cancellationToken);

            var solutionDirectory = $"{configuration.Output}\\{configuration.SolutionName}";

            await CreateSolutionFile(projectAddCommand, solutionDirectory, cancellationToken);

            foreach (var project in configuration.ProjectNames)
            {
                var projectName      = $"{configuration.SolutionName}.{project}";
                var projectPath      = $"{solutionDirectory}\\{projectName}\\";
                var projectDirectory = $"{solutionDirectory}\\{projectName}";

                string type = await ConsoleInputErrorLoopHandler
                              .Begin(prompt : () =>
                                     Console.WriteLine($"{NewLine}Enter project type for {projectName}: "),
                                     handler : (strInput) => projectAddCommand.Types
                                     .Any(a => a.Key.Equals(strInput, StringComparison.InvariantCultureIgnoreCase)),
                                     failedAttemptHandler : (strInput) => Console.WriteErrorLine("Invalid type selected."),
                                     onFinalHandler : (success) => Logger.LogTrace($"Is accepted: {success}"));

                var configureWebApplicationWithRazorandVue =
                    ProcessUserPromptToCopyWebRazorAndVueContentFiles(type, projectName);

                //Create project of specified type
                await CreateProject(type, projectDirectory,
                                    projectAddCommand, cancellationToken);

                //Add project to solution
                await AddProjectToSolution(solutionAddProjectCommand, projectPath,
                                           solutionDirectory, cancellationToken);

                if (configureWebApplicationWithRazorandVue)
                {
                    //Copy startup.cs from template directory
                    await CopyStartupToWebProject(projectDirectory, projectName, cancellationToken);

                    await CopyContentFilesToWebProject(projectPath, cancellationToken);

                    char userSelection = default;
                    var  commandNameDictionaryBuilder = DictionaryBuilder.Create <char, string>()
                                                        .Add('1', "Npm.Install")
                                                        .Add('2', "Yarn.Install");
                    string commandName = string.Empty;

                    await ConsoleInputErrorLoopHandler.Begin(prompt : () => {
                        Console.WriteLine("Which package manager should be used for client files?");
                        Console.Write($"\t 1. NPM{NewLine}" +
                                      $"\t2. Yarn{NewLine}{NewLine}Please select:\t");
                        userSelection = Console.Read().KeyChar;
                    },
                                                             handler : input => commandNameDictionaryBuilder.TryGetValue(userSelection, out commandName),
                                                             failedAttemptHandler : input => Console.WriteLine($"{NewLine}Invalid selection.{NewLine}"));

                    var packageManagerCommand = await GetCommandByKey(commandName, cancellationToken);

                    await RunPackageManager(packageManagerCommand, projectPath, cancellationToken);
                }
            }

            return(true);
        }
 public ModelStateException(Action <IDictionaryBuilder <string, string> > memberExceptions)
 {
     ModelStateBuilder = DictionaryBuilder.Create <string, string>();
     memberExceptions?.Invoke(ModelStateBuilder);
 }