public Result FindPath(AStarServiceModel model)
        {
            if (!ValidationUtil.IsObjectValid(model))
            {
                return(null);
            }

            var heap     = new MinHeap <AStarNode>();
            var allSteps = new HashSet <INode>();

            var startNode = model.StartNode;
            var endNode   = model.EndNode;
            var grid      = model.Grid;

            startNode.GScore    = 0;
            startNode.HScore    = this.ManhattanDistance(startNode, endNode);
            startNode.IsVisited = true;
            startNode.Direction = NodeDirection.Up;
            heap.Add(startNode);

            while (heap.Count != 0)
            {
                var currentNode = heap.Pop();

                if (currentNode.NodeType == NodeType.Wall)
                {
                    continue;
                }

                if (currentNode.Equals(endNode))
                {
                    // Remove StartNode
                    allSteps.Remove(allSteps.ElementAt(0));
                    return(new Result(allSteps, this.GetAllNodesInShortestPathOrder(currentNode)));
                }

                allSteps.Add(currentNode);

                var rowDirection    = new[] { -1, +1, 0, 0 };
                var columnDirection = new[] { 0, 0, +1, -1 };
                for (var i = 0; i < 4; i++)
                {
                    var currentRowDirection = currentNode.Row + rowDirection[i];
                    var currentColDirection = currentNode.Col + columnDirection[i];

                    if (currentRowDirection < 0 ||
                        currentColDirection < 0 ||
                        currentRowDirection >= grid.GetLength(0) ||
                        currentColDirection >= grid.GetLength(1))
                    {
                        continue;
                    }

                    var nextNode = grid[currentRowDirection, currentColDirection];
                    this.AddNodeToHeap(currentNode, nextNode, endNode, heap);
                }
            }

            return(new Result(allSteps));
        }
        public Result FindPath(DijkstraServiceModel model)
        {
            if (!ValidationUtil.IsObjectValid(model))
            {
                return(null);
            }

            this.startNode = model.StartNode;
            this.endNode   = model.EndNode;
            var grid = model.Grid;

            var heap     = new MinHeap <DijkstraNode>();
            var allSteps = new HashSet <INode>();

            this.startNode.Distance  = 0;
            this.startNode.IsVisited = true;
            heap.Add(this.startNode);

            while (heap.Count != 0)
            {
                var currentNode = heap.Pop();

                if (grid[currentNode.Row, currentNode.Col].NodeType == NodeType.Wall)
                {
                    continue;
                }

                // Destination target found
                if (currentNode.Equals(this.endNode))
                {
                    allSteps.Remove(allSteps.ElementAt(0));
                    return(new Result(allSteps, this.GetAllNodesInShortestPathOrder(currentNode)));
                }

                allSteps.Add(currentNode);

                var rowDirection    = new[] { -1, +1, 0, 0 };
                var columnDirection = new[] { 0, 0, +1, -1 };
                for (var i = 0; i < 4; i++)
                {
                    var currentRowDirection = currentNode.Row + rowDirection[i];
                    var currentColDirection = currentNode.Col + columnDirection[i];

                    if (currentRowDirection < 0 ||
                        currentColDirection < 0 ||
                        currentRowDirection >= grid.GetLength(0) ||
                        currentColDirection >= grid.GetLength(1))
                    {
                        continue;
                    }

                    var targetNode = grid[currentRowDirection, currentColDirection];
                    this.AddNodeToHeap(currentNode, targetNode, heap);
                }
            }

            return(new Result(allSteps));
        }
Beispiel #3
0
        public List <int[]> GenerateWeightMaze(MazeServiceModel model)
        {
            if (!ValidationUtil.IsObjectValid(model))
            {
                return(null);
            }

            this.GenerateMaze(model.Grid, 0, 0, NodeType.Weight);

            return(this.elements);
        }
