Exemplo n.º 1
0
 public bool HasNewPasswordBeenUsedRecently(Int64 userId, string proposedNewPassword)
 {
     try
     {
         int numberOfRecentPasswordsToKeep = ExtentionUtility.GetIntAppSetting("NoOfPasswordCheck");
         //first delete old record
         _applicationUser.ExecuteStoreprocedure("spPasswordHistoryDeleteNonRecentPasswords   @UserId,@numberOfRecentPasswordsToKeep", new SqlParameter("UserId", userId), new SqlParameter("numberOfRecentPasswordsToKeep", numberOfRecentPasswordsToKeep));
         //Now get recent password details
         var hashedPasswordDetails = _applicationUser.ExecuteStoredProdure <HashedPasswordDetails>("spPasswordHistorySelect  @UserId,@numberOfRecentPasswordsToKeep", new SqlParameter("UserId", userId), new SqlParameter("numberOfRecentPasswordsToKeep", numberOfRecentPasswordsToKeep));
         foreach (HashedPasswordDetails passwordDetails in hashedPasswordDetails)
         {
             var encodePassword = ExtentionUtility.Encrypt(proposedNewPassword);
             if (ProposedNewPasswordMatchesAPreviousPassword(passwordDetails, encodePassword))
             {
                 return(true);
             }
         }
         return(false);
     }
     catch (Exception ex)
     {
         _log.Error(ex);
         return(false);
     }
 }
Exemplo n.º 2
0
 public static ApplicationUser ModeltoEntity(ArtistViewModel model)
 {
     return(model == null
        ? null
        : new ApplicationUser
     {
         FirstName = model.FirstName,
         LastName = model.LastName,
         MiddleName = model.MiddleName,
         UserName = model.UserName,
         MobileNumber = model.MobileNumber,
         PhoneNumber = model.PhoneNumber,
         Email = model.Email,
         DOB = !string.IsNullOrEmpty(model.DOB) ? ExtentionUtility.ConvertDateValue(model.DOB) : DateTime.MinValue,
         Address = model.Address,
         FacebookURL = model.FacebookURL,
         EmailConfirmed = true,
         PhoneNumberConfirmed = true,
         TwoFactorEnabled = false,
         LockoutEnabled = false,
         AccessFailedCount = 0,
         DateCreated = DateTime.Now,
         IsFirstLogin = true
     });
 }
Exemplo n.º 3
0
        public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }
                Int64 UserId = model.userCode.DecryptID();
                var   user   = await UserManager.FindByIdAsync(UserId);

                if (user == null)
                {
                    // Don't reveal that the user does not exist
                    return(RedirectToAction("ResetPasswordConfirmation", "Account"));
                }
                //check here if password exist b4
                if (HasNewPasswordBeenUsedRecently(user.Id, model.Password))
                {
                    //return false;
                    ModelState.AddModelError("A previous password can't be used as your new password", "Kindly provide a new password this password ");
                    return(View(model));
                }
                else
                {
                    var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

                    if (result.Succeeded)
                    {
                        ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory();
                        passwordModel.UserId       = user.Id;
                        passwordModel.DateCreated  = DateTime.Now;
                        passwordModel.HashPassword = ExtentionUtility.Encrypt(model.Password);
                        _passwordCommand.Insert(passwordModel);
                        _passwordCommand.SaveChanges();

                        ApplicationUser xmodel = UserManager.FindById(user.Id);
                        xmodel.IsFirstLogin = false;
                        UserManager.Update(xmodel);

                        return(RedirectToAction("ResetPasswordConfirmation", "Account"));
                    }
                    AddErrors(result);
                    return(View());
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                return(View("Error"));
            }
        }
Exemplo n.º 4
0
        public async Task <ActionResult> SetFirstlogin(SetFirstPasswordViewModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }
                long UserId = model.code.DecryptID();
                if (HasNewPasswordBeenUsedRecently(UserId, model.Password))
                {
                    //return false;
                    ModelState.AddModelError("A previous password can't be used as your new password", "Kindly provide a new password this password ");
                    return(View(model));
                }
                else
                {
                    // string code = await _userManager.GeneratePasswordResetTokenAsync(UserId);
                    // var result = await _userManager.ResetPasswordAsync(UserId,code, model.Password);
                    var result = await _userManager.ChangePasswordAsync(UserId, "Password", model.Password);

                    if (result.Succeeded)
                    {
                        ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory();
                        passwordModel.UserId       = UserId;
                        passwordModel.DateCreated  = DateTime.Now;
                        passwordModel.HashPassword = ExtentionUtility.Encrypt(model.Password);
                        _passwordCommand.Insert(passwordModel);
                        _passwordCommand.SaveChanges();

                        ApplicationUser xmodel = _userManager.FindById(UserId);
                        xmodel.IsFirstLogin = false;
                        _userManager.Update(xmodel);
                        return(RedirectToAction("SetPasswordConfirmation", "Account"));
                    }
                    AddErrors(result);
                }
                return(View(model));
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                return(View("Error"));
            }
        }
