public async Task <IActionResult> CreateWallet()
        {
            System.Security.Claims.ClaimsPrincipal currentUser = User;
            var UserId = _userManager.GetUserId(currentUser);
            // Reference logged in User
            ApplicationUser LoggedInUser = await _userManager.FindByIdAsync(UserId);

            var walletAddress = (
                from w in _context.Wallets
                where w.Username == LoggedInUser.UserName
                select w.publicAddress).FirstOrDefault();

            if (walletAddress == null)
            {
                Wallet newWallet = _flipChain.CreateAndStoreWalletInDatabase(LoggedInUser.UserName, LoggedInUser.Email);
                ViewBag.walletAddress = newWallet.publicAddress;
                _notyf.Success($"Wallet {newWallet.publicAddress} created!");
            }
            else
            {
                ViewBag.newWalletAddress = $"Wallet for user {LoggedInUser.UserName} already exists.";
                ViewBag.walletAddress    = walletAddress;
                _notyf.Error($"Wallet for user {LoggedInUser.UserName} already exists!");
            }

            var wallet = (from w in _context.Wallets
                          where w.Username == LoggedInUser.UserName
                          select w).FirstOrDefault();

            return(View("Wallet", wallet));
        }
Beispiel #2
0
        public async Task <IActionResult> _AddQualification(LearnerCourse learnerCourse)
        {
            //Get current user details
            var user = await _lookUpService.GetCurrentLoggedInUser(User.Identity.Name);

            //Get currect leaner details
            var learner = await _lookUpService.GetLearnerDetailsByIdEmail(user.Person.NationalId);

            //assign Leaner Id to link these qualifications to leaner
            learnerCourse.LearnerId = learner.LearnerId;

            //create an audit trail
            learnerCourse.CreatedBy   = user.UserName;
            learnerCourse.DateCreated = DateTime.Now;

            if (ModelState.IsValid)
            {
                _context.Add(learnerCourse);
                await _context.SaveChangesAsync();

                _notyf.Success("Qualification added successfully...");
                return(RedirectToAction(nameof(Index)));
            }
            return(PartialView(learnerCourse));
        }
        public async Task <IActionResult> CreateRole(CreateRoleViewModel model)
        {
            if (ModelState.IsValid)
            {
                // We just need to specify a unique role name to create a new role
                IdentityRole identityRole = new IdentityRole
                {
                    Name = model.RoleName
                };

                // Saves the role in the underlying AspNetRoles table
                IdentityResult result = await roleManager.CreateAsync(identityRole);

                if (result.Succeeded)
                {
                    _notyf.Success("Role Added Succefully 😍");
                    //_notyf.Success("Item added to your Cart Successfuly 😍");
                    //_notyf.Custom("Custom Notification - closes in 5 seconds.", 5, "whitesmoke", "fa fa-gear");
                    //_notyf.Custom("Custom Notification - closes in 5 seconds.", 10, "#B600FF", "fa fa-home");

                    return(RedirectToAction("ListRoles"));
                }

                foreach (IdentityError error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }

            return(View(model));
        }
        public async Task <IActionResult> Login(LoginRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(View(request));
            }

            var result = await _userApiClient.Authenticate(request);

            if (result.ResultObj == null)
            {
                ModelState.AddModelError("", result.Message);
                return(View());
            }

            var userPrincipal = this.ValidateToken(result.ResultObj);

            //xác thực và thời hạn của phiên đăng nhập
            var authProperties = new AuthenticationProperties
            {
                ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(20),

                IsPersistent = false
            };

            HttpContext.Session.SetString(SystemConstants.AppSettings.Token, result.ResultObj);

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, authProperties);

            _notyf.Success($"Xin chào {request.UserName}");
            return(RedirectToAction("Index", "Home"));
        }
