Exemplo n.º 1
0
        public static void SendInvitationMessages(IUrlHelper urlHelper)
        {
            IList <Account> accounts = DataRepository.GetAll <Account>();

            foreach (Account account in accounts)
            {
                var    token = GuidEncoder.Encode(account.Id.Value);
                string url   = urlHelper.Action("LogIn", "Account", new { token }, "http");

                StringBuilder body = new StringBuilder()
                                     .AppendLine($"Hey {account.DisplayName}!")
                                     .AppendLine()
                                     .Append("Santa here. Just wanted to let you know that the ")
                                     .AppendLine("Secret Santa website is ready!")
                                     .AppendLine()
                                     .Append("Please visit the address below to pick your recipient and ")
                                     .AppendLine("create your wish list.")
                                     .AppendLine()
                                     .AppendLine($"<a href=\"{url}\">Secret Santa Website</a>")
                                     .AppendLine()
                                     .AppendLine("Ho ho ho, ")
                                     .AppendLine()
                                     .AppendLine("Santa")
                                     .AppendLine();

                var from = new MailboxAddress("Santa Claus", "*****@*****.**");
                var to   = new List <MailboxAddress> {
                    new MailboxAddress(account.DisplayName, account.Email)
                };

                EmailMessage.Send(from, to, "Secret Santa Reminder", body.ToString());
            }
        }
Exemplo n.º 2
0
    private async Task SendWishListReminder(Account account, CancellationToken token)
    {
        if (account?.Id is null)
        {
            return;
        }

        var guid = GuidEncoder.Encode(account.Id.Value);
        var url  = Url.Action("LogIn", "Account", new { token = guid }, "http");
        var body = new StringBuilder()
                   .AppendFormat("Hey {0}, ", account.DisplayName).AppendLine()
                   .AppendLine()
                   .AppendFormat("Santa here. A little birdie told me you haven't added any items to your ")
                   .AppendFormat("wish list yet. Maybe you should increase your chances ")
                   .AppendFormat("of getting something you actually want by ")
                   .AppendFormat("visiting the address below! ").AppendLine()
                   .AppendLine()
                   .AppendFormat("<a href=\"{0}\">Secret Santa Website</a> ", url).AppendLine()
                   .AppendLine()
                   .AppendFormat("Ho ho ho, ").AppendLine()
                   .AppendLine()
                   .AppendFormat("Santa ").AppendLine()
                   .ToString();

        var to = new[]
Exemplo n.º 3
0
        public async Task <IActionResult> Login(string ReturnUrl, LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var signInResult = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);

                var identityUser = await _userManager.FindByEmailAsync(model.Email);

                if (signInResult.Succeeded && await _userManager.IsInRoleAsync(identityUser, "Bank Admin"))
                {
                    if (!string.IsNullOrWhiteSpace(ReturnUrl))
                    {
                        return(LocalRedirect(ReturnUrl));
                    }

                    return(RedirectToAction("Index", "AppUsers"));
                }
                else
                {
                    return(RedirectToAction("AppUserIndex", "AppUsers", new { id = GuidEncoder.Encode(identityUser.Id) }));
                }

                ModelState.AddModelError("", "Invalid Login Attempt");
            }
            return(View(model));
        }