Exemplo n.º 5
0
        public async Task <ActionResult> ChangePassword(ChangePasswordViewModel model)
        {
            CreateViewBagParams();
            if (!ModelState.IsValid)
            {
                return(PartialView(model));
            }
            long UserId = User.Identity.GetUserId <Int64>();

            if (HasNewPasswordBeenUsedRecently(UserId, model.NewPassword))
            {
                ModelState.AddModelError("A previous password can't be used as your new password", "Kindly provide a new password this password ");
                ViewBag.ErrMsg = "A previous password can't be used as your new password, Kindly provide a new password this password ";
                return(PartialView(model));
            }
            else
            {
                var result = await UserManager.ChangePasswordAsync(UserId, model.OldPassword, model.NewPassword);

                if (result.Succeeded)
                {
                    ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory();
                    passwordModel.UserId       = UserId;
                    passwordModel.DateCreated  = DateTime.Now;
                    passwordModel.HashPassword = ExtentionUtility.Encrypt(model.NewPassword);
                    _passwordCommand.Insert(passwordModel);
                    _passwordCommand.SaveChanges();

                    TempData["MESSAGE"] = "Password change successfully";
                    ModelState.Clear();
                    return(Json(new { success = true }));
                }
                else
                {
                    AddErrors(result);
                    return(PartialView(model));
                }
            }
        }
Exemplo n.º 6
0
        public JsonResult GetEvents(ScheduleViewModel scheduleVm)
        {
            DateTime sdate = DateTime.Now;
            DateTime edate = DateTime.Now;

            DateTime.TryParse(scheduleVm.StartDate, out sdate);
            DateTime.TryParse(scheduleVm.EndDate, out edate);
            if (sdate == DateTime.MinValue)
            {
                sdate = DateTime.Now;
            }
            if (edate == DateTime.MinValue)
            {
                edate = ExtentionUtility.GetDateValue(DateTime.Now.ToString("yyyy-MM-") + DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month).ToString());
            }

            var          model      = new List <ScheduleViewModel>();
            List <Event> eventmodel = _EventQuery.GetAll().ToList();

            if (eventmodel.Any())
            {
                foreach (Event e in eventmodel)
                {
                    model.Add(new ScheduleViewModel()
                    {
                        Id    = e.Id,
                        start = e.StartDate,
                        //eventVmodel.StartDate,
                        end = e.EndDate,
                        //eventVmodel.EndDate,
                        title = "Event: " + e.EventName +
                                "\nVenue: " + e.Venue +
                                "\n Description : " + e.EventDescription
                    });
                }
            }
            return(Json(model, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 7
0
        public async Task <ActionResult> Create(UserViewModel model)
        {
            string code = string.Empty;

            model.Roles = _utility.GetRoles();
            try
            {
                CreateViewBagParams();
                if (ModelState.IsValid)
                {
                    //checking if emailaddress does not exist b4
                    var organizerAdminEmailExist = _applicationUserQuery.GetAllList(m => m.Email.ToLower().Trim() == model.Email.ToLower().Trim()).ToList();
                    if (organizerAdminEmailExist.Any())
                    {
                        ModelState.AddModelError("", "email address already exist");
                        return(PartialView("_PartialAddEdit", model));
                    }

                    //checking if username does not exist b4
                    var organizerAdminUsernameExist = _applicationUserQuery.GetAllList(m => m.UserName.ToLower().Trim() == model.UserName.ToLower().Trim()).ToList();
                    if (organizerAdminUsernameExist.Any())
                    {
                        ModelState.AddModelError("", "username already exist");
                        return(PartialView("_PartialAddEdit", model));
                    }

                    ApplicationUser usermodel = UserViewModel.ModeltoEntity(model);

                    var result = await UserManager.CreateAsync(usermodel, "Password");

                    if (result.Succeeded)
                    {
                        _activityRepo.CreateActivityLog(string.Format("Assinging User Id:{0} with Name :{1} to role Id's:{2}", usermodel.Id, (usermodel.LastName + " " + usermodel.FirstName), model.SelectedRole), this.GetContollerName(), this.GetContollerName(), usermodel.Id, null);

                        ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory();
                        passwordModel.UserId       = usermodel.Id;
                        passwordModel.DateCreated  = DateTime.Now;
                        passwordModel.HashPassword = ExtentionUtility.Encrypt("Password");
                        passwordModel.CreatedBy    = usermodel.Id;
                        _applicationUserPwdhistoryCommand.Insert(passwordModel);
                        _applicationUserPwdhistoryCommand.Save();

                        var addRoleResult = await UserManager.AddToRolesAsync(usermodel.Id, model.SelectedRole.ToArray <string>());

                        if (addRoleResult.Succeeded)
                        {
                            //send user reset mail
                            code = await UserManager.GeneratePasswordResetTokenAsync(usermodel.Id);

                            string portalUrl = System.Web.HttpContext.Current.Request.Url.Scheme + "://" + System.Web.HttpContext.Current.Request.Url.Authority + System.Web.HttpContext.Current.Request.ApplicationPath.TrimEnd('/') + "/";

                            var    callbackUrl = Url.Action("ResetPassword", "Account", new { userId = usermodel.Id, code = code });
                            string mPre        = portalUrl + callbackUrl;
                            _log.Info(string.Format("Reset URL:{0}", mPre));
                            if (!String.IsNullOrEmpty(usermodel.Email))
                            {
                                try
                                {
                                    _utility.SendWelcomeAndPasswordResetEmail(usermodel, mPre);
                                }
                                catch  { }
                            }


                            TempData["MESSAGE"] = "Portal User " + (usermodel.LastName + " " + usermodel.FirstName) + " was successfully created";
                            ModelState.Clear();
                            return(Json(new { success = true }));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", result.Errors.FirstOrDefault().ToString());
                    }
                    ModelState.Clear();
                    return(Json(new { success = true }));
                }
                else
                {
                    StringBuilder errorMsg = new StringBuilder();

                    foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors))
                    {
                        errorMsg.AppendLine(modelError.ErrorMessage);
                        ModelState.AddModelError(string.Empty, modelError.ErrorMessage);
                    }
                    ViewBag.ErrMsg = errorMsg.ToString();
                    return(PartialView("_PartialAddEdit", model));
                }
            }
            catch (Exception exp)
            {
                _log.Error(exp);
                //return View("Error");
                StringBuilder errorMsg = new StringBuilder();

                foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors))
                {
                    errorMsg.AppendLine(modelError.ErrorMessage);
                    ModelState.AddModelError(string.Empty, modelError.ErrorMessage);
                }
                ViewBag.ErrMsg = errorMsg.ToString();
                return(PartialView("_PartialAddEdit", model));
            }
        }