Beispiel #5
0
        public async Task <IActionResult> Create(string name, int kitchen, int toilet, int room)
        {
            if (ModelState.IsValid)
            {
                var apartment = new Apartment
                {
                    Name    = name,
                    Kitchen = kitchen,
                    Toilet  = toilet,
                    Room    = room
                };
                var addApartment = await _data.CreateApartmentAsync(apartment, _user.UserName);

                if (addApartment == true)
                {
                    _notyf.Success("Apartment added successfully!");
                    //return RedirectToAction(nameof(Index), TempData["user"] = _user.UserName);
                    var vM = new GetApartmentsViewModel
                    {
                        Apartments    = await _data.GetApartmentsAsync(_user.Id),
                        Contributions = await _data.GetUserContributionsAsync(_user.Id)
                    };
                    return(PartialView("GetApartments", vM));
                }
                _notyf.Error("Something went wrong :( ");
                return(PartialView());
            }
            _notyf.Warning("Insert all fields!!");
            return(PartialView());
        }
Beispiel #6
0
 public IActionResult Index()
 {
     _notyf.Success("Success Notification");
     _notyf.Success("Success Notification that closes in 10 Seconds.", 3);
     _notyf.Error("Some Error Message");
     _notyf.Warning("Some Error Message");
     _notyf.Information("Information Notification - closes in 4 seconds.", 4);
     _notyf.Custom("Custom Notification - closes in 5 seconds.", 5, "whitesmoke", "fa fa-gear");
     _notyf.Custom("Custom Notification - closes in 5 seconds.", 10, "#B600FF", "fa fa-home");
     return(View());
 }
Beispiel #7
0
        public IActionResult InsertOrUpdateInstitutionType(InstitutionType institutionType)
        {
            Action action = Action.None;

            if (ModelState.IsValid)
            {
                if (institutionType.Id == 0)
                {
                    action = Action.Create;
                    _unitWork.InstitutionType.Add(institutionType);
                }
                else
                {
                    action = Action.Update;
                    _unitWork.InstitutionType.Update(institutionType);
                }

                try
                {
                    _unitWork.Save();

                    if (action == Action.Create)
                    {
                        _notyfService.Success("Tipo de institución creada correctamente.");
                    }
                    if (action == Action.Update)
                    {
                        _notyfService.Success("Tipo de institución actualizada correctamente.");
                    }

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateException dbUpdateException)
                {
                    if (dbUpdateException.InnerException.Message.Contains("IX_InstitutionTypes_Name"))
                    {
                        _notyfService.Error("Ya existe un tipo de institución con el mismo nombre.");

                        return(View(institutionType));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, dbUpdateException.InnerException.Message);
                    }
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError(string.Empty, exception.Message);
                }
            }

            return(View(institutionType));
        }
Beispiel #8
0
        public IActionResult InsertOrUpdateSubmodality(Submodality submodality)
        {
            if (ModelState.IsValid)
            {
                Action action = Action.None;
                if (submodality.Id == 0)
                {
                    action = Action.Create;
                    _unitWork.Submodality.Add(submodality);
                }
                else
                {
                    action = Action.Update;
                    _unitWork.Submodality.Update(submodality);
                }

                try
                {
                    _unitWork.Save();

                    if (action == Action.Create)
                    {
                        _notyfService.Success("Submodalidad creada correctamente.");
                    }
                    if (action == Action.Update)
                    {
                        _notyfService.Success("Submodalidad actualizada correctamente.");
                    }

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateException dbUpdateException)
                {
                    if (dbUpdateException.InnerException.Message.Contains("IX_Submodalities_Name"))
                    {
                        _notyfService.Error("Ya existe una submodalidad con el mismo nombre.");

                        return(View(submodality));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, dbUpdateException.InnerException.Message);
                    }
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError(string.Empty, exception.Message);
                }
            }

            return(View(submodality));
        }
Beispiel #9
0
        public IActionResult InsertOrUpdateGender(Gender gender)
        {
            if (ModelState.IsValid)
            {
                Action action = Action.None;
                if (gender.Id == 0)
                {
                    action = Action.Create;
                    _unitWork.Gender.Add(gender);
                }
                else
                {
                    action = Action.Update;
                    _unitWork.Gender.Update(gender);
                }
                try
                {
                    _unitWork.Save();

                    if (action == Action.Create)
                    {
                        _notyfService.Success("Género creado correctamente.");
                    }
                    if (action == Action.Update)
                    {
                        _notyfService.Success("Género actualizado correctamente.");
                    }

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateException dbUpdateException)
                {
                    if (dbUpdateException.InnerException.Message.Contains("IX_Genders_Name"))
                    {
                        _notyfService.Error("Ya existe un Género con el mismo nombre.");

                        return(View(gender));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, dbUpdateException.InnerException.Message);
                    }
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError(string.Empty, exception.Message);
                }
            }

            return(View(gender));
        }