Beispiel #4
0
        public async Task <GlobalTransferResult> TransferMoneyAsync(GlobalTransferDto model)
        {
            if (!ValidationUtil.IsObjectValid(model))
            {
                return(GlobalTransferResult.GeneralFailure);
            }

            var account = await this.bankAccountService
                          .GetByIdAsync <BankAccountConciseServiceModel>(model.SourceAccountId);

            // check if account exists and recipient name is accurate
            if (account == null)
            {
                return(GlobalTransferResult.GeneralFailure);
            }

            // verify there is enough money in the account
            if (account.Balance < model.Amount)
            {
                return(GlobalTransferResult.InsufficientFunds);
            }

            // contact the CentralApi to execute the transfer
            var submitDto = this.mapper.Map <CentralApiSubmitTransferDto>(model);

            submitDto.SenderName            = account.UserFullName;
            submitDto.SenderAccountUniqueId = account.UniqueId;

            bool remoteSuccess = await this.ContactCentralApiAsync(submitDto);

            if (!remoteSuccess)
            {
                return(GlobalTransferResult.GeneralFailure);
            }

            // remove money from source account
            var serviceModel = new MoneyTransferCreateServiceModel
            {
                Amount      = -model.Amount,
                Source      = account.UniqueId,
                Description = model.Description,
                AccountId   = account.Id,
                DestinationBankAccountUniqueId = model.DestinationBankAccountUniqueId,
                SenderName      = account.UserFullName,
                RecipientName   = model.RecipientName,
                ReferenceNumber = submitDto.ReferenceNumber
            };

            bool success = await this.moneyTransferService.CreateMoneyTransferAsync(serviceModel);

            return(!success ? GlobalTransferResult.GeneralFailure : GlobalTransferResult.Succeeded);
        }
Beispiel #5
0
        public Result FindPath(DfsServiceModel model)
        {
            if (!ValidationUtil.IsObjectValid(model))
            {
                return(null);
            }

            var path = new List <INode>();

            return(this.PathFound(model.Grid, model.StartNode, model.EndNode, path)
                ? new Result(path, path)
                : new Result(path));
        }
Beispiel #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <CodexApiDbContext>(options =>
                                                      options.UseSqlServer(
                                                          this.Configuration.GetConnectionString("DefaultConnection")));
            services.AddScoped <IBankService, BankService>();

            services.Configure <CodexApiConfiguration>(
                this.Configuration.GetSection(nameof(CodexApiConfiguration)));

            services.PostConfigure <CodexApiConfiguration>(settings =>
            {
                if (!ValidationUtil.IsObjectValid(settings))
                {
                    throw new ApplicationException("CodexApiConfiguration is invalid");
                }
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Beispiel #7
0
        public async Task <GlobalTransactionResult> TransactAsync(GlobalTransactionDto model)
        {
            if (!ValidationUtil.IsObjectValid(model))
            {
                return(GlobalTransactionResult.GeneralFailure);
            }

            // TODO: Remove this check or the one in PaymentsController
            var account = await this.bankAccountService
                          .GetByUniqueIdAsync <BankAccountConciseServiceModel>(model.DestinationBankAccountUniqueId);

            if (account == null)
            {
                return(GlobalTransactionResult.GeneralFailure);
            }

            if (account.Balance < model.Amount)
            {
                return(GlobalTransactionResult.InsufficientFunds);
            }

            var serviceModel = new TransactionCreateServiceModel
            {
                Amount      = -model.Amount,
                Source      = account.UniqueId,
                Description = model.Description ?? String.Empty,
                AccountId   = account.Id,
                DestinationBankAccountUniqueId = model.DestinationBankAccountUniqueId,
                SenderName      = account.UserFullName,
                RecipientName   = model.RecipientName,
                ReferenceNumber = ReferenceNumberGenerator.GenerateReferenceNumber()
            };

            bool success = await this.transactionService.CreateTransactionAsync(serviceModel);

            return(!success ? GlobalTransactionResult.GeneralFailure : GlobalTransactionResult.Succeeded);
        }
Beispiel #8
0
 protected bool IsEntityStateValid(object model)
 => ValidationUtil.IsObjectValid(model);
Beispiel #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContextPool <BankSystemDbContext>(options =>
                                                            options.UseSqlServer(
                                                                this.Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("BankSystem.Data")));

            services
            .Configure <CookieTempDataProviderOptions>(options => { options.Cookie.IsEssential = true; });

            services.AddIdentity <BankUser, IdentityRole>(options =>
            {
                options.Password.RequireNonAlphanumeric = false;
                options.SignIn.RequireConfirmedEmail    = true;

                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(10);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;
            })
            .AddEntityFrameworkStores <BankSystemDbContext>()
            .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.HttpOnly   = true;
                options.ExpireTimeSpan    = TimeSpan.FromMinutes(5);
                options.SlidingExpiration = true;
                options.LoginPath         = "/account/login";
                options.LogoutPath        = "/account/logout";
            });

            services
            .AddDomainServices()
            .AddApplicationServices()
            .AddCommonProjectServices()
            .AddAuthentication();

            services.Configure <SecurityStampValidatorOptions>(options => { options.ValidationInterval = TimeSpan.Zero; });

            services
            .Configure <RouteOptions>(options => options.LowercaseUrls = true);

            services
            .Configure <BankConfiguration>(
                this.Configuration.GetSection(nameof(BankConfiguration)))
            .Configure <SendGridConfiguration>(
                this.Configuration.GetSection(nameof(SendGridConfiguration)));

            services
            .PostConfigure <BankConfiguration>(settings =>
            {
                if (!ValidationUtil.IsObjectValid(settings))
                {
                    throw new ApplicationException("BankConfiguration is invalid");
                }
            })
            .PostConfigure <SendGridConfiguration>(settings =>
            {
                if (!ValidationUtil.IsObjectValid(settings))
                {
                    throw new ApplicationException("SendGridConfiguration is invalid");
                }
            });

            services
            .AddResponseCompression(options => options.EnableForHttps = true);

            services.AddMvc(options => { options.Filters.Add <AutoValidateAntiforgeryTokenAttribute>(); })
            .AddRazorPagesOptions(options => { options.Conventions.AuthorizePage("/MoneyTransfers"); })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Beispiel #10