Exemplo n.º 8
0
        public async Task <ActionResult> Create(EventViewModel eventVm)
        {
            string filename = string.Empty;
            string fileName = string.Empty;

            eventVm.Artists = _utility.GetAllArtists();
            try
            {
                CreateViewBagParams();
                if (ModelState.IsValid)
                {
                    //checking if organizer name does not exist b4
                    var eventnameExist = _EventQuery.GetAllList(m => m.EventName.ToLower().Trim() == eventVm.EventName.ToLower().Trim()).ToList();
                    if (eventnameExist.Any())
                    {
                        ModelState.AddModelError("", "Event name already exist");
                        return(PartialView("_PartialAddEdit", eventVm));
                    }

                    var eventmodel = new Event()
                    {
                        EventName        = eventVm.EventName,
                        EventDescription = eventVm.EventDescription,
                        Venue            = eventVm.Venue,
                        ArtistId         = eventVm.ArtistId,
                        City             = eventVm.City,
                        Country          = eventVm.Country,
                        StartDate        = ExtentionUtility.ConvertDateValue(eventVm.StartDate),
                        EndDate          = ExtentionUtility.ConvertDateValue(eventVm.EndDate),
                        CreatedBy        = GetCurrentUserID()
                    };
                    //Save Event
                    await _EventCommand.InsertAsync(eventmodel);

                    await _EventCommand.SaveChangesAsync();

                    _activityRepo.CreateActivityLog(string.Format("User ID: {0} Created event with event Name:{0}", GetCurrentUserID(), eventmodel.EventName), this.GetContollerName(), this.GetActionName(), GetCurrentUserID(), eventmodel);

                    TempData["MESSAGE"] = "Event " + eventmodel.EventName + " was successfully created";
                    ModelState.Clear();
                    return(Json(new { success = true }));
                }
                else
                {
                    StringBuilder errorMsg = new StringBuilder();

                    var errorModel =
                        from x in ModelState.Keys
                        where ModelState[x].Errors.Count > 0
                        select new
                    {
                        key    = x,
                        errors = ModelState[x].Errors.
                                 Select(y => y.ErrorMessage).
                                 ToArray()
                    };

                    foreach (var item in errorModel)
                    {
                        errorMsg.AppendLine(string.Format("Error Key: {0} Error Message: {1}", item.key, string.Join(",", item.errors)));
                        ModelState.AddModelError(item.key, string.Join(",", item.errors));
                    }
                    ViewBag.ErrMsg = errorMsg.ToString();
                    return(PartialView("_PartialAddEdit", eventVm));
                }
            }
            catch (Exception exp)
            {
                _log.Error(exp);
                return(View("Error"));
            }
        }