Beispiel #10
0
        public IActionResult InsertOrUpdateTeachingFunction(TeachingFunction teachingFunction)
        {
            if (ModelState.IsValid)
            {
                Action action = Action.None;
                if (teachingFunction.Id == 0)
                {
                    action = Action.Create;
                    _unitWork.TeachingFunction.Add(teachingFunction);
                }
                else
                {
                    action = Action.Update;
                    _unitWork.TeachingFunction.Update(teachingFunction);
                }
                try
                {
                    _unitWork.Save();

                    if (action == Action.Create)
                    {
                        _notyfService.Success("Función docente creada correctamente.");
                    }
                    if (action == Action.Update)
                    {
                        _notyfService.Success("Función docente actualizada correctamente.");
                    }

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateException dbUpdateException)
                {
                    if (dbUpdateException.InnerException.Message.Contains("IX_TeachingFunctions_Name"))
                    {
                        _notyfService.Error("Ya existe una función docente con el mismo nombre.");

                        return(View(teachingFunction));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, dbUpdateException.InnerException.Message);
                    }
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError(string.Empty, exception.Message);
                }
            }

            return(View(teachingFunction));
        }
Beispiel #11
0
        public async Task <IActionResult> Create([Bind("CityId,CityName,CityCode,ProvinceId,CreatedBy,DateCreated,LastUpdatedBy,DateUpdated")] City city)
        {
            if (ModelState.IsValid)
            {
                _context.Add(city);
                await _context.SaveChangesAsync();

                _notyf.Success("Created successfully...");
                _notyf.Custom("Edited ", 10, "green", "user");
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ProvinceId"] = new SelectList(_context.Province, "ProvinceId", "ProvinceName", city.ProvinceId);
            return(PartialView(city));
        }
Beispiel #12
0
        public async Task <IActionResult> Create([Bind("ProductId,ProductName,Category,UnitPrice,StockQty")] Products products)
        {
            if (ModelState.IsValid)
            {
                _context.Add(products);
                await _context.SaveChangesAsync();

                await _hub.Clients.All.SendAsync("LoadProducts");

                _notyf.Custom("Create Succussfully- closes in 5 seconds.", 5, "whitesmoke", "fa fa-gear");
                _notyf.Success("Success that closes in 10 Seconds.", 3);
                return(RedirectToAction(nameof(Index)));
            }
            _notyf.Warning("Some Error Message");
            return(View(products));
        }
Beispiel #13
0
        public async Task <IActionResult> ImportData(FileDTO fileDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    string messages = string.Join("; ", ModelState.Values
                                                  .SelectMany(x => x.Errors)
                                                  .Select(x => x.ErrorMessage));
                    throw new Exception("Please correct the following errors: " + Environment.NewLine + messages);
                }
                //Upload the Excel Spreadsheet of learners
                var path = _fileService.UploadFile(fileDto.File, _foldersConfigation.Uploads);

                //import the data
                if (path != null)
                {
                    await _dataService.ImportExcelForLearners(path);

                    _notyf.Success("File uploaded successfully...");
                }
                else
                {
                    _notyf.Error("Invalid file uploaded");
                    return(Json(new { Result = "ERROR", Message = "Invalid file uploaded" }));
                }
                return(Json(new { Result = "OK" }));
            }
            catch (Exception ex)
            {
                _notyf.Error("Something went wrong : " + ex.Message);
                return(Json(new { Result = "ERROR", Message = ex.Message }));
            }
        }