Exemplo n.º 4
0
        public async Task <ActionResult> Delete(string id)
        {
            if (String.IsNullOrEmpty(id))
            {
                return(RedirectToAction("index", "home"));
            }

            string currentUserId = User.Identity.GetUserId();

            // only allow people to delete their own accounts
            if (currentUserId != id)
            {
                return(RedirectToAction("index", "home"));
            }

            var user = await UserManager.FindByIdAsync(id);

            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            user.EmailConfirmed = false;
            user.Logins.Clear();
            user.PhoneNumber          = null;
            user.PhoneNumberConfirmed = false;
            user.Roles.Clear();
            user.UserName      = GuidEncoder.Encode(user.Id);
            user.Email         = String.Format("{0}@disabled.com", user.UserName);
            user.IsActive      = false;
            user.CurrentPoints = 0;
            IdentityResult updateUserResult = await UserManager.UpdateAsync(user);

            return(RedirectToAction("index", "home"));
        }
        public async Task <IActionResult> EditRole(string roleId)
        {
            var decryptedId = GuidEncoder.Decode(roleId);
            var role        = await _roleManager.FindByIdAsync(decryptedId.ToString());

            if (role == null)
            {
                ViewBag.ErrorMessage = $"Role with ID = {roleId} cannot be found.";
                return(View("NotFound"));
            }
            var model = new RoleViewModel()
            {
                Id   = role.Id,
                Name = role.Name
            };

            model           = PopulateUriKey(model);
            model.UIControl = "Edit";
            foreach (var user in _userManager.Users)
            {
                if (await _userManager.IsInRoleAsync(user, role.Name))
                {
                    model.RoleUsers.Add(user.FirstName + " " + user.LastName);
                }
            }
            return(View("CreateRole", model));
        }
        public async Task <IActionResult> EditRole(RoleViewModel roleViewModel)
        {
            if (ModelState.IsValid)
            {
                var decryptedId = GuidEncoder.Decode(roleViewModel.UriKey);
                var role        = await _roleManager.FindByIdAsync(decryptedId.ToString());

                if (role == null)
                {
                    ViewBag.ErrorMessage = $"Role with ID = {role.Id} cannnot be found.";
                    return(View("NotFound"));
                }
                role.Name = roleViewModel.Name;
                var updateResult = await _roleManager.UpdateAsync(role);

                if (updateResult.Succeeded)
                {
                    RedirectToAction("Roles");
                }
                foreach (var error in updateResult.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                    return(View(roleViewModel));
                }
            }



            return(View(roleViewModel));
        }
Exemplo n.º 7
0
        public async Task <ReferralCodeServiceResult> GenerateReferralCodeForUserAsync(string userId)
        {
            Debug.Assert(!String.IsNullOrEmpty(userId));

            var code = GuidEncoder.Encode(Guid.NewGuid().ToString());

            bool success = false;

            try
            {
                db.Referrals.Add(new Referral()
                {
                    Code        = code,
                    UserId      = userId,
                    IsRedeemed  = false,
                    DateCreated = DateTime.Now
                });

                success = (await db.SaveChangesAsync()) > 0;
            }
            catch (DbUpdateException ex)
            {
                Log.Error("UserService.GenerateReferralCodeForUserAsync", ex, new { userId, code });
                ValidationDictionary.AddError(Guid.NewGuid().ToString(), ErrorMessages.ReferralCodeNotGenerated);
            }

            return(success ? ReferralCodeServiceResult.Success(code) : ReferralCodeServiceResult.Failed(ErrorMessages.ReferralCodeNotGenerated));
        }
        public async Task <ActionResult> Edit(AppUserViewModel model)
        {
            model.AppUserId = GuidEncoder.Decode(model.UriKey).ToString();
            model.SubjectId = GuidEncoder.Decode(model.SubjectId).ToString();

            try
            {
                var path = string.Format("{0}", BaseUri);
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    await _apiClient.PutAsync(path, _mapper.Map <AppUserDto>(model));

                    return(RedirectToAction(nameof(Index)));
                }
                await PopulateViewBagsAsync();

                return(View());
            }
            catch (Exception ex)
            {
                var errMsg = ex.Message;
                return(View());
            }
        }
Exemplo n.º 9
0
        public async Task <ActionResult> Edit(PricesViewModel model)
        {
            var path = string.Format("{0}/{1}",
                                     Base_Address, GuidEncoder.Decode(model.UriKey));

            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    var pathUpdate = string.Format("{0}/{1}/{2}",
                                                   AlternatePut_Address, GuidEncoder.Decode(model.UriKey), model.Price);


                    //model.PricesId = GuidEncoder.Decode(model.UriKey).ToString();
                    //await _apiClient.PutAsync(path,
                    //    _mapper.Map<PricesDto>(model));

                    await _apiClient.GetAsync <PricesDto>(pathUpdate);

                    return(RedirectToAction(nameof(Index)));
                }

                return(View("CreateEdit", model));
            }
            catch (Exception ex)
            {
                var errMsg = ex.Message;
                return(View("CreateEdit", model));
            }
        }