Exemplo n.º 9
0
        public async Task <ActionResult> Edit(int id, EventViewModel eventVm)
        {
            string filename      = string.Empty;
            string fileName      = string.Empty;
            Int64  CurrentUserId = GetCurrentUserID();

            eventVm.Artists = _utility.GetAllArtists();
            try
            {
                EditViewBagParams();
                if (id <= 0)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }
                if (ModelState.IsValid)
                {
                    //checking if organizer name does not exist b4
                    var eventnameExist = _EventQuery.GetAllList(m => m.EventName.ToLower().Trim() == eventVm.EventName.ToLower().Trim() && m.Id != eventVm.Id).ToList();
                    if (eventnameExist.Any())
                    {
                        ModelState.AddModelError("", "Event name already exist");
                        return(PartialView("_PartialAddEdit", eventVm));
                    }

                    Event eventModel = await _EventQuery.GetAsync(eventVm.Id);

                    eventModel.EventName        = eventVm.EventName;
                    eventModel.EventDescription = eventVm.EventDescription;
                    eventModel.Venue            = eventVm.Venue;
                    eventModel.ArtistId         = eventVm.ArtistId;
                    eventModel.Venue            = eventVm.Venue;
                    eventModel.City             = eventVm.City;
                    eventModel.Country          = eventVm.Country;
                    eventModel.StartDate        = ExtentionUtility.ConvertDateValue(eventVm.StartDate);
                    eventModel.EndDate          = ExtentionUtility.ConvertDateValue(eventVm.EndDate);

                    //Save Event
                    await _EventCommand.UpdateAsync(eventModel);

                    await _EventCommand.SaveChangesAsync();

                    _activityRepo.CreateActivityLog(string.Format(" User Id:{0} updated event with event Name:{1}", CurrentUserId, eventVm.EventName), this.GetContollerName(), this.GetActionName(), CurrentUserId, eventVm);

                    TempData["MESSAGE"] = "Event: " + eventVm.EventName + " was successfully updated";
                    ModelState.Clear();

                    return(Json(new { success = true }));
                }
                else
                {
                    StringBuilder errorMsg = new StringBuilder();

                    var errorModel =
                        from x in ModelState.Keys
                        where ModelState[x].Errors.Count > 0
                        select new
                    {
                        key    = x,
                        errors = ModelState[x].Errors.
                                 Select(y => y.ErrorMessage).
                                 ToArray()
                    };

                    foreach (var item in errorModel)
                    {
                        errorMsg.AppendLine(string.Format("Error Key: {0} Error Message: {1}", item.key, string.Join(",", item.errors)));
                        ModelState.AddModelError(item.key, string.Join(",", item.errors));
                    }
                    //ModelState.Values.SelectMany(modelState => modelState.Errors)
                    //foreach (var modelError in ModelState.Erro)
                    //{
                    //    errorMsg.AppendLine(modelError.ErrorMessage);
                    //    ModelState.AddModelError(string.Empty, modelError.ErrorMessage);
                    //}
                    ViewBag.ErrMsg = errorMsg.ToString();
                    return(PartialView("_PartialAddEdit", eventVm));
                }
            }
            catch (Exception exp)
            {
                _log.Error(exp);
                return(View("Error"));
            }
        }