Beispiel #14
0
        public IActionResult Details(int id)
        {
            _logger.LogInformation(DateTime.Now.ToString("dd.MM.yyyy, HH:mm:ss"));
            var campaign    = _context.Campaigns.Find(id);
            var achieveGood = new UserAchievementsModel
            {
                UserId        = _userManager.GetUserId(this.User),
                AchievementId = _context.Achievements.Where(x => x.Name == "Good start").First().Id,
                GetDate       = DateTime.Now
            };
            var achieveSad = new UserAchievementsModel
            {
                UserId        = _userManager.GetUserId(this.User),
                AchievementId = _context.Achievements.Where(x => x.Name == "It could be worse...").First().Id,
                GetDate       = DateTime.Now
            };
            var isUserHasAcvhieveGood = _context.UserAchievements.Where(x => x.UserId == achieveGood.UserId && x.AchievementId == achieveGood.AchievementId).Any();
            var isUserHasAcvhieveSad  = _context.UserAchievements.Where(x => x.UserId == achieveSad.UserId && x.AchievementId == achieveSad.AchievementId).Any();

            if (campaign.EndTime < DateTime.Now)
            {
                campaign.Ended = true;
                var isGoodEnd = campaign.RemainSum >= campaign.TotalSum;
                if (!isUserHasAcvhieveGood && isGoodEnd)
                {
                    _context.UserAchievements.Add(achieveGood);
                    _notyfService.Success("You got new achievement!");
                }
                else if (!isUserHasAcvhieveSad && !isGoodEnd)
                {
                    _context.UserAchievements.Add(achieveSad);
                    _notyfService.Success("You got new achievement!");
                }
                _context.SaveChanges();
            }
            var commentVm = new CommentViewModel
            {
                Campaign = _context.Campaigns.Find(id),
                Comments = _context.Comments.ToList(),
                Rating   = new Rating
                {
                    CampaignId = id
                }
            };

            return(View(commentVm));
        }
Beispiel #15
0
 public IActionResult Index()
 {
     _notyf.Success("Success Notification");
     _notyf.Error("Some Error Message");
     _notyf.Information("Information Notification - closes in 4 seconds.", 4);
     _notyf.Custom("Custom Notification <br><b><i>closes in 5 seconds.</i></b></p>", 5, "indigo", "fa fa-gear");
     return(View());
 }
        public async Task <IActionResult> Create([FromForm] ProductCategoryCreateRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(View(request));
            }
            var result = await _categoryApiClient.CreateCategory(request);

            if (result)
            {
                //TempData["result"] = "Thêm mới danh mục sản phẩm thành công";
                _notyf.Success("Thêm mới danh mục sản phẩm thành công");
                return(RedirectToAction("Index"));
            }

            ModelState.AddModelError("", "Thêm danh mục sản phẩm thất bại");
            return(View(request));
        }
Beispiel #17
0
        public async Task <IActionResult> Create(RegisterRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(View(request));
            }
            request.origin = Request.Headers["origin"];
            var result = await _userApiClient.RegisterUser(request);

            if (result.IsSuccessed)
            {
                //TempData["result"] = "Thêm mới tài khoản quản trị thành công";
                _notyf.Success("Thêm mới tài khoản quản trị thành công");
                return(RedirectToAction("Index"));
            }

            ModelState.AddModelError("", result.Message);

            return(View(request));
        }