Exemplo n.º 10
0
        public ApprovalProcessor()
        {
            InstanceState(state => state.CurrentState);

            Event(() => Initiated);

            Event(() => Accepted);

            State(() => WaitingForApproval);

            Initially(
                When(Initiated)
                .Then((state, @event) =>
            {
                state.ApprovalId = @event.Id;
            })
                .TransitionTo(WaitingForApproval));

            During(WaitingForApproval,
                   When(WaitingForApproval.Enter)
                   .Then(state => Dispatch(new MarkApprovalAccepted
            {
                Id = state.ApprovalId,
                ReferenceNumber = GuidEncoder.Encode(Guid.NewGuid())
            })),
                   When(Accepted)
                   .Finalize());
        }
        private void DispatchCommands()
        {
            if (!_isLive || Interlocked.CompareExchange(ref _isDispatching, 1, 0) != 0)
            {
                return;
            }

            var candidates = Enumerable.Repeat(new { Id = default(Guid), CausationId = default(Guid) }, 0).ToList();

            using (var reader = _queryExecutor.ExecuteReader(TSql.QueryStatement(@"SELECT [Id], [CausationId] FROM [ApprovalProcess] WHERE [DispatchAcknowledged] = 0 AND ([Dispatched] IS NULL OR [Dispatched] < DATEADD(MINUTE, -5, GETDATE()))")))
            {
                candidates = reader.Cast <IDataRecord>()
                             .Select(record => new { Id = record.GetGuid(0), CausationId = record.GetGuid(1) })
                             .ToList();
            }

            foreach (var candidate in candidates)
            {
                var newCausationId = ApprovalProcessorConstants.DeterministicGuid.Create(candidate.CausationId);

                _bus.Publish(new MarkApprovalAccepted
                {
                    Id = candidate.Id,
                    ReferenceNumber = GuidEncoder.Encode(candidate.CausationId)
                }, context => context.SetHeader(Constants.CausationIdKey, newCausationId.ToString()));

                _queryExecutor.ExecuteNonQuery(TSql.NonQueryStatement(@"UPDATE [ApprovalProcess] SET [Dispatched] = GETDATE() WHERE [Id] = @P1", new { P1 = TSql.UniqueIdentifier(candidate.Id) }));
            }

            Interlocked.Exchange(ref _isDispatching, 0);
        }