Exemplo n.º 10
0
        public async Task <ActionResult> MyProfile(UserViewModel model)
        {
            long UserId = User.Identity.GetUserId <Int64>();

            try
            {
                if (ModelState.IsValid)
                {
                    var emailExist = _applicationUser.GetAllList(m => m.Email.ToLower().Trim() == model.Email.ToLower().Trim() && m.Id != model.Id).ToList();
                    if (emailExist.Any())
                    {
                        ModelState.AddModelError("", "email address already exist");
                        ViewBag.ErrMsg = "email address already exist";
                        return(View(model));
                    }

                    //checking if username does not exist b4
                    var usernameExist = _applicationUser.GetAllList(m => m.UserName.ToLower().Trim() == model.UserName.ToLower().Trim() && m.Id != model.Id).ToList();
                    if (usernameExist.Any())
                    {
                        ModelState.AddModelError("", "username already exist");
                        ViewBag.ErrMsg = "username already exist";
                        return(View(model));
                    }

                    ApplicationUser usermodel = await _applicationUser.GetAsync(model.Id);

                    if (usermodel != null)
                    {
                        usermodel.FirstName    = model.FirstName;
                        usermodel.LastName     = model.LastName;
                        usermodel.MiddleName   = model.MiddleName;
                        usermodel.MobileNumber = model.MobileNumber;
                        usermodel.PhoneNumber  = model.PhoneNumber;
                        usermodel.DOB          = !string.IsNullOrEmpty(model.DOB) ? ExtentionUtility.ConvertDateValue(model.DOB) : DateTime.MinValue;
                        usermodel.Address      = model.Address;
                        await _applicationUserCommand.UpdateAsync(usermodel);

                        await _applicationUserCommand.SaveChangesAsync();

                        _activityRepo.CreateActivityLog(string.Format("Updtae User Id:{0} with Name :{1}", usermodel.Id, (usermodel.LastName + " " + usermodel.FirstName)), this.GetContollerName(), this.GetActionName(), usermodel.Id, null);


                        ViewBag.Msg = "User Profile was successfully updated";
                        ModelState.Clear();
                        return(View(model));
                    }
                }
                else
                {
                    StringBuilder errorMsg = new StringBuilder();

                    foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors))
                    {
                        errorMsg.AppendLine(modelError.ErrorMessage);
                        ModelState.AddModelError(string.Empty, modelError.ErrorMessage);
                    }
                    ViewBag.ErrMsg = errorMsg.ToString();
                    return(View(model));
                }
                return(View(model));
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                return(View("Error"));
            }
        }
Exemplo n.º 11
0
        public async Task <ActionResult> Edit(UserViewModel model)
        {
            string code = string.Empty;

            model.Roles = _utility.GetRoles();
            try
            {
                EditViewBagParams();
                if (ModelState.IsValid)
                {
                    //checking if emailaddress does not exist b4
                    var organizerAdminEmailExist = _applicationUserQuery.GetAllList(m => m.Email.ToLower().Trim() == model.Email.ToLower().Trim() && m.Id != model.Id).ToList();
                    if (organizerAdminEmailExist.Any())
                    {
                        ModelState.AddModelError("", "email address already exist");
                        return(PartialView("_PartialAddEdit", model));
                    }

                    //checking if username does not exist b4
                    var organizerAdminUsernameExist = _applicationUserQuery.GetAllList(m => m.UserName.ToLower().Trim() == model.UserName.ToLower().Trim() && m.Id != model.Id).ToList();
                    if (organizerAdminUsernameExist.Any())
                    {
                        ModelState.AddModelError("", "username already exist");
                        return(PartialView("_PartialAddEdit", model));
                    }

                    ApplicationUser usermodel = await _applicationUserQuery.GetAsync(model.Id);

                    if (usermodel != null)
                    {
                        usermodel.FirstName    = model.FirstName;
                        usermodel.LastName     = model.LastName;
                        usermodel.MiddleName   = model.MiddleName;
                        usermodel.MobileNumber = model.MobileNumber;
                        usermodel.PhoneNumber  = model.PhoneNumber;
                        usermodel.DOB          = !string.IsNullOrEmpty(model.DOB) ? ExtentionUtility.ConvertDateValue(model.DOB) : DateTime.MinValue;
                        usermodel.Address      = model.Address;
                        await _applicationUserCommand.UpdateAsync(usermodel);

                        await _applicationUserCommand.SaveChangesAsync();

                        _activityRepo.CreateActivityLog(string.Format("Updtae User Id:{0} with Name :{1}", usermodel.Id, (usermodel.LastName + " " + usermodel.FirstName)), this.GetContollerName(), this.GetActionName(), usermodel.Id, null);


                        //update UserRole
                        //.First delete role if exist
                        //Add the new role
                        _applicationUserQuery.ExecuteStoreprocedure(AppConstant.DeleteUserRoleByUserId + " @UserId", new SqlParameter("UserId", usermodel.Id));
                        await UserManager.AddToRolesAsync(usermodel.Id, model.SelectedRole.ToArray <string>());

                        _activityRepo.CreateActivityLog(string.Format("Assinging User Id:{0} with Name :{1} to role Id's:{2}", usermodel.Id, (usermodel.LastName + " " + usermodel.FirstName), model.SelectedRole), this.GetContollerName(), this.GetActionName(), usermodel.Id, null);

                        TempData["MESSAGE"] = "Portal User " + (usermodel.LastName + " " + usermodel.FirstName) + " was successfully created";
                        ModelState.Clear();
                        return(Json(new { success = true }));
                    }
                    else
                    {
                        ModelState.AddModelError("", "An error occurred while processing your request");
                    }
                    ModelState.Clear();
                    return(Json(new { success = true }));
                }
                else
                {
                    StringBuilder errorMsg = new StringBuilder();

                    foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors))
                    {
                        errorMsg.AppendLine(modelError.ErrorMessage);
                        ModelState.AddModelError(string.Empty, modelError.ErrorMessage);
                    }
                    ViewBag.ErrMsg = errorMsg.ToString();
                    return(PartialView("_PartialAddEdit", model));
                }
            }
            catch (Exception exp)
            {
                _log.Error(exp);
                model.Roles = _utility.GetRoles();
                //return View("Error");
                StringBuilder errorMsg = new StringBuilder();

                foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors))
                {
                    errorMsg.AppendLine(modelError.ErrorMessage);
                    ModelState.AddModelError(string.Empty, modelError.ErrorMessage);
                }
                ViewBag.ErrMsg = errorMsg.ToString();
                return(PartialView("_PartialAddEdit", model));
            }
        }