Beispiel #18
0
        public IActionResult InsertOrUpdateSolicitude(Solicitude solicitude)
        {
            if (ModelState.IsValid)
            {
                Action action = Action.None;
                solicitude.ActDate = DateTime.Parse(Convert.ToString(Request.Form["ActDate"]));

                if (solicitude.Id == 0)
                {
                    action = Action.Create;
                    _unitWork.Solicitude.Add(solicitude);
                }
                else
                {
                    action = Action.Update;
                    _unitWork.Solicitude.Update(solicitude);
                }

                try
                {
                    _unitWork.Save();

                    if (action == Action.Create)
                    {
                        _notyfService.Success("Solicitud trabajo de grado creada correctamente.");
                    }
                    if (action == Action.Update)
                    {
                        _notyfService.Success("Solicitud trabajo de grado actualizada correctamente.");
                    }

                    return(RedirectToAction(nameof(Index)));
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError(string.Empty, exception.Message);
                }
            }

            return(View(solicitude));
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var currentUser = await _userManager.FindByEmailAsync(Input.Gebruikersnaam);

                if (currentUser == null)
                {
                    ModelState.AddModelError(string.Empty, "Geen geldidge inloggegevens.");
                    return(Page());
                }

                var result = await _signInManager.PasswordSignInAsync(currentUser, Input.Wachtwoord, Input.Wachtwoord_onthouden, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User ingelogd.");
                    _notyf.Success("Logged in succesful", 3);
                    _dbContext.GebruikerLogins.Add(new GebruikerLogin {
                        Datum_TijdStip = DateTime.UtcNow, LoginResult = LoginResult.GELUKT, Username = currentUser.Email
                    });
                    _dbContext.SaveChanges();
                    return(LocalRedirect(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.Wachtwoord_onthouden }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("Account geblokkeerd");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    _dbContext.GebruikerLogins.Add(new GebruikerLogin {
                        Datum_TijdStip = DateTime.UtcNow, LoginResult = LoginResult.MISLUKT, Username = currentUser.Email
                    });
                    _dbContext.SaveChanges();
                    ModelState.AddModelError(string.Empty, "Geen geldige inloggegevens.");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Beispiel #20
0
        public async Task <IActionResult> _Verify(Guid id, [Bind("Id,FilePath,FileName,DocumentTypeId,Comments,LearnerId")] Document document)
        {
            if (id != document.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                document.Verified         = Const.TRUE;
                document.VerifiedBy       = User.Identity.Name;
                document.VerificationDate = DateTime.Now;
                document.LastUpdatedBy    = User.Identity.Name;
                document.DateUpdated      = DateTime.Now;

                try
                {
                    _context.Update(document);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!FileExists(document.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                _notyf.Success("Document verified successfully....");
                var user = await _lookUpService.GetCurrentLoggedInUser(User.Identity.Name);

                return(RedirectToAction("Details", "Person", new { id = user.Person.NationalId }));
            }

            return(View(document));
        }
 public IActionResult Register(string nick, string email, string password)
 {
     if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(nick) && !string.IsNullOrEmpty(password))
     {
         var result = _data.RegisterAsync(email, nick, password);
         if (result.Result.Equals("Success"))
         {
             _notyf.Success("Welcome to our service");
             TempData["user"] = nick;
             return(RedirectToAction("Index", "Logged"));
         }
         if (result.Result.Equals("exists"))
         {
             _notyf.Error("User with this email or nick name already exists");
             return(RedirectToAction(nameof(Index)));
         }
         _notyf.Error(result.Result);
         return(RedirectToAction(nameof(Index)));
     }
     _notyf.Error("Fill all fields!");
     return(RedirectToAction(nameof(Index)));
 }
Beispiel #22
0
        public async Task <IActionResult> Login(LoginDTO input)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var messages = string.Join("; ", ModelState.Values
                                               .SelectMany(x => x.Errors)
                                               .Select(x => x.ErrorMessage));
                    throw new Exception("Please correct the following errors: " + Environment.NewLine + messages);
                }

                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result =
                    await _signInManager.PasswordSignInAsync(input.Username, input.Password, input.RememberMe, false);

                if (result.Succeeded)
                {
                    var person = _lookUpService.GetPersonDetailsByUsername(input.Username).Result;

                    var user = await _userManager.Users.FirstOrDefaultAsync(a => a.UserName.Equals(input.Username));

                    var userRole = await _userManager.GetRolesAsync(user);

                    if (userRole.ToList()[0].Equals(Const.ADMINISTRATOR_USER))
                    {
                        return(RedirectToRoute("", new { controller = "Dashboard", action = "Index" }));
                    }

                    if (person == null)
                    {
                        _notyf.Warning("User logged out successful...", 10);
                        return(RedirectToRoute("", new { controller = "Person", action = "CreateAccount" }));
                    }

                    _notyf.Success("Login was successful", 10);
                    return(RedirectToRoute("", new { controller = "Person", action = "Details", Id = person.NationalID }));
                }

                _notyf.Error("Login for " + input.Username + " failed...", 10);

                return(View(input));
            }
            catch (Exception ex)
            {
                _notyf.Error("Something went wrong...");
                return(Json(new { Result = "ERROR", ex.Message }));
            }
        }
 public IActionResult Create(ContractEditViewModel cevm, Klant klant)
 {
     if (ModelState.IsValid)
     {
         try
         {
             Contract     contract = new Contract();
             ContractType type     = _contractTypeRepository.GetContractType(cevm.ContractTypeId);
             MapContractEditViewModelToContract(cevm, contract);
             contract.ContractType = type;
             klant.VoegContractToe(contract);
             _gebruikerRepository.SaveChanges();
             _notyf.Success($"Succesvol {contract.ContractTitel} aangemaakt!");
         }
         catch
         {
             _notyf.Error("Oops.. contract is niet aangemaakt. Probeer opnieuw.");
         }
         return(RedirectToAction(nameof(Index)));
     }
     ViewData["contractTypes"] = GetContractTypesAsSelectList();
     return(View(nameof(Create), cevm));
 }
Beispiel #24
0
 public IActionResult Create(TicketEditViewModel tevm, Klant klant)
 {
     if (ModelState.IsValid)
     {
         try
         {
             Ticket ticket = new Ticket();
             MapTicketEditViewModelToTicket(tevm, ticket);
             TicketType ticketType = _ticketTypeRepository.GetBy(tevm.TicketTypeId);
             ticket.TicketType = ticketType;
             klant.AddTicketByContractId(tevm.ContractId, ticket);
             _gebruikerRepository.SaveChanges();
             _notyf.Success("Ticket succesvol aangemaakt", 3);
         }
         catch
         {
             _notyf.Error("Er is iets misgelopen. Probeer opnieuw.", 3);
         }
         return(RedirectToAction(nameof(Index)));
     }
     ViewData["IsEdit"]      = false;
     ViewData["ticketTypes"] = GetTicketTypesAsSelectList();
     return(View(nameof(Edit), tevm));
 }
        public async Task<IActionResult> Edit(string id,[Bind("LearnerId,PersonId,SchoolId,SchoolGradeId,MotivationText,YearSchoolCompleted,CreatedBy,DateCreated,LastUpdatedBy,DateUpdated,RecruitedYn,AppliedYn,Person,School,SchoolGrade")] Learner learner)
        {
            if (learner.Person == null )
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                learner.Person.LastUpdatedBy = "admin";
                learner.Person.DateUpdated = DateTime.Now;
                
               //  lnr.LearnerCourse.AddRange(lnr.LearnerCourse);
              try
                {
                     _context.Update(learner);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PersonExists(learner.Person.NationalId) && !AddressExists(learner.Person.Address.FirstOrDefault().AddressId))
                    {
                        return NotFound();
                    } 
                    else
                    {
                        throw;
                    }
                }
              _notyf.Success("Your details were edited successfully...");
                return RedirectToAction(nameof(Index));
            }
            ViewData["CitizenshipStatusId"] = new SelectList(_context.CitizenshipStatus, "CitizenshipStatusId", "CitizenshipStatusDesc", learner.Person.CitizenshipStatusId);
            ViewData["DisabilityStatusId"] = new SelectList(_context.DisabilityStatus, "DisabilityStatusId", "DisabilityStatusDesc", learner.Person.DisabilityStatusId);
            ViewData["EquityId"] = new SelectList(_context.Equity, "EquityId", "EquityDesc", learner.Person.EquityId);
            ViewData["GenderId"] = new SelectList(_context.Gender, "GenderId", "GenderDesc", learner.Person.GenderId);
            ViewData["HomeLanguageId"] = new SelectList(_context.HomeLanguage, "HomeLanguageId", "HomeLanguageDesc", learner.Person.HomeLanguageId);
            ViewData["NationalityId"] = new SelectList(_context.Nationality, "NationalityId", "NationalityDesc", learner.Person.NationalityId);
            ViewData["CityId"] = new SelectList(_context.City, "CityId", "CityName", learner.Person.Address.FirstOrDefault().CityId);
            ViewData["SuburbId"] = new SelectList(_context.Suburb, "SuburbId", "SuburbName", learner.Person.Address.FirstOrDefault().SuburbId);
            ViewData["CourseId"] = new SelectList(_context.Course, "CourseId", "CourseTitle");  
            ViewData["CountryId"] = new SelectList(_context.Country, "CountryId", "CountryName", learner.Person.Address.FirstOrDefault().CountryId);
            ViewData["ProvinceId"] = new SelectList(_context.Province, "ProvinceId", "ProvinceName", learner.Person.Address.FirstOrDefault().ProvinceId);
            ViewData["AddressTypeId"] = new SelectList(_context.AddressType, "AddressTypeId", "AddressTypeName", learner.Person.Address.FirstOrDefault().AddressTypeId);
            ViewData["SchoolId"] = new SelectList(_context.School, "SchoolId", "SchoolName", learner.SchoolId);
            ViewData["SchoolGradeId"] = new SelectList(_context.SchoolGrade, "SchoolGradeId", "SchoolGradeName", learner.SchoolGradeId);
            return View(learner);
        }
        public async Task <IActionResult> CreateAsync(Campaign campaign)
        {
            if (ModelState.IsValid)
            {
                if (campaign.ImageFile != null)
                {
                    var    file     = campaign.ImageFile;
                    string filePath = await _cloudStorage.GetFilePathAsync(file);

                    var uri = _cloudStorage.UploadImage(filePath);
                    campaign.ImageUrl = uri.ToString();
                }
                else
                {
                    campaign.ImageUrl = "https://res.cloudinary.com/dwivxsl5s/image/upload/v1621205266/no-img_if8frz.jpg";
                }

                campaign.Author    = _userManager.GetUserName(this.User);
                campaign.UserId    = _userManager.GetUserId(this.User);
                campaign.BeginTime = DateTime.Now;
                campaign.RemainSum = 0;
                var achieve = new UserAchievementsModel
                {
                    UserId        = _userManager.GetUserId(this.User),
                    AchievementId = _context.Achievements.Where(x => x.Name == "That's only the beginning!").First().Id,
                    GetDate       = DateTime.Now
                };
                var campaignsCurrentUserCount = _context.Campaigns.Where(x => x.Author == campaign.Author).Count();
                var isUserHasAcvhieve         = _context.UserAchievements.Where(x => x.UserId == achieve.UserId && x.AchievementId == achieve.AchievementId).Any();
                if (!isUserHasAcvhieve && campaignsCurrentUserCount < 1)
                {
                    _context.UserAchievements.Add(achieve);
                    _notyfService.Success("You got new achievement!");
                }
                _context.Campaigns.Add(campaign);
                _context.SaveChanges();
            }
            return(RedirectPermanent("~/Home/Index"));
        }
