//private async Task<List<Error>> SaveGrid1(UserRoleVm grid1, IEnumerable<KeyValuePair<string, ModelState>> state, UserViewModel record)
        //{
        //    List<Error> errors = new List<Error>();


        //    IdentityResult re = new IdentityResult();
        //    // updated records
        //    if (grid1.updated != null)
        //    {
        //        foreach (var model in grid1.updated)
        //        {
        //            if (model.IsChecked)
        //            {
        //                if (!_userManager.IsInRole(record.Id, model.Name))
        //                    re = await _userManager.AddToRoleAsync(record.Id, model.Name);
        //            }
        //            else
        //            {
        //                if (_userManager.IsInRole(record.Id, model.Name))
        //                    re = await _userManager.RemoveFromRoleAsync(record.Id, model.Name);
        //            }
        //        }
        //    }
        //    else
        //    {
        //        if (record.NewUser)
        //        {
        //            await _userManager.AddToRoleAsync(record.Id, "Employee");
        //        }
        //    }
        //    if (re.Errors.Count() > 0)
        //    {
        //        foreach (var error in re.Errors)
        //        {
        //            ErrorMessage mess = new ErrorMessage()
        //            {
        //                message = MsgUtils.Instance.Trls(error)
        //            };
        //            Error er = new Error();
        //            er.errors.Add(mess);
        //            return errors;
        //        }
        //    }

        //    return errors;
        //}
        private List <Error> SaveGrid(UserCompaniesVM grid, IEnumerable <KeyValuePair <string, ModelState> > state, ApplicationUser user)
        {
            List <Error> errors = new List <Error>();

            // Deleted
            if (grid.deleted != null)
            {
                foreach (var model in grid.deleted)
                {
                    var companyrole = new UserCompanyRole
                    {
                        Id = model.Id
                    };

                    db.UserCompanyRoles.Remove(companyrole);
                }
            }

            // updated records
            if (grid.updated != null)
            {
                foreach (var model in grid.updated)
                {
                    var companyrole = new UserCompanyRole();
                    AutoMapper(new Models.AutoMapperParm {
                        Destination = companyrole, Source = model, Transtype = TransType.Update
                    });

                    db.UserCompanyRoles.Attach(companyrole);
                    db.Entry(companyrole).State = EntityState.Modified;
                }
            }

            // inserted records
            if (grid.inserted != null)
            {
                foreach (var model in grid.inserted)
                {
                    var companyrole = new UserCompanyRole();
                    AutoMapper(new Models.AutoMapperParm {
                        Destination = companyrole, Source = model, Transtype = TransType.Insert
                    });
                    companyrole.User = user;
                    db.UserCompanyRoles.Add(companyrole);
                }
            }

            return(errors);
        }
示例#2
0
        private void SaveGrid(UserCompaniesVM grid, IEnumerable <KeyValuePair <string, ModelState> > state, ApplicationUser user, HrUnitOfWork unitOfWork, UserContext db)
        {
            // Deleted
            if (grid.deleted != null)
            {
                foreach (var model in grid.deleted)
                {
                    var companyrole = new UserCompanyRole
                    {
                        Id = model.Id
                    };

                    db.UserCompanyRoles.Remove(companyrole);
                }
            }

            // updated records
            if (grid.updated != null)
            {
                foreach (var model in grid.updated)
                {
                    var companyrole = new UserCompanyRole();
                    AutoMapper(new Models.AutoMapperParm {
                        Destination = companyrole, Source = model, Transtype = TransType.Update
                    }, unitOfWork);
                    companyrole.UserId = user.Id;
                    db.UserCompanyRoles.Attach(companyrole);
                    db.Entry(companyrole).State = EntityState.Modified;
                }
            }

            // inserted records
            if (grid.inserted != null)
            {
                foreach (var model in grid.inserted)
                {
                    var companyrole = new UserCompanyRole();
                    AutoMapper(new Models.AutoMapperParm {
                        Destination = companyrole, Source = model, Transtype = TransType.Insert
                    }, unitOfWork);
                    companyrole.User = user;
                    db.UserCompanyRoles.Add(companyrole);
                }
            }
        }