Exemplo n.º 12
0
        public async Task <ActionResult> FramewokAdmin(string nextButton, string backButton)
        {
            string msg;

            if (backButton != null)
            {
                return(RedirectToAction("FrameworkSetting"));
            }

            if (nextButton != null)
            {
                if (!ModelState.IsValid)
                {
                    return(View(_setupContract));
                }
                if (string.Compare(_setupContract.AdminUserSetting.Password,
                                   _setupContract.AdminUserSetting.ConfirmPassword,
                                   StringComparison.InvariantCultureIgnoreCase) != 0)
                {
                    ViewBag.ErrMsg = "Password and confirm password must be equal";
                    // ModelState.AddModelError("","Password and confirm password must be equal");
                    return(View(_setupContract));
                }


                var user = new ApplicationUser
                {
                    FirstName            = _setupContract.AdminUserSetting.FirstName,
                    LastName             = _setupContract.AdminUserSetting.LastName,
                    MiddleName           = _setupContract.AdminUserSetting.MiddleName,
                    UserName             = _setupContract.AdminUserSetting.UserName,
                    Email                = _setupContract.AdminUserSetting.Email,
                    MobileNumber         = _setupContract.AdminUserSetting.MobileNumber,
                    PhoneNumber          = _setupContract.AdminUserSetting.PhoneNumber,
                    EmailConfirmed       = true,
                    PhoneNumberConfirmed = true,
                    TwoFactorEnabled     = false,
                    LockoutEnabled       = false,
                    AccessFailedCount    = 0,
                    DateCreated          = DateTime.Now,
                    IsFirstLogin         = false
                };
                var result = await UserManager.CreateAsync(user, _setupContract.AdminUserSetting.Password);

                if (result.Succeeded)
                {
                    ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory();
                    passwordModel.UserId       = user.Id;
                    passwordModel.DateCreated  = DateTime.Now;
                    passwordModel.HashPassword = ExtentionUtility.Encrypt(_setupContract.AdminUserSetting.Password);
                    passwordModel.CreatedBy    = user.Id;
                    _applicationUserPwdhistoryCommand.Insert(passwordModel);
                    _applicationUserPwdhistoryCommand.Save();

                    var addRoleResult = await UserManager.AddToRoleAsync(user.Id, "PortalAdmin");

                    if (addRoleResult.Succeeded)
                    {
                        Application applicationmodel = _applicationQuery.GetAll().FirstOrDefault();
                        applicationmodel.HasAdminUserConfigured = true;
                        _applicationCommand.Update(applicationmodel);
                        _applicationCommand.SaveChanges();
                        _activityRepo.CreateActivityLog("creating Framework admin user details", this.GetContollerName(), this.GetContollerName(), _setupContract.AdminUserSetting.Id, _setupContract.AdminUserSetting);
                        return(RedirectToAction("Login", "Account", new { area = "" }));
                    }
                }
                else
                {
                    ModelState.AddModelError("", result.Errors.FirstOrDefault().ToString());
                }
                return(View(_setupContract));
            }

            var userInfo = UserManager.Users.ToList().Select(AdminUserSettingViewModel.EntityToModels).FirstOrDefault();

            if (userInfo == null)
            {
                //ModelState.AddModelError("", "Unable to initialize admin user information due to internal error! Please try again later");
                return(View(_setupContract));
            }
            _setupContract.AdminUserSetting = userInfo;
            return(View(_setupContract));
        }