0
        public Result FindPath(BfsServiceModel model)
        {
            if (!ValidationUtil.IsObjectValid(model))
            {
                return(null);
            }

            var startNode = model.StartNode;
            var endNode   = model.EndNode;
            var grid      = model.Grid;

            var allSteps = new HashSet <BfsNode>();
            var queue    = new Queue <BfsNode>();

            queue.Enqueue(startNode);

            while (queue.Count != 0)
            {
                var currentNode = queue.Dequeue();

                if (grid[currentNode.Row, currentNode.Col].NodeType == NodeType.Wall)
                {
                    continue;
                }

                // Destination target found
                if (currentNode.Equals(endNode))
                {
                    allSteps.Remove(allSteps.ElementAt(0));
                    var shortestPathOrder = this.GetAllNodesInShortestPathOrder(currentNode);
                    return(new Result(allSteps, shortestPathOrder));
                }

                allSteps.Add(currentNode);

                // Up
                if (currentNode.Row - 1 >= 0 &&
                    !grid[currentNode.Row - 1, currentNode.Col].IsVisited)
                {
                    AddNodeToQueue(grid, queue, currentNode, currentNode.Row - 1, currentNode.Col);
                }

                // Right
                if (currentNode.Col + 1 < grid.GetLength(1) &&
                    !grid[currentNode.Row, currentNode.Col + 1].IsVisited)
                {
                    AddNodeToQueue(grid, queue, currentNode, currentNode.Row, currentNode.Col + 1);
                }

                // Down
                if (currentNode.Row + 1 < grid.GetLength(0) &&
                    !grid[currentNode.Row + 1, currentNode.Col].IsVisited)
                {
                    AddNodeToQueue(grid, queue, currentNode, currentNode.Row + 1, currentNode.Col);
                }

                // Left
                if (currentNode.Col - 1 >= 0 &&
                    !grid[currentNode.Row, currentNode.Col - 1].IsVisited)
                {
                    AddNodeToQueue(grid, queue, currentNode, currentNode.Row, currentNode.Col - 1);
                }
            }

            return(new Result(allSteps));
        }