Beispiel #27
0
        public void AddGenesisBlock()
        {
            // Check if GenesisBlock already exists
            var Block = (
                from r in _context.Blocks
                select r).FirstOrDefault();

            if (Block == null)
            {
                // Create GenesisBlock
                Block GenesisBlock = CreateGenesisBlock();
                // Save GenesisBlock in database
                StoreBlockInDatabase(GenesisBlock);

                _notyf.Success("Genesis Block added to Database!");
            }
            else
            {
                _notyf.Error("Genesis Block already exists!");
            }
        }
Beispiel #28
0
        public IActionResult InsertOrUpdateCareerPerson(CareerPersonViewModel careerPersonViewModel)
        {
            if (ModelState.IsValid)
            {
                Action action = Action.None;
                if (careerPersonViewModel.CareerPerson.Id == 0)
                {
                    action = Action.Create;
                    _unitWork.CareerPerson.Add(careerPersonViewModel.CareerPerson);
                }
                else
                {
                    action = Action.Update;
                    _unitWork.CareerPerson.Update(careerPersonViewModel.CareerPerson);
                }

                try
                {
                    _unitWork.Save();
                    if (action == Action.Create)
                    {
                        _notyfService.Success("Programa Persona creado correctamente.");
                    }
                    if (action == Action.Update)
                    {
                        _notyfService.Success("Programa Persona actualizado correctamente.");
                    }

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateException dbUpdateException)
                {
                    if (dbUpdateException.InnerException.Message.Contains("IX_CareerPeople_CareerId_PersonId"))
                    {
                        _notyfService.Error("Ya existe una Persona con el mismo programa.");

                        careerPersonViewModel.CareerList = _unitWork.Career.GetAll().Select(ca => new SelectListItem
                        {
                            Text  = ca.Name,
                            Value = ca.Id.ToString()
                        });

                        careerPersonViewModel.PersonList = _unitWork.Person.GetAll().Select(pe => new SelectListItem
                        {
                            Text  = pe.Names + " " + pe.Surnames,
                            Value = pe.Id.ToString()
                        }).ToList();

                        return(View(careerPersonViewModel));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, dbUpdateException.InnerException.Message);
                    }
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError(string.Empty, exception.Message);
                }
            }
            else
            {
                careerPersonViewModel.CareerList = _unitWork.Career.GetAll().Select(ca => new SelectListItem
                {
                    Text  = ca.Name,
                    Value = ca.Id.ToString()
                });

                careerPersonViewModel.PersonList = _unitWork.Person.GetAll(orderBy: pe => pe.OrderBy(pe => pe.Surnames + pe.Names)).Select(pe => new SelectListItem
                {
                    Text  = pe.Names + " " + pe.Surnames,
                    Value = pe.Id.ToString()
                });

                if (careerPersonViewModel.CareerPerson.Id != 0)
                {
                    careerPersonViewModel.CareerPerson = _unitWork.CareerPerson.Get(careerPersonViewModel.CareerPerson.Id);
                }
            }
            return(View(careerPersonViewModel));
        }