Exemplo n.º 13
0
        public async Task <ActionResult> Create(ArtistViewModel model, HttpPostedFileBase profileImage)
        {
            string code        = string.Empty;
            string profilePath = string.Empty;

            try
            {
                CreateViewBagParams();
                if (ModelState.IsValid)
                {
                    if (profileImage != null && profileImage.ContentLength > 0)
                    {
                        var      ext = Path.GetExtension(profileImage.FileName).Trim().ToLower();
                        string[] allowedExtension = new string[] { ".jpeg", ".jpg", ".png" };
                        if (allowedExtension.Contains(ext))
                        {
                            profilePath = _utility.Upload(profileImage, _utility.GetAppSetting("AppUploadFolder"));
                        }
                        else
                        {
                            ModelState.AddModelError("", string.Format("Invalid image extension,allowed extension are: .jpeg,.jpg,.png ", allowedExtension));
                            //return PartialView("_PartialAddEdit", staffVm);
                            return(View("_PartialAddEdit", model));
                        }
                    }


                    //checking if emailaddress does not exist b4
                    var organizerAdminEmailExist = _applicationUserQuery.GetAllList(m => m.Email.ToLower().Trim() == model.Email.ToLower().Trim()).ToList();
                    if (organizerAdminEmailExist.Any())
                    {
                        ModelState.AddModelError("", "email address already exist");
                        return(PartialView("_PartialAddEdit", model));
                    }

                    //checking if username does not exist b4
                    var organizerAdminUsernameExist = _applicationUserQuery.GetAllList(m => m.UserName.ToLower().Trim() == model.UserName.ToLower().Trim()).ToList();
                    if (organizerAdminUsernameExist.Any())
                    {
                        ModelState.AddModelError("", "username already exist");
                        return(PartialView("_PartialAddEdit", model));
                    }

                    ApplicationUser usermodel = ArtistViewModel.ModeltoEntity(model);
                    usermodel.PicturePath = Path.GetFileName(profilePath);
                    usermodel.FacebookURL = model.FacebookURL;

                    var result = await UserManager.CreateAsync(usermodel, "Password");

                    if (result.Succeeded)
                    {
                        _activityRepo.CreateActivityLog(string.Format("Assinging User Id:{0} with Name :{1} to role Id's:{2}", usermodel.Id, (usermodel.LastName + " " + usermodel.FirstName), ""), this.GetContollerName(), this.GetContollerName(), usermodel.Id, null);

                        ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory();
                        passwordModel.UserId       = usermodel.Id;
                        passwordModel.DateCreated  = DateTime.Now;
                        passwordModel.HashPassword = ExtentionUtility.Encrypt("Password");
                        passwordModel.CreatedBy    = usermodel.Id;
                        _applicationUserPwdhistoryCommand.Insert(passwordModel);
                        _applicationUserPwdhistoryCommand.Save();

                        var addRoleResult = await UserManager.AddToRoleAsync(usermodel.Id, "Artist");

                        if (addRoleResult.Succeeded)
                        {
                            //send user reset mail
                            code = await UserManager.GeneratePasswordResetTokenAsync(usermodel.Id);

                            string portalUrl = System.Web.HttpContext.Current.Request.Url.Scheme + "://" + System.Web.HttpContext.Current.Request.Url.Authority + System.Web.HttpContext.Current.Request.ApplicationPath.TrimEnd('/') + "/";

                            var    callbackUrl = Url.Action("ResetPassword", "Account", new { userCode = usermodel.Id.EncryptID(), code = code });
                            string mPre        = portalUrl + callbackUrl;
                            _log.Info(string.Format("Reset URL:{0}", mPre));
                            if (!String.IsNullOrEmpty(usermodel.Email))
                            {
                                _utility.SendWelcomeAndPasswordResetEmail(usermodel, mPre);
                            }


                            TempData["MESSAGE"] = "Artist " + (usermodel.LastName + " " + usermodel.FirstName) + " was successfully created";
                            ModelState.Clear();
                            return(Json(new { success = true }));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", result.Errors.FirstOrDefault().ToString());
                    }
                    ModelState.Clear();
                    return(Json(new { success = true }));
                }
                else
                {
                    StringBuilder errorMsg = new StringBuilder();

                    foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors))
                    {
                        errorMsg.AppendLine(modelError.ErrorMessage);
                        ModelState.AddModelError(string.Empty, modelError.ErrorMessage);
                    }
                    ViewBag.ErrMsg = errorMsg.ToString();
                    return(PartialView("_PartialAddEdit", model));
                }
            }
            catch (Exception exp)
            {
                _log.Error(exp);
                //return View("Error");
                StringBuilder errorMsg = new StringBuilder();

                foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors))
                {
                    errorMsg.AppendLine(modelError.ErrorMessage);
                    ModelState.AddModelError(string.Empty, modelError.ErrorMessage);
                }
                ViewBag.ErrMsg = errorMsg.ToString();
                return(PartialView("_PartialAddEdit", model));
            }
        }