示例#3
0
        public async Task <ActionResult> UserProfile(UserViewModel model, string Id, int EmpId, OptionsViewModel moreInfo, UserCompaniesVM grid1)
        {
            var Errors                  = new List <Error>();
            var _hrUnitOfWork           = new HrUnitOfWork(new HrContextFactory(System.Configuration.ConfigurationManager.ConnectionStrings["HrContext"].ConnectionString));
            var ServerValidationEnabled = System.Configuration.ConfigurationManager.AppSettings["ServerValidationEnabled"] == "true";

            if (ModelState.IsValid)
            {
                if (ServerValidationEnabled)
                {
                    var columns = Models.Utils.GetColumnViews(ModelState.Where(a => !a.Key.Contains('.')));
                    Errors = _hrUnitOfWork.SiteRepository.CheckForm(new CheckParm
                    {
                        CompanyId  = User.Identity.GetDefaultCompany(),
                        ObjectName = "UserProfile",
                        TableName  = "AspNetUsers",
                        Columns    = columns,
                        Culture    = User.Identity.GetLanguage()
                    });

                    if (Errors.Count() > 0)
                    {
                        foreach (var e in Errors)
                        {
                            foreach (var errorMsg in e.errors)
                            {
                                ModelState.AddModelError(errorMsg.field, errorMsg.message);
                            }
                        }

                        return(Json(Models.Utils.ParseFormErrors(ModelState)));
                    }
                }

                var db           = HttpContext.GetOwinContext().Get <UserContext>();
                var _userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();

                //var db = new UserContext();
                //var _userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));

                ApplicationUser user = _userManager.FindById(Id);
                IdentityResult  res;
                var             loginId = User.Identity.GetUserId();
                model.Messages = getMessage(model.Culture);

                //Update User
                if (user != null)
                {
                    string OldCulture  = user.Language;
                    string OldTimeZone = user.TimeZone;
                    int    OldCompany  = user.DefaultCompany.Value;
                    AutoMapper(new Models.AutoMapperParm
                    {
                        Destination = user,
                        Source      = model,
                        ObjectName  = "UserProfile",
                        Options     = moreInfo
                    }, _hrUnitOfWork);

                    user.Language       = model.Language == null ? "en-GB" : model.Language;
                    user.Messages       = getMessage(model.Culture);
                    model.NewUser       = false;
                    user.LockoutEnabled = model.LockoutEnabled;

                    if ((user.Id == loginId) && (user.TimeZone != OldTimeZone) && (OldCulture != model.Language) && (user.Language != null) && (user.TimeZone != null))
                    {
                        ChangeAll(model.TimeZone, model.Language, model.DefaultCompany.Value);
                    }
                    else if ((user.Id == loginId) && (OldCulture != null) && (OldCulture != model.Language))
                    {
                        ChangeCulture(model.Language, model.DefaultCompany.Value);
                    }
                    else if ((user.Id == loginId) && (OldTimeZone != null) && (OldTimeZone != model.TimeZone))
                    {
                        ChangeTimeZone(model.TimeZone, model.DefaultCompany.Value);
                    }
                    else if ((user.Id == loginId) && (OldCompany != User.Identity.GetDefaultCompany()))
                    {
                        ChangeDefaultCompany(model.DefaultCompany.Value);
                    }
                }
                else //New User
                {
                    user = new ApplicationUser {
                        UserName = model.UserName, Email = model.Email, LockoutEnabled = model.LockoutEnabled
                    };
                    model.NewUser = true;
                }

                // database transactions
                //var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                var trans  = db.Database.BeginTransaction();
                var status = (model.NewUser == true ? PersonStatus.UserProfile : 0);
                if (!model.NewUser)
                {
                    res = await _userManager.UpdateAsync(user);
                }
                else
                {
                    if (model.Password == null)
                    {
                        user.ResetPassword = true;
                        res = await _userManager.CreateAsync(user);
                    }
                    else
                    {
                        res = await _userManager.CreateAsync(user, model.Password);
                    }
                }

                moreInfo.VisibleColumns.Remove("Id");
                if (res.Errors.Count() > 0)
                {
                    var err = res.Errors.FirstOrDefault().Split(' ')[0];
                    if (err == "Passwords")
                    {
                        ModelState.AddModelError("Password", MsgUtils.Instance.Trls("Passwordmustnotlest6"));
                    }
                    else if (err == "User")
                    {
                        ModelState.AddModelError("UserName", MsgUtils.Instance.Trls("Namemustcontaindigitorchar"));
                    }
                    else
                    {
                        ModelState.AddModelError("", MsgUtils.Instance.Trls(res.Errors.FirstOrDefault()));
                    }

                    trans.Rollback();
                    trans.Dispose();
                    return(Json(Models.Utils.ParseFormErrors(ModelState)));
                }

                if (model.NewUser)
                {
                    AutoMapper(new Models.AutoMapperParm
                    {
                        Destination = user,
                        Source      = model,
                        ObjectName  = "UserProfile",
                        Options     = moreInfo
                    }, _hrUnitOfWork);

                    user.Messages        = getMessage(model.Culture);
                    user.Language        = model.Language == null ? "en-GB" : model.Language;
                    user.DefaultCompany  = User.Identity.GetDefaultCompany();
                    user.EmpId           = EmpId;
                    model.EmpId          = EmpId;
                    model.DefaultCompany = user.DefaultCompany;
                    model.Id             = user.Id;
                }

                SaveGrid(grid1, ModelState.Where(a => a.Key.Contains("grid1")), user, _hrUnitOfWork, db);
                try
                {
                    //if (model.NewUser)
                    //{
                    //    string Message;
                    //    SendNotifyLetterMethod(_hrUnitOfWork, user.UserName, EmpId, user.Id, out Message);
                    //}

                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    var message = _hrUnitOfWork.HandleDbExceptions(ex);
                    if (message == "Date Already Exists")
                    {
                        message = "UserHaveOnlyRole";
                    }
                    //scope.Dispose();
                    trans.Rollback();
                    trans.Dispose();
                    return(Json(MsgUtils.Instance.Trls(message)));
                }

                trans.Commit();
                trans.Dispose();

                if (status != PersonStatus.Done)
                {
                    var person = _hrUnitOfWork.PeopleRepository.GetPerson(model.EmpId);
                    person.Status = PersonStatus.Done;
                    model.Status  = PersonStatus.Done;
                    _hrUnitOfWork.SaveChanges();
                }

                return(Json("OK," + ((new JavaScriptSerializer()).Serialize(model))));
            }

            return(Json(Models.Utils.ParseFormErrors(ModelState)));
        }
        public async Task <ActionResult> UserProfile(UserViewModel model, string Id, OptionsViewModel moreInfo, UserCompaniesVM grid1)
        {
            List <Error> Errors = new List <Error>();

            if (ModelState.IsValid)
            {
                if (ServerValidationEnabled)
                {
                    var columns = Models.Utils.GetColumnViews(ModelState.Where(a => !a.Key.Contains('.')));
                    Errors = _hrUnitOfWork.SiteRepository.CheckForm(new CheckParm
                    {
                        CompanyId  = User.Identity.GetDefaultCompany(),
                        ObjectName = "UserProfile",
                        TableName  = "AspNetUsers",
                        Columns    = columns,
                        Culture    = User.Identity.GetLanguage()
                    });

                    if (Errors.Count() > 0)
                    {
                        foreach (var e in Errors)
                        {
                            foreach (var errorMsg in e.errors)
                            {
                                ModelState.AddModelError(errorMsg.field, errorMsg.message);
                            }
                        }

                        return(Json(Models.Utils.ParseFormErrors(ModelState)));
                    }
                }


                ApplicationUser user = _userManager.FindById(Id);
                IdentityResult  res;
                var             loginId = User.Identity.GetUserId();
                //ApplicationUser loginUser = _userManager.FindById(User.Identity.GetUserId());
                model.Messages = getMessage(model.Culture);

                //Update User
                if (user != null)
                {
                    //if (!loginUser.SuperUser)
                    //    model.SuperUser = user.SuperUser; //Keep Original Value
                    //else
                    //{
                    //    int supersCount = _userManager.Users.Where(u => u.SuperUser).Count();
                    //    if (user.Id == loginUser && !model.SuperUser && supersCount <= 1)
                    //    {
                    //        ErrorMessage mess = new ErrorMessage()
                    //        {
                    //            field = "SuperUser",
                    //            message = MsgUtils.Instance.Trls("CantRemoveSuperUser")
                    //        };
                    //        Error er = new Error();
                    //        er.errors.Add(mess);
                    //        return Json(Errors);
                    //    }
                    //}

                    string OldCulture  = user.Language;
                    string OldTimeZone = user.TimeZone;
                    int    OldCompany  = user.DefaultCompany.Value;
                    AutoMapper(new Models.AutoMapperParm
                    {
                        Destination = user,
                        Source      = model,
                        ObjectName  = "UserProfile",
                        Options     = moreInfo
                    });

                    user.Language       = model.Language == null ? "en-GB" : model.Language;
                    user.Messages       = getMessage(model.Culture);
                    model.NewUser       = false;
                    user.LockoutEnabled = model.LockoutEnabled;

                    res = await _userManager.UpdateAsync(user);

                    if ((user.Id == loginId) && (user.TimeZone != OldTimeZone) && (OldCulture != model.Language) && (user.Language != null) && (user.TimeZone != null))
                    {
                        ChangeAll(model.TimeZone, model.Language, model.DefaultCompany.Value);
                    }
                    else if ((user.Id == loginId) && (user.Language != null) && (OldCulture != model.Language))
                    {
                        ChangeCulture(model.Language, model.DefaultCompany.Value);
                    }
                    else if ((user.Id == loginId) && (user.TimeZone != null) && (OldTimeZone != model.TimeZone))
                    {
                        ChangeTimeZone(model.TimeZone, model.DefaultCompany.Value);
                    }
                    else if ((user.Id == loginId) && (OldCompany != model.DefaultCompany))
                    {
                        ChangeDefaultCompany(model.DefaultCompany.Value);
                    }
                }
                else //New User
                {
                    user     = new ApplicationUser();
                    model.Id = user.Id;
                    AutoMapper(new Models.AutoMapperParm
                    {
                        Destination = user,
                        Source      = model,
                        ObjectName  = "UserProfile",
                        Options     = moreInfo
                    });
                    user.Messages       = getMessage(model.Culture);
                    user.Language       = model.Language == null ? "en-GB" : model.Language;
                    model.NewUser       = true;
                    user.LockoutEnabled = model.LockoutEnabled;
                    user.DefaultCompany = User.Identity.GetDefaultCompany();

                    if (model.Password == null)
                    {
                        user.ResetPassword = true;
                        res = await _userManager.CreateAsync(user);
                    }
                    else
                    {
                        res = await _userManager.CreateAsync(user, model.Password);
                    }

                    if (res.Errors.Count() > 0)
                    {
                        var err = res.Errors.FirstOrDefault().Split(' ')[0];
                        if (err == "Passwords")
                        {
                            ModelState.AddModelError("Password", MsgUtils.Instance.Trls("Passwordmustnotlest6"));
                        }
                        else if (err == "User")
                        {
                            ModelState.AddModelError("UserName", MsgUtils.Instance.Trls("Namemustcontaindigitorchar"));
                        }
                        else
                        {
                            ModelState.AddModelError("", MsgUtils.Instance.Trls(res.Errors.FirstOrDefault()));
                        }

                        return(Json(Models.Utils.ParseFormErrors(ModelState)));
                    }
                }

                //Errors = await SaveGrid1(grid1, ModelState.Where(a => a.Key.Contains("grid1")), model);
                //if (Errors.Count > 0) return Json(Errors.First().errors.First().message);

                Errors = SaveGrid(grid1, ModelState.Where(a => a.Key.Contains("grid1")), user);
                if (Errors.Count > 0)
                {
                    return(Json(Errors.First().errors.First().message));
                }


                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    ErrorMessage mess = new ErrorMessage()
                    {
                        message = MsgUtils.Instance.Trls(ex.Message)
                    };
                    //Error er = new Error();
                    //er.errors.Add(mess);
                    //return Json(errors.First().errors.First().message);
                }



                //Validation
                //if (res.Errors.Count() > 0)
                //{
                //    foreach (var error in res.Errors)
                //    {
                //        ErrorMessage mess = new ErrorMessage()
                //        {
                //            field = "SuperUser",
                //            message = MsgUtils.Instance.Trls(error)
                //        };
                //        Error er = new Error();
                //        er.errors.Add(mess);
                //        return Json(Errors);
                //    }
                //}
                //else
                //{
                //    if (user.EmpId != null)
                //    {
                //        var person = _hrUnitOfWork.Repository<Person>().FirstOrDefault(a => a.Id == user.EmpId);
                //        person.WorkEmail = user.Email;
                //        person.WorkTel = user.PhoneNumber;
                //        _hrUnitOfWork.PeopleRepository.Attach(person);
                //        _hrUnitOfWork.PeopleRepository.Entry(person).State = System.Data.Entity.EntityState.Modified;
                //    }
                //    SaveChanges(user.Language);
                //}

                return(Json("OK," + ((new JavaScriptSerializer()).Serialize(model))));
            }

            return(Json(Models.Utils.ParseFormErrors(ModelState)));
        }