Exemplo n.º 12
0
        public async Task <IActionResult> Registration(RegistrationViewModel newAppUserRegistration)
        {
            if (ModelState.IsValid)
            {
                var newAppUser = _mapper.Map <AppUser>(newAppUserRegistration);
                newAppUser.UserName  = newAppUserRegistration.Email;
                newAppUser.AppUserId = Guid.NewGuid().ToString();
                var createResult = await _userManager.CreateAsync(newAppUser, newAppUser.Password);

                if (createResult.Succeeded)
                {
                    if (_signInManager.IsSignedIn(User) && (User.IsInRole(("Bank Admin")) || User.IsInRole(("Bank Manager")) || User.IsInRole(("Bank Customer Advisor"))))
                    {
                        return(RedirectToAction("Index", "AppUsers"));
                    }
                    await _signInManager.SignInAsync(newAppUser, false);

                    return(RedirectToAction("AppUserIndex", "AppUsers", new { id = GuidEncoder.Encode(newAppUser.Id) }));
                }
                foreach (var error in createResult.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            return(View(newAppUserRegistration));
        }
Exemplo n.º 13
0
    private Task SendLogInEmail(Account?account, CancellationToken token)
    {
        if (account?.Id is null)
        {
            return(Task.CompletedTask);
        }

        var guid = GuidEncoder.Encode(account.Id.Value);
        var url  = Url.Action("LogIn", "Account", new { token = guid }, "http");
        var body = new StringBuilder()
                   .AppendLine($"Hey {account.DisplayName}!")
                   .AppendLine()
                   .Append("Santa here. Just sending you the log-in link ")
                   .AppendLine("you requested for the Secret Santa website. ")
                   .AppendLine()
                   .Append("Please click the link below to access the website ")
                   .AppendLine("and manage your wish list.")
                   .AppendLine()
                   .AppendLine($"<a href=\"{url}\">Secret Santa</a>")
                   .AppendLine()
                   .AppendLine("Ho ho ho, ")
                   .AppendLine()
                   .AppendLine("Santa")
                   .AppendLine();

        var to = new[]
Exemplo n.º 14
0
        public async Task <IActionResult> Edit(ProductViewModel model)
        {
            model.ProductId = GuidEncoder.Decode(model.UriKey).ToString();
            var path = string.Format("{0}/{1}", Products_Base_Address,
                                     model.ProductId);

            try
            {
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    await _appClient.PutAsync(path,
                                              _mapper.Map <ProductDto>(model));

                    //return RedirectToAction("Index");
                }

                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception ex)
            {
                var errMsg = ex.Message;
                return(View("CreateEdit", model));
            }
        }
        public async Task <IActionResult> AddOrRemoveUserInRoles(string urikey)
        {
            ViewData["UriKey"] = urikey;

            var decryptedId = GuidEncoder.Decode(urikey);
            var role        = await _roleManager.FindByIdAsync(decryptedId.ToString());

            if (role == null)
            {
                ViewBag.ErrorMessage = $"Role with ID = {urikey} cannnot be found.";
                return(View("NotFound"));
            }
            var models = new List <UserRoleViewModel>();


            //model.UIControl = "Edit";
            foreach (var user in _userManager.Users)
            {
                var userRoleviewModel = new UserRoleViewModel()
                {
                    UserId   = user.Id,
                    UserName = user.UserName
                };

                var fillIsSelected = await _userManager.IsInRoleAsync(user, role.Name) ? userRoleviewModel.IsSelected = true : userRoleviewModel.IsSelected = false;

                models.Add(userRoleviewModel);
            }

            return(View(models));
        }
Exemplo n.º 16
0
        public async Task <IActionResult> MaskPage(string id)
        {
            Guid pageMaskId;

            try
            {
                pageMaskId = GuidEncoder.Decode(id);
            }
            catch (Exception e)
            {
                if (e is ArgumentException || e is FormatException)
                {
                    return(NotFound());
                }
                throw;
            }

            var pageMask = await _repository.GetPageMaskByIdAsync(pageMaskId);

            if (pageMask == null)
            {
                return(NotFound());
            }

            var model = new MaskPageViewModel()
            {
                PageMask = pageMask,
                Url      = $"{_settings.Value.Hostname}{id}"
            };

            return(View(model));
        }
Exemplo n.º 17
0
        private string GenerateInvitationCode()
        {
            var plainText = string.Format(
                "{0}={1}&{2}={3}", IdKey, GuidEncoder.Encode(Guid.NewGuid()), InvitingTenancyKey, InvitingTenancy);

            return(GenerateCode(plainText));
        }
Exemplo n.º 18
0
    private async Task SendInvitationMessages(CancellationToken token)
    {
        var accounts = await _accountRepository.GetAllAsync(token);

        foreach (var chunk in accounts.Chunk(5))
        {
            foreach (var account in chunk)
            {
                if (account.Id is null)
                {
                    continue;
                }

                var guid = GuidEncoder.Encode(account.Id.Value);
                var url  = Url.Action("LogIn", "Account", new { token = guid }, "http");
                var body = new StringBuilder()
                           .AppendLine($"Hey {account.DisplayName}!")
                           .AppendLine()
                           .Append("Santa here. Just wanted to let you know that the ")
                           .AppendLine("Secret Santa website is ready!")
                           .AppendLine()
                           .Append("Please visit the address below to pick your recipient and ")
                           .AppendLine("create your wish list.")
                           .AppendLine()
                           .AppendLine($"<a href=\"{url}\">Secret Santa Website</a>")
                           .AppendLine()
                           .AppendLine("Ho ho ho, ")
                           .AppendLine()
                           .AppendLine("Santa")
                           .AppendLine();

                var to = new[]
Exemplo n.º 19
0
        public async Task <IEnumerable <CountryViewModel> > PopulateCountryUriKeyAsync(List <CountryViewModel> countries)
        {
            return(await Task.Run(() =>

                                  countries.Select(g => { g.UriKey = GuidEncoder.Encode(g.CountryId); return g; })
                                  ));
        }
Exemplo n.º 20
0
        public async Task <ActionResult> Create(AppUserViewModel model)
        {
            var userPath = string.Format("{0}/{1}", User_ByUserIdUri, GuidEncoder.Decode(model.UriKey));
            var user     = _mapper.Map <UserViewModel>(await _apiClient.GetAsync <UserDto>(userPath));


            var path = string.Format("{0}{1}", HttpClientProvider.HttpClient.BaseAddress, BaseUri);

            //model.SubjectId = GuidEncoder.Decode(model.UriKey).ToString();
            model.CreatedDate  = DateTime.UtcNow;
            model.ModifiedDate = DateTime.UtcNow;

            model.GenderId  = GuidEncoder.Decode(model.GenderId).ToString();
            model.CountryId = GuidEncoder.Decode(model.CountryId).ToString();

            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    model.User = user;
                    await _apiClient.PostAsync(path, _mapper.Map <AppUserDto>(model));

                    return(RedirectToAction(nameof(Index)));
                }
                return(View());
            }
            catch (Exception ex)
            {
                var msgError = ex.Message;
                return(View());
            }
        }
Exemplo n.º 21
0
        private async Task PopulateForViewBagAccountTypeToOpenForUserAsync(string userId)
        {
            //var decryptedUserId = GuidEncoder.Decode(userId).ToString();
            //var userAccts = await _accountRepository.FindAccountsByAppUserIdAsync(decryptedUserId);
            //if (userAccts == null || userAccts.Count() <= 0)
            //{

            //}
            ViewBag.Currencies = await GetCurrencsAsync();

            var decryptedAccountTypeId = GuidEncoder.Decode(userId);
            var user = await _appUserRepository.FindAppUserWithAccountAsync(GuidEncoder.Decode(userId).ToString());

            var accTypes = await GetAccountTypesAsync();

            var userAccounts = user.Accounts;

            if (userAccounts.Count > 0)
            {
                var AcctTypeIdsAllowed = accTypes.Select(x => x.AccountTypeId)
                                         .Except(userAccounts.Select(x => x.AccountTypeId));

                ViewBag.AccountTypes = accTypes.Where(x => AcctTypeIdsAllowed.Contains(x.AccountTypeId)).ToList();
            }
            else
            {
                ViewBag.AccountTypes = await GetAccountTypesAsync();
            }
        }
Exemplo n.º 22
0
        public async Task <IEnumerable <GenderViewModel> > PopulateGenderUriKeyAsync(List <GenderViewModel> genders)
        {
            return(await Task.Run(() =>

                                  genders.Select(g => { g.UriKey = GuidEncoder.Encode(g.GenderId); return g; })
                                  ));
        }
Exemplo n.º 23
0
        private AccountViewModel PopulateUriKey(AccountViewModel model)
        {
            model.UriKey = GuidEncoder.Encode(model.AccountId.ToString());


            return(model);
        }
Exemplo n.º 24
0
        public async Task <IActionResult> DebitAccount(string id)
        {
            //needs to implement update function

            var decryptedId = GuidEncoder.Decode(id);
            var account     = await _accountRepository.FindAsync(decryptedId.ToString());

            if (!account.IsBlocked)
            {
                ViewBag.AccountTypesLeftForfundTransfer = await _accountTypeRepository.FindAllAccountTypesByAccountTypeIdAsync(account.AccountTypeId);

                ViewBag.OrderByTypes = await GetOrderByTypesAsync();

                ViewBag.TransactionTypes = await GetTransactionTypeAsync();

                var newTransaction = new AccountTransactionViewModel()
                {
                    AccUriKey           = GuidEncoder.Encode(account.AccountId),
                    AppUserUriKey       = GuidEncoder.Encode(account.AppUserId),
                    IdUriKey            = GuidEncoder.Encode(account.Id),
                    AccountTypeIdUriKey = GuidEncoder.Encode(account.AccountTypeId),
                    UiControl           = "Debit"
                };



                return(View("TransferFund", newTransaction));
            }
            //Todo: more informative view
            return(View());
        }
Exemplo n.º 25
0
        public async Task <IActionResult> Edit(AccountViewModel model)
        {
            CancellationToken cancellation = new CancellationToken();

            if (ModelState.IsValid)
            {
                var updateAcct = await _accountRepository.FindAsync(GuidEncoder.Decode(model.UriKey).ToString());

                //updates
                updateAcct.CurrentBalance = model.CurrentBalance;
                //updateAcct.IsBlocked = model.IsBlocked;

                var acc = await _unitOfWorkAccount.UpdateAsync(cancellation, _mapper.Map <Account>(updateAcct));

                var identityUser = await _userManager.FindByIdAsync(acc.Id);

                if (await _userManager.IsInRoleAsync(identityUser, "Bank Admin") || await _userManager.IsInRoleAsync(identityUser, "Bank Manager"))
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(RedirectToAction("UserAccountsByAccountId", new{ id = GuidEncoder.Encode(acc.AccountId) }));
                }
            }


            return(View());
        }
Exemplo n.º 26
0
        public async Task <IActionResult> Create(AccountViewModel model)
        {
            CancellationToken cancellation = new CancellationToken();

            if (ModelState.IsValid)
            {
                var appUser = await _appUserRepository.FindAsync(GuidEncoder.Decode(model.UriKey).ToString());

                model.Id             = appUser.Id;
                model.AppUserId      = appUser.AppUserId;
                model.OpeningDate    = DateTime.UtcNow;
                model.CurrentBalance = model.OpeningBalance;

                model.PersonalAccountNumber = Guid.NewGuid().ToString();
                model = await _setAccounRate.SetRateAsync(model);

                await _accountRepository.AddAsync(_mapper.Map <Account>(model));

                await _unitOfWorkAccount.CommitAsync(cancellation);

                return(RedirectToAction("Index"));
            }


            return(View());
        }
Exemplo n.º 27
0
 public SerializableVirtualTextureLayer(SerializableVirtualTextureLayer other)
 {
     this.layerName        = other.layerName;
     this.guid             = Guid.NewGuid();
     this.layerRefName     = $"Layer_{GuidEncoder.Encode(this.guid)}";
     this.layerTexture     = other.layerTexture;
     this.layerTextureType = LayerTextureType.Default;
 }
Exemplo n.º 28
0
 public SerializableVirtualTextureLayer(string name, SerializableTexture texture)
 {
     this.layerName        = name;
     this.guid             = Guid.NewGuid();
     this.layerRefName     = $"Layer_{GuidEncoder.Encode(this.guid)}";
     this.layerTexture     = texture;
     this.layerTextureType = LayerTextureType.Default;
 }
Exemplo n.º 29
0
 // GET: OrderItems/Details/5
 public async Task<ActionResult> Details(string id)
 {
     var path = string.Format("{0}/{1}", Base_Address,
         GuidEncoder.Decode(id));
     var orderItem = _mapper.Map<OrderItemViewModel>(await _apiClient.GetAsync<OrderItemDto>(path));
     orderItem.UriKey = GuidEncoder.Encode(orderItem.OrderItemId);
     return View(orderItem);
 }
        public async Task <ActionResult> WelcomeNewUser(string emailId)
        {
            var path = string.Format("{0}/{1}", UsersBaseUri, emailId);
            var user = _mapper.Map <UserViewModel>(await _apiClient.GetAsync <UserDto>(path));

            user.UriKey = GuidEncoder.Encode(user.SubjectId);
            return(View(user));
        }