Beispiel #29
0
        public IActionResult InsertOrUpdatePerson(PersonViewModel personViewModel)
        {
            personViewModel.Person.DepartmentId = Convert.ToInt32(Request.Form["DepartmentId"]);
            personViewModel.Person.CityId       = Convert.ToInt32(Request.Form["CityId"]);

            if (ModelState.IsValid)
            {
                Action action = Action.None;
                if (personViewModel.Person.Id == 0)
                {
                    action = Action.Create;
                    _unitWork.Person.Add(personViewModel.Person);
                }
                else
                {
                    action = Action.Update;
                    _unitWork.Person.Update(personViewModel.Person);
                }

                try
                {
                    _unitWork.Save();
                    if (action == Action.Create)
                    {
                        _notyfService.Success("Persona creada correctamente.");
                    }
                    if (action == Action.Update)
                    {
                        _notyfService.Success("Persona actualizada correctamente.");
                    }

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateException dbUpdateException)
                {
                    if (dbUpdateException.InnerException.Message.Contains("IX_People_IdentificationNumber"))
                    {
                        _notyfService.Error("Ya existe una Persona con el mismo número de identificacxión.");


                        personViewModel.IdentityDocumentTypeList = _unitWork.IdentityDocumentType.GetAll().Select(idt => new SelectListItem
                        {
                            Text  = idt.Name,
                            Value = idt.Id.ToString()
                        });

                        personViewModel.GenderList = _unitWork.Gender.GetAll().Select(ge => new SelectListItem
                        {
                            Text  = ge.Name,
                            Value = ge.Id.ToString()
                        });

                        personViewModel.DepartmentList = _unitWork.Department.GetAll().Select(d => new SelectListItem
                        {
                            Text  = d.Name,
                            Value = d.Id.ToString()
                        });

                        personViewModel.CityList = _unitWork.City.GetAll().OrderBy(ci => ci.Name).Select(ci => new SelectListItem
                        {
                            Text  = ci.Name,
                            Value = ci.Id.ToString()
                        });

                        return(View(personViewModel));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, dbUpdateException.InnerException.Message);
                    }
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError(string.Empty, exception.Message);
                }
            }
            else
            {
                personViewModel.IdentityDocumentTypeList = _unitWork.IdentityDocumentType.GetAll().Select(idt => new SelectListItem
                {
                    Text  = idt.Name,
                    Value = idt.Id.ToString()
                });

                personViewModel.GenderList = _unitWork.Gender.GetAll().Select(ge => new SelectListItem
                {
                    Text  = ge.Name,
                    Value = ge.Id.ToString()
                });

                personViewModel.DepartmentList = _unitWork.Department.GetAll().Select(d => new SelectListItem
                {
                    Text  = d.Name,
                    Value = d.Id.ToString()
                });

                personViewModel.CityList = _unitWork.City.GetAll().Select(ci => new SelectListItem
                {
                    Text  = ci.Name,
                    Value = ci.Id.ToString()
                });

                if (personViewModel.Person.Id != 0)
                {
                    personViewModel.Person = _unitWork.Person.Get(personViewModel.Person.Id);
                }
            }
            return(View(personViewModel));
        }
 public IActionResult Index()
 {
     _notyf.Success("Successfully Created");
     return(View());
 }