Exemplo n.º 14
0
        public async Task <ActionResult> Edit(ArtistViewModel model, HttpPostedFileBase profileImage)
        {
            string code        = string.Empty;
            string profilePath = string.Empty;

            try
            {
                EditViewBagParams();
                if (ModelState.IsValid)
                {
                    if (profileImage != null && profileImage.ContentLength > 0)
                    {
                        var      ext = Path.GetExtension(profileImage.FileName).Trim().ToLower();
                        string[] allowedExtension = new string[] { ".jpeg", ".jpg", ".png" };
                        if (allowedExtension.Contains(ext))
                        {
                            profilePath = _utility.Upload(profileImage, _utility.GetAppSetting("AppUploadFolder"));
                        }
                        else
                        {
                            ModelState.AddModelError("", string.Format("Invalid image extension,allowed extension are: .jpeg,.jpg,.png ", allowedExtension));
                            //return PartialView("_PartialAddEdit", staffVm);
                            return(View("_PartialAddEdit", model));
                        }
                    }

                    ApplicationUser usermodel = await _applicationUserQuery.GetAsync(model.Id);

                    if (usermodel != null)
                    {
                        usermodel.FirstName    = model.FirstName;
                        usermodel.LastName     = model.LastName;
                        usermodel.MiddleName   = model.MiddleName;
                        usermodel.MobileNumber = model.MobileNumber;
                        usermodel.PhoneNumber  = model.PhoneNumber;
                        usermodel.DOB          = !string.IsNullOrEmpty(model.DOB) ? ExtentionUtility.ConvertDateValue(model.DOB) : DateTime.MinValue;
                        usermodel.Address      = model.Address;
                        usermodel.PicturePath  = Path.GetFileName(profilePath);
                        usermodel.FacebookURL  = model.FacebookURL;
                        await _applicationUserCommand.UpdateAsync(usermodel);

                        await _applicationUserCommand.SaveChangesAsync();

                        _activityRepo.CreateActivityLog(string.Format("Updtae User Id:{0} with Name :{1}", usermodel.Id, (usermodel.LastName + " " + usermodel.FirstName)), this.GetContollerName(), this.GetActionName(), usermodel.Id, null);

                        _activityRepo.CreateActivityLog(string.Format("Assinging User Id:{0} with Name :{1} to role Id's:{2}", usermodel.Id, (usermodel.LastName + " " + usermodel.FirstName), ""), this.GetContollerName(), this.GetActionName(), usermodel.Id, null);

                        TempData["MESSAGE"] = "Artist " + (usermodel.LastName + " " + usermodel.FirstName) + " was successfully created";
                        ModelState.Clear();
                        return(Json(new { success = true }));
                    }
                    else
                    {
                        ModelState.AddModelError("", "An error occurred while processing your request");
                    }
                    ModelState.Clear();
                    return(Json(new { success = true }));
                }
                else
                {
                    StringBuilder errorMsg = new StringBuilder();

                    foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors))
                    {
                        errorMsg.AppendLine(modelError.ErrorMessage);
                        ModelState.AddModelError(string.Empty, modelError.ErrorMessage);
                    }
                    ViewBag.ErrMsg = errorMsg.ToString();
                    return(PartialView("_PartialAddEdit", model));
                }
            }
            catch (Exception exp)
            {
                _log.Error(exp);
                //return View("Error");
                StringBuilder errorMsg = new StringBuilder();

                foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors))
                {
                    errorMsg.AppendLine(modelError.ErrorMessage);
                    ModelState.AddModelError(string.Empty, modelError.ErrorMessage);
                }
                ViewBag.ErrMsg = errorMsg.ToString();
                return(PartialView("_PartialAddEdit", model));
            }
        }