Ejemplo n.º 1
0
 public async Task<bool> EditAspNetUser(AspNetUser aspNetUser, string newPassword)
 {
     db.Entry(aspNetUser).State = EntityState.Modified;
     db.Entry(aspNetUser).Property(prop => prop.CreateDate).IsModified = false;
     db.Entry(aspNetUser).Property(prop => prop.UpdateDate).IsModified = false;
     db.Entry(aspNetUser).Property(prop => prop.PasswordHash).IsModified = false;
     db.Entry(aspNetUser).Property(prop => prop.SecurityStamp).IsModified = false;
     aspNetUser.Id = aspNetUser.Id.Trim();
     aspNetUser.Email = aspNetUser.Email.Trim();
     aspNetUser.PhoneNumber = aspNetUser.PhoneNumber == null ? aspNetUser.PhoneNumber : aspNetUser.PhoneNumber.Trim();
     aspNetUser.UserName = aspNetUser.UserName.Trim();
     if (newPassword != null)
     {
         Microsoft.AspNet.Identity.PasswordHasher hash = new Microsoft.AspNet.Identity.PasswordHasher();
         aspNetUser.PasswordHash = hash.HashPassword(newPassword);
     }
     try
     {
         await db.SaveChangesAsync();
         return true;
     }
     catch (Exception ex)
     {
         string errorStr = ex.Message;
         return false;
     }
 }
Ejemplo n.º 2
0
        public void ResetPassword()
        {
            try
            {
                using (var db = new LetranIntegratedSystemEntities())
                {
                    string userid = "";
                    var    a      = ((HRiSClass.AccountManagementList)dgAdmin.SelectedItem);
                    var    b      = ((HRiSClass.AccountManagementList)dgEmployee.SelectedItem);
                    var    c      = ((HRiSClass.AccountManagementList)dgFaculty.SelectedItem);
                    var    d      = ((HRiSClass.AccountManagementList)dgFacultyHead.SelectedItem);
                    var    f      = ((HRiSClass.AccountManagementList)dgGuidance.SelectedItem);
                    var    g      = ((HRiSClass.AccountManagementList)dgHR.SelectedItem);
                    var    h      = ((HRiSClass.AccountManagementList)dgRegistrar.SelectedItem);

                    if (a != null)
                    {
                        userid = a.AccountID;
                    }
                    else if (b != null)
                    {
                        userid = b.AccountID;
                    }
                    else if (c != null)
                    {
                        userid = c.AccountID;
                    }
                    else if (d != null)
                    {
                        userid = d.AccountID;
                    }
                    else if (f != null)
                    {
                        userid = f.AccountID;
                    }
                    else if (g != null)
                    {
                        userid = g.AccountID;
                    }
                    else if (h != null)
                    {
                        userid = h.AccountID;
                    }

                    if (!String.IsNullOrEmpty(userid))
                    {
                        AspNetUser search         = db.AspNetUsers.Where(m => m.Id == userid).FirstOrDefault();
                        var        passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();
                        search.PasswordHash = passwordHasher.HashPassword("letran1620");
                        db.SaveChanges();
                        MessageBox.Show("Password has been reset.", "Successful", MessageBoxButton.OK, MessageBoxImage.Information);
                        GetAccount();
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Something went wrong.", "System Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 3
0
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;
            db          = new LetranIntegratedSystemEntities();
            var passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();

            AspNetUser search  = db.AspNetUsers.Where(m => m.UserName == App.EmployeeNumber).FirstOrDefault();
            string     compare = passwordHasher.VerifyHashedPassword(search.PasswordHash, pbCurrent.Password).ToString();

            if (compare != "Success")
            {
                MessageBox.Show("Incorrect current password.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (pbNew.Password != pbVerify.Password)
            {
                MessageBox.Show("Verify password does not match.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (String.IsNullOrEmpty(pbCurrent.Password) || String.IsNullOrEmpty(pbNew.Password) || String.IsNullOrEmpty(pbVerify.Password))
            {
                MessageBox.Show("Password cannot be empty.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            search.PasswordHash = passwordHasher.HashPassword(pbVerify.Password);
            db.SaveChanges();
            MessageBox.Show("Password has been changed.", "Successful", MessageBoxButton.OK);
            pbCurrent.Clear();
            pbNew.Clear();
            pbVerify.Clear();
            this.Cursor = Cursors.Arrow;
        }
Ejemplo n.º 4
0
        public ResultModel UpdatePassword(string newPassword, string newConfirmPassword, int userId)
        {
            ResultModel resultModel = new ResultModel();

            if (newPassword == newConfirmPassword)
            {
                User user = _userRepo.GetById(userId);
                if (user != null)
                {
                    var ph   = new Microsoft.AspNet.Identity.PasswordHasher();
                    var hash = ph.HashPassword(newPassword);
                    user.Password = hash;
                    user.PasswordExpirationDate = DateTime.Now.AddDays(Convert.ToInt32(ConfigurationManager.AppSettings["ExpiryDays"]));
                    _userRepo.Update(user);
                    resultModel.IsSuccess = true;
                    resultModel.Message   = "Password changed successfully.";
                }
                else
                {
                    // do code here.
                    resultModel.IsSuccess = false;
                    resultModel.Message   = "No User Found.";
                }
            }
            else
            {
                resultModel.IsSuccess = false;
                resultModel.Message   = "The password and confirmation password do not match.";
            }
            return(resultModel);
        }
Ejemplo n.º 5
0
        private async Task <bool> CreateUserAsync([Bind(Include = "Email, Password, ConfirmPassword")] EditUserViewModel user, bool isApplicant)
        {
            var passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();
            var db             = new ApplicationDbContext();
            var newUser        = new ApplicationUser();

            newUser.Email        = user.Email;
            newUser.UserName     = user.Email;
            newUser.PasswordHash = passwordHasher.HashPassword(user.Password);

            ApplicationUserManager userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();

            var result = await userManager.CreateAsync(newUser, user.Password);

            if (result.Succeeded)
            {
                //add new user to default role
                string role = "Guest";

                if (isApplicant)
                {
                    role = "Applicant";
                }
                else
                {
                    role = "Business";
                }

                await userManager.AddToRoleAsync(newUser.Id, role);
            }

            return(result.Succeeded);
        }
        private void savebtn_Click(object sender, RoutedEventArgs e)
        {
            if (SystemClass.CheckConnection())
            {
                if (newpasswordpb.Password != confirmpasswordpb.Password)
                {
                    MessageBox.Show("Password mismatch!");
                }
                else
                {
                    Employee   employee       = db.Employees.Find(App.EmployeeID);
                    AspNetUser asp            = db.AspNetUsers.FirstOrDefault(m => m.UserName == employee.EmployeeNo);
                    var        passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();
                    asp.PasswordHash = passwordHasher.HashPassword(confirmpasswordpb.Password);
                    db.SaveChanges();
                    MessageBox.Show("Password updated successfully!");

                    var audit = new AuditTrailModel
                    {
                        Activity   = "User changes his/her password.",
                        ModuleName = this.GetType().Name,
                        EmployeeID = App.EmployeeID
                    };

                    SystemClass.InsertLog(audit);
                    this.Close();
                }
            }
            else
            {
                MessageBox.Show(SystemClass.DBConnectionErrorMessage);
            }
        }
        private void GenerateSystemAdmin(VMSDbContext context)
        {
            var systemAdminrole = context.Roles.Add(new ApplicationRole {
                Name = "SystemAdmin", Description = "System Admin"
            });

            var newSystemAdminUser = new ApplicationUser
            {
                FirstName     = "System",
                LastName      = "Admin",
                Email         = "*****@*****.**",
                PhoneNumber   = "1234567890",
                UserName      = "******",
                GenderId      = 1,
                SecurityStamp = System.Guid.NewGuid().ToString()
            };

            var passwordHash   = new Microsoft.AspNet.Identity.PasswordHasher();
            var hashedPassword = passwordHash.HashPassword("Evis@123");

            newSystemAdminUser.PasswordHash = hashedPassword;

            var systemAdminUser = context.Users.Add(newSystemAdminUser);

            systemAdminUser.Roles.Add(
                new Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole
            {
                UserId = systemAdminUser.Id,
                RoleId = systemAdminrole.Id
            });

            context.Users.AddOrUpdate(systemAdminUser);
        }
Ejemplo n.º 8
0
        private void Button1_Click(object sender, EventArgs e)
        {
            var ph = new Microsoft.AspNet.Identity.PasswordHasher <ApplicationUser>();

            hashPassword_tb.Text = ph.HashPassword(new ApplicationUser()
            {
                SecurityStamp = "45b85708-5851-45cf-998b-352"
            }, password_tb.Text);
        }
Ejemplo n.º 9
0
        //public static void GenerateLicense(DateTime expiredDate, bool isActive, bool isDemo)
        //{
        //    ImusCityHallEntities db = new ImusCityHallEntities();
        //    StringDictionary licenseCodes = new StringDictionary();
        //    licenseCodes.Add("1", "BDBR5VUAYDQD9FWJV9VSCZJNWV87UN");
        //    licenseCodes.Add("1", "KKFGXKZCSNBZBBKR24SFJJ3PEUAXC7");
        //    licenseCodes.Add("1", "RWDGUYBSE4XT9SRH6LKNSRWUY6LLGR");
        //    licenseCodes.Add("1", "NSBNT984V82SGTN342NBKHUYNEGB4C");
        //    licenseCodes.Add("1", "7Y2DRE3XCF9R2BQ36W252YFCGRBUXR");

        //    LicensingCode licenseCode = new LicensingCode();

        //}
        static void Main(string[] args)
        {
            ImusCityHallEntities db       = new ImusCityHallEntities();
            Employee             employee = new Employee();

            employee.EmployeeNo = "0000001";

            if (!db.Employees.Any(m => m.EmployeeNo == employee.EmployeeNo))
            {
                int superAdmin = SuperAdminCreation();
                //Admin Creation
                employee.FirstName    = "HalconTech";
                employee.LastName     = "HalconTech";
                employee.PrimaryEmail = "*****@*****.**";
                employee.IsAdmin      = true;
                db.Employees.Add(employee);

                AspNetRole roles = new AspNetRole();
                roles.Id   = "2";
                roles.Name = "Administrator";
                db.AspNetRoles.Add(roles);
                db.SaveChanges();

                db = new ImusCityHallEntities();
                AspNetUser     aspuser     = new AspNetUser();
                AspNetUserRole asproleuser = new AspNetUserRole();
                aspuser.Id                   = Guid.NewGuid().ToString();
                aspuser.UserName             = employee.EmployeeNo;
                aspuser.Email                = employee.PrimaryEmail;
                aspuser.EmailConfirmed       = true;
                aspuser.PhoneNumberConfirmed = false;
                aspuser.TwoFactorEnabled     = false;
                aspuser.LockoutEnabled       = true;
                aspuser.AccessFailedCount    = 0;
                aspuser.SecurityStamp        = Guid.NewGuid().ToString();
                var passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();
                aspuser.PasswordHash = passwordHasher.HashPassword("Pa$$w0rd");
                var adduser = db.AspNetUsers.Add(aspuser);
                asproleuser.UserId = adduser.Id;
                asproleuser.RoleId = "2";
                db.AspNetUserRoles.Add(asproleuser);
                db.SaveChanges();


                SubmoduleCreation();
                CreateSecurityQuestion();
                SetUserAccess(employee.EmployeeID);
                SetUserAccess(superAdmin);
                Console.WriteLine("Admin account created succesfully");
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Account is already created");
                Console.ReadLine();
            }
        }
Ejemplo n.º 10
0
        public ActionResult Edit(UserViewModel model)
        {
            if (string.IsNullOrEmpty(model.Id) && string.IsNullOrEmpty(model.Password))
            {
                ModelState.AddModelError("Password", "Требуется поле Пароль.");
            }

            if (!ModelState.IsValid)
            {
                SetRoles(model.Role);
                return(View(model));
            }
            try
            {
                using (var db = new SmDbContext())
                {
                    var user = db.AspNetUsers.FirstOrDefault(x => x.Id == model.Id);
                    if (user == null)
                    {
                        user = new AspNetUsers {
                            Id = Guid.NewGuid().ToString()
                        };
                        db.AspNetUsers.Add(user);
                        user.UserName      = model.UserName;
                        user.SecurityStamp = Guid.NewGuid().ToString();
                    }
                    user.Email       = model.Email;
                    user.Lastname    = model.Lastname;
                    user.Firstname   = model.Firstname;
                    user.PhoneNumber = model.PhoneNumber;
                    if (!string.IsNullOrEmpty(model.Password))
                    {
                        var ph = new Microsoft.AspNet.Identity.PasswordHasher();
                        user.PasswordHash = ph.HashPassword(model.Password);
                    }
                    if (!string.IsNullOrEmpty(model.Role))
                    {
                        var role = db.AspNetRoles.FirstOrDefault(x => x.Id == model.Role);
                        if (role != null)
                        {
                            user.AspNetRoles.Clear();
                            user.AspNetRoles.Add(role);
                        }
                    }
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("UserName", ex);

                SetRoles(model.Role);
                return(View(model));
            }
        }
Ejemplo n.º 11
0
        public ResultModel Login(LoginViewModel loginViewModel)
        {
            ResultModel resultModel = new ResultModel();

            if (!string.IsNullOrEmpty(loginViewModel.Email))
            {
                var  ph   = new Microsoft.AspNet.Identity.PasswordHasher();
                var  hash = ph.HashPassword(loginViewModel.Password);
                User user = _userRepo.GetByEmailOrUserName(loginViewModel.Email);
                if (user != null)
                {
                    if (ph.VerifyHashedPassword(user.Password, loginViewModel.Password).ToString() == "Success")
                    {
                        if (user.Active == 1)
                        {
                            HttpContext.Current.Session["UserType"] = user.UserType;
                            HttpContext.Current.Session["UserId"]   = Convert.ToString(user.UserID);
                            //if (user.PasswordExpirationDate != null && (DateTime.Now >= Convert.ToDateTime(user.PasswordExpirationDate.Value.AddDays(Convert.ToInt32(ConfigurationManager.AppSettings["ExpiryDays"])))))
                            if (user.PasswordExpirationDate != null && (DateTime.Now > Convert.ToDateTime(user.PasswordExpirationDate.Value)))
                            {
                                resultModel.IsPasswordExpire = true;
                                resultModel.Message          = "";
                                return(resultModel);
                            }
                            resultModel.IsSuccess = true;
                            resultModel.Message   = "";
                        }
                        else
                        {
                            resultModel.IsSuccess = false;
                            resultModel.Message   = "Your account is inactive, please contact your WFJ Administrator";
                        }
                    }
                    else
                    {
                        resultModel.IsSuccess = false;
                        resultModel.Message   = "Please enter valid password.";
                    }
                }
                else
                {
                    resultModel.IsSuccess = false;
                    resultModel.Message   = "Please enter vaild username/email address.";
                }
            }
            else
            {
                resultModel.IsSuccess = false;
                resultModel.Message   = "Email address can not be set Empty.";
            }
            return(resultModel);
        }
Ejemplo n.º 12
0
        public void EncryptionPassword()
        {
            List <User> users = _userRepo.GetAll().Where(x => x.IsPasswordHashed == false && !string.IsNullOrEmpty(x.Password)).ToList();

            foreach (User user in users)
            {
                var ph      = new Microsoft.AspNet.Identity.PasswordHasher();
                var hash    = ph.HashPassword(user.Password);
                var respnse = ph.VerifyHashedPassword(hash, user.Password);
                user.Password = hash;
                user.PasswordExpirationDate = DateTime.Now.AddDays(Convert.ToInt32(ConfigurationManager.AppSettings["ExpiryDays"]));;
                user.IsPasswordHashed       = true;
                _userRepo.Update(user);
            }
        }
Ejemplo n.º 13
0
        private void EditUser([Bind(Include = "Email, Password, ConfirmPassword")] EditUserViewModel user, string oldEmail)
        {
            var passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();
            var db             = new ApplicationDbContext();
            var editedUser     = db.Users.First(u => u.Email == oldEmail);

            editedUser.Email    = user.Email;
            editedUser.UserName = user.Email;
            if (editedUser.PasswordHash != user.Password)
            {
                editedUser.PasswordHash = passwordHasher.HashPassword(user.Password);
            }

            db.Entry(editedUser).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();
        }
Ejemplo n.º 14
0
        public ResultModel ChangePassword(int userId, string currentPassword, string newPassword, string newConfirmPassword)
        {
            ResultModel resultModel = new ResultModel();

            if (newPassword == newConfirmPassword)
            {
                User user = _userRepo.GetById(userId);
                if (user != null)
                {
                    var ph = new Microsoft.AspNet.Identity.PasswordHasher();
                    if (ph.VerifyHashedPassword(user.Password, currentPassword).ToString() == "Success")
                    {
                        if (user.Active == 1)
                        {
                            var hash = ph.HashPassword(newPassword);
                            user.Password = hash;
                            user.PasswordExpirationDate = DateTime.Now.AddDays(Convert.ToInt32(ConfigurationManager.AppSettings["ExpiryDays"]));
                            _userRepo.Update(user);
                            resultModel.IsSuccess = true;
                            resultModel.Message   = "Password changed successfully.";
                        }
                        else
                        {
                            resultModel.IsSuccess = false;
                            resultModel.Message   = "Your account is inactive, please contact your WFJ Administrator";
                        }
                    }
                    else
                    {
                        resultModel.IsSuccess = false;
                        resultModel.Message   = "The current password is incorrect.";
                    }
                }
                else
                {
                    // do code here.
                    resultModel.IsSuccess = false;
                    resultModel.Message   = "No User Found.";
                }
            }
            else
            {
                resultModel.IsSuccess = false;
                resultModel.Message   = "The password and confirmation password do not match.";
            }
            return(resultModel);
        }
Ejemplo n.º 15
0
        public static int SuperAdminCreation()
        {
            ImusCityHallEntities db       = new ImusCityHallEntities();
            Employee             employee = new Employee();

            employee.EmployeeNo   = "123456";
            employee.FirstName    = "HalconTech";
            employee.LastName     = "HalconTech";
            employee.PrimaryEmail = "*****@*****.**";
            employee.IsAdmin      = true;
            db.Employees.Add(employee);

            AspNetRole roles = new AspNetRole();

            roles.Id   = "1";
            roles.Name = "Super Administrator";
            db.AspNetRoles.Add(roles);
            db.SaveChanges();

            db = new ImusCityHallEntities();
            AspNetUser     aspuser     = new AspNetUser();
            AspNetUserRole asproleuser = new AspNetUserRole();

            aspuser.Id                   = Guid.NewGuid().ToString();
            aspuser.UserName             = employee.EmployeeNo;
            aspuser.Email                = employee.PrimaryEmail;
            aspuser.EmailConfirmed       = true;
            aspuser.PhoneNumberConfirmed = false;
            aspuser.TwoFactorEnabled     = false;
            aspuser.LockoutEnabled       = true;
            aspuser.AccessFailedCount    = 0;
            aspuser.SecurityStamp        = Guid.NewGuid().ToString();
            var passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();

            aspuser.PasswordHash = passwordHasher.HashPassword("Pa$$w0rd");
            var adduser = db.AspNetUsers.Add(aspuser);

            asproleuser.UserId = adduser.Id;
            asproleuser.RoleId = "1";
            db.AspNetUserRoles.Add(asproleuser);

            db.SaveChanges();


            return(employee.EmployeeID);
        }
        public ActionResult Login()
        {
            HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies[".ASPXAUTH"];
            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                if (authTicket != null & !authTicket.Expired)
                {
                    return RedirectToAction("Index", "Dashboard");
                }
            }

            string test = System.Guid.NewGuid().ToString();
            var passwordHash = new Microsoft.AspNet.Identity.PasswordHasher();
            var hashedPassword = passwordHash.HashPassword("Evis@123");
            return View();
        }
Ejemplo n.º 17
0
        public ActionResult Login()
        {
            HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies[".ASPXAUTH"];

            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                if (authTicket != null & !authTicket.Expired)
                {
                    return(RedirectToAction("Index", "Dashboard"));
                }
            }

            string test           = System.Guid.NewGuid().ToString();
            var    passwordHash   = new Microsoft.AspNet.Identity.PasswordHasher();
            var    hashedPassword = passwordHash.HashPassword("Evis@123");

            return(View());
        }
Ejemplo n.º 18
0
        private void GenerateSystemAdmin(VMSContext context)
        {
            var systemAdminrole = context.Roles.Add(new ApplicationRole {
                Name = "SuperAdmin", Description = "SuperAdmin", IsActive = true
            });


            var newSystemAdminUser = new ApplicationUser
            {
                FullName             = "Super Admin",
                Email                = "*****@*****.**",
                PhoneNumber          = "1234567890",
                UserName             = "******",
                GenderId             = 1,
                Nationality          = 3,
                IsActive             = true,
                EmailConfirmed       = false,
                PhoneNumberConfirmed = false,
                TwoFactorEnabled     = false,
                LockoutEnabled       = false,
                AccessFailedCount    = 0,
                SecurityStamp        = System.Guid.NewGuid().ToString(),
                ThemeName            = "theme1",
                ProfilePicturePath   = null,
                IsImageAvailable     = false
            };

            var passwordHash   = new Microsoft.AspNet.Identity.PasswordHasher();
            var hashedPassword = passwordHash.HashPassword("Admin@123");

            newSystemAdminUser.PasswordHash = hashedPassword;

            var systemAdminUser = context.Users.Add(newSystemAdminUser);

            systemAdminUser.Roles.Add(
                new Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole
            {
                UserId = systemAdminUser.Id,
                RoleId = systemAdminrole.Id
            });

            context.Users.AddOrUpdate(systemAdminUser);
        }
Ejemplo n.º 19
0
        // GET api/values
        public IEnumerable <string> Get()
        {
            var a1  = new Microsoft.AspNet.Identity.PasswordHasher();
            var ppp = a1.HashPassword("Nss#222222");


            var ph  = new Microsoft.AspNet.Identity.PasswordHasher <ApplicationUser>();
            var pwd = ph.HashPassword(new ApplicationUser()
            {
                UserName      = "******",
                SecurityStamp = "18076d02-6d8f-420d-b150-50531f18123f"
            }, "Nss#222222");



            var sss = ph.VerifyHashedPassword(new ApplicationUser()
            {
                SecurityStamp = "08076d02-6d8f-420d-b150-50531f18105f"
            }, "ADhVPnM6XRHONiJbNP4zQEc0KzQUQl3a/d0XF4aub9yF+A49vck7qTEIrCbDAbZqww==", "Nss#123456").ToString();

            return(new string[] { pwd, "ADhVPnM6XRHONiJbNP4zQEc0KzQUQl3a/d0XF4aub9yF+A49vck7qTEIrCbDAbZqww==", sss, ppp });
        }
Ejemplo n.º 20
0
 private void resetpasswordbtn_Click(object sender, RoutedEventArgs e)
 {
     if (SystemClass.CheckConnection())
     {
         ImusCityHallEntities db = new ImusCityHallEntities();
         if (employeelistlb.SelectedValue == null)
         {
             MessageBox.Show("Please select an employee");
         }
         else
         {
             var        employee       = db.Employees.Find((int)employeelistlb.SelectedValue);
             AspNetUser aspuser        = db.AspNetUsers.FirstOrDefault(m => m.UserName == employee.EmployeeNo);
             var        passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();
             aspuser.PasswordHash = passwordHasher.HashPassword("imuscitygov");
             db.SaveChanges();
             MessageBox.Show("Employee account has been reset to" + Environment.NewLine + "Default Password: imuscitygov");
         }
     }
     else
     {
         MessageBox.Show(SystemClass.DBConnectionErrorMessage);
     }
 }
Ejemplo n.º 21
0
        private void Button1_Click(object sender, EventArgs e)
        {
            var ph = new Microsoft.AspNet.Identity.PasswordHasher();

            textBox1.Text = ph.HashPassword("111111!");
        }
Ejemplo n.º 22
0
 public async Task<bool> CreateAspNetUser(AspNetUser aspNetUser)
 {
     aspNetUser.CreateDate = DateTime.UtcNow;
     aspNetUser.UpdateDate = DateTime.UtcNow;
     aspNetUser.Id = Guid.NewGuid().ToString();
     Microsoft.AspNet.Identity.PasswordHasher hash = new Microsoft.AspNet.Identity.PasswordHasher();
     aspNetUser.PasswordHash = hash.HashPassword(aspNetUser.PasswordHash.Trim());
     aspNetUser.SecurityStamp = Guid.NewGuid().ToString();
     db.AspNetUsers.Add(aspNetUser);
     try
     {
         await db.SaveChangesAsync();
         return true;
     }
     catch (Exception ex)
     {
         return false;
     }
 }
Ejemplo n.º 23
0
        public void AddOrUpdate(ManagerUserFilterViewModel managerUserFilterViewModel)
        {
            var ph = new Microsoft.AspNet.Identity.PasswordHasher();

            try
            {
                if (managerUserFilterViewModel.userViewModel.UserID > 0)
                {
                    if (!CheckDuplicateByEmailAndUser(managerUserFilterViewModel.userViewModel.Email, managerUserFilterViewModel.userViewModel.UserID))
                    {
                        User user = _userRepo.GetById(managerUserFilterViewModel.userViewModel.UserID);
                        user.UserName      = managerUserFilterViewModel.userViewModel.FirstName + managerUserFilterViewModel.userViewModel.LastName;
                        user.FirstName     = managerUserFilterViewModel.userViewModel.FirstName;
                        user.LastName      = managerUserFilterViewModel.userViewModel.LastName;
                        user.Telephone     = managerUserFilterViewModel.userViewModel.Telephone;
                        user.Address1      = managerUserFilterViewModel.userViewModel.Address1;
                        user.Address2      = managerUserFilterViewModel.userViewModel.Address2;
                        user.City          = managerUserFilterViewModel.userViewModel.City;
                        user.State         = managerUserFilterViewModel.userViewModel.State;
                        user.PostalCode    = managerUserFilterViewModel.userViewModel.PostalCode;
                        user.EMail         = managerUserFilterViewModel.userViewModel.Email;
                        user.UserType      = managerUserFilterViewModel.userViewModel.UserType;
                        user.dashboardUser = managerUserFilterViewModel.userViewModel.IsDashboardUser;
                        user.Active        = managerUserFilterViewModel.userViewModel.IsActive;
                        user.ManagerUserID = managerUserFilterViewModel.userViewModel.ManagerUserId > 0 ? managerUserFilterViewModel.userViewModel.ManagerUserId : null;
                        user.UserAccess    = managerUserFilterViewModel.userViewModel.AccessLevelId;
                        _userRepo.Update(user);
                        _userClientRepo.DeleteByUserId(managerUserFilterViewModel.userViewModel.UserID);
                        if (managerUserFilterViewModel.userViewModel.ClientId != null)
                        {
                            foreach (var itemId in managerUserFilterViewModel.userViewModel.ClientId)
                            {
                                UserClient uClient = new UserClient()
                                {
                                    UserID   = managerUserFilterViewModel.userViewModel.UserID,
                                    ClientID = Convert.ToInt32(itemId)
                                };
                                _userClientRepo.Add(uClient);
                            }
                        }
                        _userLevelsRepo.DeleteByUserId(managerUserFilterViewModel.userViewModel.UserID);
                        if (managerUserFilterViewModel.userViewModel.RegionId != null)
                        {
                            foreach (var itemId in managerUserFilterViewModel.userViewModel.RegionId)
                            {
                                UserLevel userLevel = new UserLevel()
                                {
                                    UserID  = managerUserFilterViewModel.userViewModel.UserID,
                                    LevelID = Convert.ToInt32(itemId)
                                };
                                _userLevelsRepo.Add(userLevel);
                            }
                        }
                        _formUsersRepo.DeleteByUserId(managerUserFilterViewModel.userViewModel.UserID);
                        if (managerUserFilterViewModel.userViewModel.FormId != null)
                        {
                            foreach (var itemId in managerUserFilterViewModel.userViewModel.FormId)
                            {
                                FormUser uClient = new FormUser()
                                {
                                    UserID = managerUserFilterViewModel.userViewModel.UserID,
                                    FormID = Convert.ToInt32(itemId)
                                };
                                _formUsersRepo.Add(uClient);
                            }
                        }
                        managerUserFilterViewModel.IsSuccess = true;
                        managerUserFilterViewModel.Message   = "Record Updated Successfully.";
                    }
                    else
                    {
                        managerUserFilterViewModel.IsSuccess = false;
                        managerUserFilterViewModel.Message   = "Email address already exist.";
                    }
                }
                else
                {
                    if (!CheckDuplicateByEmail(managerUserFilterViewModel.userViewModel.Email))
                    {
                        User user = new User()
                        {
                            UserName               = managerUserFilterViewModel.userViewModel.FirstName + managerUserFilterViewModel.userViewModel.LastName,
                            Password               = ph.HashPassword(managerUserFilterViewModel.userViewModel.Password),
                            FirstName              = managerUserFilterViewModel.userViewModel.FirstName,
                            LastName               = managerUserFilterViewModel.userViewModel.LastName,
                            Telephone              = managerUserFilterViewModel.userViewModel.Telephone,
                            Address1               = managerUserFilterViewModel.userViewModel.Address1,
                            Address2               = managerUserFilterViewModel.userViewModel.Address2,
                            City                   = managerUserFilterViewModel.userViewModel.City,
                            State                  = managerUserFilterViewModel.userViewModel.State,
                            PostalCode             = managerUserFilterViewModel.userViewModel.PostalCode,
                            EMail                  = managerUserFilterViewModel.userViewModel.Email,
                            UserType               = managerUserFilterViewModel.userViewModel.UserType,
                            dashboardUser          = managerUserFilterViewModel.userViewModel.IsDashboardUser,
                            Active                 = managerUserFilterViewModel.userViewModel.IsActive,
                            DateAdded              = DateTime.Now,
                            PasswordExpirationDate = DateTime.Now.AddDays(Convert.ToInt32(ConfigurationManager.AppSettings["ExpiryDays"])),
                            IsPasswordHashed       = false,
                            ManagerUserID          = managerUserFilterViewModel.userViewModel.ManagerUserId > 0? managerUserFilterViewModel.userViewModel.ManagerUserId:null,
                            UserAccess             = managerUserFilterViewModel.userViewModel.AccessLevelId
                        };
                        _userRepo.Add(user);
                        if (user.UserID > 0 && (managerUserFilterViewModel.userViewModel.ClientId != null))
                        {
                            foreach (var itemId in managerUserFilterViewModel.userViewModel.ClientId)
                            {
                                UserClient dClient = new UserClient()
                                {
                                    UserID   = user.UserID,
                                    ClientID = Convert.ToInt32(itemId)
                                };
                                _userClientRepo.Add(dClient);
                            }
                        }
                        if (user.UserID > 0 && (managerUserFilterViewModel.userViewModel.RegionId != null))
                        {
                            foreach (var itemId in managerUserFilterViewModel.userViewModel.RegionId)
                            {
                                UserLevel userLevel = new UserLevel()
                                {
                                    UserID  = user.UserID,
                                    LevelID = Convert.ToInt32(itemId)
                                };
                                _userLevelsRepo.Add(userLevel);
                            }
                        }
                        if (user.UserID > 0 && (managerUserFilterViewModel.userViewModel.FormId != null))
                        {
                            foreach (var itemId in managerUserFilterViewModel.userViewModel.FormId)
                            {
                                FormUser formUser = new FormUser()
                                {
                                    UserID = user.UserID,
                                    FormID = Convert.ToInt32(itemId)
                                };
                                _formUsersRepo.Add(formUser);
                            }
                        }

                        managerUserFilterViewModel.IsSuccess = true;
                        managerUserFilterViewModel.Message   = "Record Inserted Successfully.";
                    }
                    else
                    {
                        managerUserFilterViewModel.IsSuccess = false;
                        managerUserFilterViewModel.Message   = "Email address already exist.";
                    }
                }
            }
            catch (Exception ex)
            {
                managerUserFilterViewModel.IsSuccess = false;
                managerUserFilterViewModel.Message   = "Sorry, An error occurred!";
            }
        }
Ejemplo n.º 24
0
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (var db = new LetranIntegratedSystemEntities())
                {
                    AspNetUser     aspuser     = new AspNetUser();
                    AspNetUserRole asproleuser = new AspNetUserRole();
                    int            EmpID       = Convert.ToInt32(cbEmp.SelectedValue);
                    var            emp         = db.Employees.Find(EmpID);
                    var            user        = db.AspNetUsers.Where(m => m.UserName == emp.EmployeeNo).FirstOrDefault();
                    if (user != null)
                    {
                        MessageBox.Show("User account for this person already exists!", "System Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    else
                    {
                        if (String.IsNullOrEmpty(cbRole.Text))
                        {
                            MessageBox.Show("Role is not specified", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }
                        if (String.IsNullOrEmpty(txtEmail.Text))
                        {
                            MessageBox.Show("Email cannot be empty.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }
                        string roleid = cbRole.SelectedValue.ToString();

                        aspuser.Id                   = Guid.NewGuid().ToString();
                        aspuser.UserName             = emp.EmployeeNo;
                        aspuser.Email                = emp.PrimaryEmail;
                        aspuser.EmailConfirmed       = true;
                        aspuser.PhoneNumberConfirmed = false;
                        aspuser.TwoFactorEnabled     = false;
                        aspuser.LockoutEnabled       = true;
                        aspuser.AccessFailedCount    = 0;
                        aspuser.SecurityStamp        = Guid.NewGuid().ToString();
                        var passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();
                        aspuser.PasswordHash = passwordHasher.HashPassword("letran1620");
                        var adduser = db.AspNetUsers.Add(aspuser);
                        asproleuser.UserId = adduser.Id;
                        asproleuser.RoleId = roleid;
                        db.AspNetUserRoles.Add(asproleuser);

                        if (roleid == "5")
                        {
                            if (db.Faculties.Where(m => m.EmpNo == emp.EmployeeNo).FirstOrDefault() == null)
                            {
                                Faculty f = new Faculty();
                                f.FacultyCode = emp.EmployeeNo;
                                f.EmpNo       = emp.EmployeeNo;
                                db.Faculties.Add(f);
                            }
                        }
                        db.SaveChanges();
                        MessageBox.Show("Account successfully created.", "System Success", MessageBoxButton.OK, MessageBoxImage.Information);
                        this.Close();
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Something went wrong.", "System Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 25
0
        private void btnADD_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Mouse.OverrideCursor = Cursors.Wait;
                db = new LetranIntegratedSystemEntities();
                Employee       emp         = new Employee();
                AspNetUser     aspuser     = new AspNetUser();
                AspNetUserRole asproleuser = new AspNetUserRole();
                string         roleid      = "";


                int deptid      = Convert.ToInt32(cbDepartment.SelectedValue);
                int facareaid   = Convert.ToInt32(cbFacultyArea.SelectedValue);
                int statid      = Convert.ToInt32(cbStatus.SelectedValue);
                int desigid     = Convert.ToInt32(cbDesignation.SelectedValue);
                int posid       = Convert.ToInt32(cbEmployeePosition.SelectedValue);
                int lvlid       = Convert.ToInt32(cbLevel.SelectedValue);
                int resareaid   = Convert.ToInt32(cbArea.SelectedValue);
                int reszipcode  = Convert.ToInt32(cbZipcode.SelectedValue);
                int provareaid  = Convert.ToInt32(cbProvArea.SelectedValue);
                int provzipcode = Convert.ToInt32(cbProvZipcode.SelectedValue);
                int emptypeid   = Convert.ToInt32(cbEmpType.SelectedValue);

                if (String.IsNullOrEmpty(txtEmpNumber.Text) || String.IsNullOrEmpty(cbDepartment.Text) || String.IsNullOrEmpty(cbStatus.Text) ||
                    String.IsNullOrEmpty(cbDesignation.Text) || String.IsNullOrEmpty(cbEmployeePosition.Text) || String.IsNullOrEmpty(dpHired.Text) ||
                    String.IsNullOrEmpty(cbSalutation.Text) || String.IsNullOrEmpty(txtLastName.Text) || String.IsNullOrEmpty(txtFirstName.Text) ||
                    String.IsNullOrEmpty(txtCitizenship.Text) || String.IsNullOrEmpty(cbStatus.Text) || String.IsNullOrEmpty(txtReligion.Text) || String.IsNullOrEmpty(txtCity.Text))
                {
                    MessageBox.Show("Please fill up necessary fields.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    Mouse.OverrideCursor = null;
                    return;
                }
                if (db.Employees.Where(m => m.EmployeeNo == txtEmpNumber.Text).FirstOrDefault() != null)
                {
                    MessageBox.Show("Employee number already exists!", "System Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Mouse.OverrideCursor = null;
                    return;
                }
                if (db.Employees.Where(m => m.FirstName.Trim().ToUpper() == txtFirstName.Text.Trim().ToUpper() && m.LastName.Trim().ToUpper() == txtLastName.Text.Trim().ToUpper() && m.MiddleName.Trim().ToUpper() == (String.IsNullOrEmpty(txtMiddleName.Text) ? " " : txtMiddleName.Text.Trim().ToUpper())).FirstOrDefault() != null)
                {
                    MessageBox.Show("Employee already exists!!", "System Warning", MessageBoxButton.OK, MessageBoxImage.Error);
                    Mouse.OverrideCursor = null;
                    return;
                }
                emp.EmployeeNo = txtEmpNumber.Text;
                emp.Title      = cbSalutation.Text;
                emp.LastName   = txtLastName.Text;
                emp.FirstName  = txtFirstName.Text;
                emp.MiddleName = String.IsNullOrEmpty(txtMiddleName.Text) ? " " : txtMiddleName.Text;
                emp.Nickname   = txtNickName.Text;
                if (emptypeid != 0)
                {
                    emp.EmploymentTypeID = emptypeid;
                }
                if (deptid != 0)
                {
                    emp.EmployeeDepartmentID = deptid;
                }
                if (facareaid != 0)
                {
                    emp.FacultyAreaID = facareaid;
                }
                if (statid != 0)
                {
                    emp.EmployeeStatusID = statid;
                }
                if (desigid != 0)
                {
                    emp.EmployeeDesignation = desigid;
                }
                if (posid != 0)
                {
                    emp.EmployeePositionID = posid;
                }
                if (lvlid != 0)
                {
                    emp.EmployeeLevelID = lvlid;
                }
                if (!String.IsNullOrEmpty(dpHired.Text))
                {
                    emp.DateHired = Convert.ToDateTime(dpHired.SelectedDate);
                }
                if (!String.IsNullOrEmpty(dpPermanency.Text))
                {
                    emp.DatePermanency = Convert.ToDateTime(dpPermanency.SelectedDate);
                }
                if (!String.IsNullOrEmpty(dpEndo.Text))
                {
                    emp.DateEndContract = Convert.ToDateTime(dpEndo.SelectedDate);
                }
                emp.ReasonForLeaving      = txtReason.Text;
                emp.OtherReasonForLeaving = txtReason.Text;
                if (!String.IsNullOrEmpty(dpResigned.Text))
                {
                    emp.DateResigned = Convert.ToDateTime(dpResigned.SelectedDate);
                }
                if (!String.IsNullOrEmpty(dpRetirement.Text))
                {
                    emp.DateRetired = Convert.ToDateTime(dpRetirement.SelectedDate);
                }
                emp.ResidentialAddress = txtCity.Text;
                if (resareaid != 0)
                {
                    emp.ResidentialAreaID = resareaid;
                }
                if (reszipcode != 0)
                {
                    emp.ResidentialZipCodeID = reszipcode;
                }
                emp.ProvincialAddress = txtProvAddress.Text;
                if (provareaid != 0)
                {
                    emp.ProvincialAreaID = provareaid;
                }
                if (provzipcode != 0)
                {
                    emp.ProvincialZipCodeID = provzipcode;
                }
                emp.TelephoneNo           = txtTelno.Text;
                emp.ProvincialTelephoneNo = txtProvTelno.Text;
                emp.MobileNo       = txtMobileno.Text;
                emp.PrimaryEmail   = txtLetranEmail.Text;
                emp.SecondaryEmail = txtAlternateEmail.Text;
                emp.Sex            = rbMale.IsChecked == true ? "M" : "F";
                if (!String.IsNullOrEmpty(dpBirthday.Text))
                {
                    emp.Birthday = Convert.ToDateTime(dpBirthday.SelectedDate);
                }
                emp.Birthplace  = txtPlaceBirth.Text;
                emp.CivilStatus = cbCivilStatus.Text.Substring(0, 1);
                emp.Nationality = txtCitizenship.Text;
                emp.Religion    = txtReligion.Text;
                emp.TaxStatus   = cbTax.Text;
                emp.TIN         = txtTIN.Text;
                emp.SSS         = txtSSS.Text;
                emp.PAG_IBIG    = txtPagibig.Text;
                emp.PhilHealth  = txtPhilhealth.Text;
                emp.CedulaNo    = txtCertificateNumber.Text;
                if (!String.IsNullOrEmpty(dpRC.Text))
                {
                    emp.CedulaDate = Convert.ToDateTime(dpRC.SelectedDate).ToLongDateString();
                }
                emp.CedulaPlace = txtRCPlace.Text;
                emp.DateEncoded = DateTime.Now;
                emp.Archive     = chkActive.IsChecked == true ? false : true;
                if (!String.IsNullOrEmpty(txtPic.Text))
                {
                    emp.Photo = File.ReadAllBytes(txtPic.Text);
                }
                var newemp = db.Employees.Add(emp);
                db.SaveChanges();

                if (newemp.EmployeeDesignation == 1 || newemp.EmployeeDepartmentID == 19)
                {
                    roleid = "2";
                }
                if (newemp.EmployeeDesignation == 2)
                {
                    roleid = "5";
                }
                if (newemp.EmployeeDepartmentID == 34)
                {
                    roleid = "9";
                }
                else if (newemp.EmployeeDepartmentID == 35)
                {
                    roleid = "10";
                }
                else if (newemp.EmployeeDepartmentID == 18)
                {
                    roleid = "8";
                }
                else
                {
                    roleid = "4";
                }

                if (db.AspNetUsers.Where(m => m.UserName == newemp.EmployeeNo).FirstOrDefault() != null)
                {
                    MessageBox.Show("User account for this person already exists!", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                else if (db.AspNetUsers.Where(m => m.Email == newemp.PrimaryEmail && m.Email != "").FirstOrDefault() != null)
                {
                    MessageBox.Show("Email already exists!", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                else
                {
                    if (String.IsNullOrEmpty(roleid))
                    {
                        MessageBox.Show("Role is not specified", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    else
                    {
                        aspuser.Id                   = Guid.NewGuid().ToString();
                        aspuser.UserName             = newemp.EmployeeNo;
                        aspuser.Email                = newemp.PrimaryEmail;
                        aspuser.EmailConfirmed       = true;
                        aspuser.PhoneNumberConfirmed = false;
                        aspuser.TwoFactorEnabled     = false;
                        aspuser.LockoutEnabled       = true;
                        aspuser.AccessFailedCount    = 0;
                        aspuser.SecurityStamp        = Guid.NewGuid().ToString();
                        var passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();
                        aspuser.PasswordHash = passwordHasher.HashPassword("letran1620");
                        var adduser = db.AspNetUsers.Add(aspuser);
                        asproleuser.UserId = adduser.Id;
                        asproleuser.RoleId = roleid;
                        db.AspNetUserRoles.Add(asproleuser);
                    }
                }

                if (dgEmpEduc.Items.Count > 0)
                {
                    foreach (HRiSClass.EmployeeAddEducationList x in dgEmpEduc.ItemsSource)
                    {
                        EmployeeEducation ee = new EmployeeEducation();
                        ee.EmployeeID     = newemp.EmployeeID;
                        ee.EducationType  = x.EducationType;
                        ee.Institution    = x.Institution;
                        ee.Degree         = x.Degree;
                        ee.GraduationDate = x.Graduation;
                        ee.Awards         = x.Award;
                        db.EmployeeEducations.Add(ee);
                    }
                }

                //Work Experience
                if (dgWorkExp.Items.Count > 0)
                {
                    foreach (HRiSClass.EmployeeAddWorkList x in dgWorkExp.ItemsSource)
                    {
                        EmployeeWork ew = new EmployeeWork();
                        ew.EmployeeID    = newemp.EmployeeID;
                        ew.Company       = x.Company;
                        ew.WorkPosition  = x.Position;
                        ew.InclusiveDate = x.InclusiveDate;
                        ew.Salary        = x.LastSalary;
                        ew.ReasonLeaving = x.Reason;
                        db.EmployeeWorks.Add(ew);
                    }
                }

                //Semniars
                if (dgSeminars.Items.Count > 0)
                {
                    foreach (HRiSClass.EmployeeAddSeminarList x in dgSeminars.ItemsSource)
                    {
                        EmployeeSeminar es = new EmployeeSeminar();
                        es.EmployeeID    = newemp.EmployeeID;
                        es.Title         = x.Seminar;
                        es.InclusiveDate = x.InclusiveDate;
                        es.Venue         = x.Venue;
                        db.EmployeeSeminars.Add(es);
                    }
                }

                db.SaveChanges();
                TextClear();
                MessageBox.Show("Successfully Addedd.", "System Success", MessageBoxButton.OK, MessageBoxImage.Information);
                Mouse.OverrideCursor = null;
            }
            catch (Exception)
            {
                MessageBox.Show("Something went wrong.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Ejemplo n.º 26
0
        private void addAcct_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                db = new LetranIntegratedSystemEntities();
                string         roleid      = "";
                AspNetUser     aspuser     = new AspNetUser();
                AspNetUserRole asproleuser = new AspNetUserRole();
                var            x           = ((EmployeeClass)dgEmployeeList.SelectedItem);
                var            user        = db.AspNetUsers.Where(m => m.UserName == x.EmployeeNumber).FirstOrDefault();
                if (user != null)
                {
                    MessageBox.Show("User account for this person already exists!", "System Information", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                else
                {
                    var emp = db.Employees.Where(m => m.EmployeeNo == x.EmployeeNumber).FirstOrDefault();

                    roleid = "4";

                    //if (emp.EmployeeDesignation == 1 || emp.EmployeeDepartmentID == 19)
                    //{
                    //    roleid = "2";
                    //}
                    //if (emp.EmployeeDesignation == 2)
                    //{
                    //    roleid = "5";
                    //}
                    //if (emp.EmployeeDepartmentID == 34)
                    //{
                    //    roleid = "9";
                    //}
                    //else if (emp.EmployeeDepartmentID == 35)
                    //{
                    //    roleid = "10";
                    //}
                    //else if (emp.EmployeeDepartmentID == 18)
                    //{
                    //    roleid = "8";
                    //}

                    if (String.IsNullOrEmpty(roleid))
                    {
                        MessageBox.Show("Role is not specified", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    if (String.IsNullOrEmpty(emp.PrimaryEmail))
                    {
                        MessageBox.Show("Email cannot be empty.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    aspuser.Id                   = Guid.NewGuid().ToString();
                    aspuser.UserName             = emp.EmployeeNo;
                    aspuser.Email                = emp.PrimaryEmail;
                    aspuser.EmailConfirmed       = true;
                    aspuser.PhoneNumberConfirmed = false;
                    aspuser.TwoFactorEnabled     = false;
                    aspuser.LockoutEnabled       = true;
                    aspuser.AccessFailedCount    = 0;
                    aspuser.SecurityStamp        = Guid.NewGuid().ToString();
                    var passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();
                    aspuser.PasswordHash = passwordHasher.HashPassword("letran1620");
                    var adduser = db.AspNetUsers.Add(aspuser);
                    asproleuser.UserId = adduser.Id;
                    asproleuser.RoleId = roleid;
                    db.AspNetUserRoles.Add(asproleuser);

                    if (roleid == "5")
                    {
                        if (db.Faculties.Where(m => m.EmpNo == emp.EmployeeNo).FirstOrDefault() == null)
                        {
                            Faculty f = new Faculty();
                            f.FacultyCode = emp.EmployeeNo;
                            f.EmpNo       = emp.EmployeeNo;
                            db.Faculties.Add(f);
                        }
                    }
                    db.SaveChanges();
                    MessageBox.Show("Account successfully created.", "System Success", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Something went wrong.", "System Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        //Insertion of new employee information
        private void savebtn_Click(object sender, RoutedEventArgs e)
        {
            if (SystemClass.CheckConnection())
            {
                Mouse.OverrideCursor = Cursors.Wait;
                try
                {
                    ImusCityHallEntities db       = new ImusCityHallEntities();
                    Employee             employee = new Employee();

                    string   birthdateInput = birthdatedp.Text;
                    DateTime returnBirthDate;

                    string   dateHiredInput = datehiredp.Text;
                    DateTime returnDateHired;

                    if (db.Employees.Where(m => m.EmployeeNo == employeenotb.Text).FirstOrDefault() != null)
                    {
                        MessageBox.Show("Employee number already exists!", "System Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        Mouse.OverrideCursor = null;
                        return;
                    }
                    else if (String.IsNullOrEmpty(fnametb.Text))
                    {
                        MessageBox.Show("Please enter first name");
                        Mouse.OverrideCursor = null;
                    }
                    else if (String.IsNullOrEmpty(lnametb.Text))
                    {
                        MessageBox.Show("Please enter last name");
                        Mouse.OverrideCursor = null;
                    }
                    else if (String.IsNullOrEmpty(permaddtb.Text))
                    {
                        MessageBox.Show("Please enter permanent address");
                        Mouse.OverrideCursor = null;
                    }
                    else if (String.IsNullOrEmpty(primaryemailtb.Text))
                    {
                        MessageBox.Show("Please enter primary email");
                        Mouse.OverrideCursor = null;
                    }
                    else if (String.IsNullOrEmpty(employeenotb.Text))
                    {
                        MessageBox.Show("Please enter employee number");
                        Mouse.OverrideCursor = null;
                    }
                    else if (String.IsNullOrEmpty(datehiredp.Text))
                    {
                        MessageBox.Show("Please enter date hired");
                        Mouse.OverrideCursor = null;
                    }
                    else if (divisioncb.SelectedValue == null)
                    {
                        MessageBox.Show("Please select employee division");
                        Mouse.OverrideCursor = null;
                    }
                    else if (positioncb.SelectedValue == null)
                    {
                        MessageBox.Show("Please select employee position");
                        Mouse.OverrideCursor = null;
                    }
                    else if (statuscb.SelectedValue == null)
                    {
                        MessageBox.Show("Please select employee status");
                        Mouse.OverrideCursor = null;
                    }
                    else if (String.IsNullOrEmpty(birthdatedp.Text))
                    {
                        MessageBox.Show("Please enter birthday");
                        Mouse.OverrideCursor = null;
                    }
                    else if (String.IsNullOrEmpty(birthplacetb.Text))
                    {
                        MessageBox.Show("Please enter birthplace");
                        Mouse.OverrideCursor = null;
                    }
                    else if (genderdp.SelectedValue == null)
                    {
                        MessageBox.Show("Please select gender");
                        Mouse.OverrideCursor = null;
                    }
                    else if (String.IsNullOrEmpty(mobilenotb.Text))
                    {
                        MessageBox.Show("Please enter mobile number");
                        Mouse.OverrideCursor = null;
                    }
                    else if (!DateTime.TryParse(birthdateInput, out returnBirthDate))
                    {
                        MessageBox.Show("Please enter valid date format for birthdate (mm/dd/yyyy)");
                    }
                    else if (!DateTime.TryParse(dateHiredInput, out returnDateHired))
                    {
                        MessageBox.Show("Please enter valid date format for date hired (mm/dd/yyyy)");
                    }
                    else if (CheckNumberOfUser())
                    {
                        Mouse.OverrideCursor = null;
                        MessageBox.Show("Maximum number of users already reached. Please contact your vendor");
                    }
                    else
                    {
                        employee.EmployeeNo = employeenotb.Text;

                        int DivID, PosID, StatID;

                        //Employee Information
                        employee.EmployeeDivisionID = Int32.TryParse(divisioncb.SelectedValue.ToString(), out DivID) ? DivID : (int?)null;
                        employee.EmployeePositionID = Int32.TryParse(positioncb.SelectedValue.ToString(), out PosID) ? PosID : (int?)null;
                        employee.EmployeeStatusID   = Int32.TryParse(statuscb.SelectedValue.ToString(), out StatID) ? StatID : (int?)null;
                        employee.DateHired          = String.IsNullOrEmpty(datehiredp.Text) ? null : datehiredp.SelectedDate;
                        employee.DatePermanency     = String.IsNullOrEmpty(datepermanetdp.Text) ? null : datepermanetdp.SelectedDate;
                        employee.DateEndContract    = String.IsNullOrEmpty(dateendodp.Text) ? null : dateendodp.SelectedDate;
                        employee.DateResigned       = String.IsNullOrEmpty(dateresignationdp.Text) ? null : dateresignationdp.SelectedDate;

                        //Personal Information
                        employee.FirstName   = fnametb.Text;
                        employee.MiddleName  = mnametb.Text;
                        employee.LastName    = lnametb.Text;
                        employee.NameSuffix  = namesuffixtb.Text;
                        employee.Birthday    = birthdatedp.SelectedDate;
                        employee.Birthplace  = birthplacetb.Text;
                        employee.Sex         = genderdp.SelectionBoxItem.ToString().Substring(0, 1);
                        employee.Nationality = citizenshiptb.Text;
                        employee.CivilStatus = civilstatuscb.SelectionBoxItem.ToString();
                        employee.Religion    = religiontb.Text;
                        employee.TIN         = tinnotb.Text;
                        employee.SSS         = sssnotb.Text;
                        employee.PhilHealth  = philhealthnotb.Text;
                        employee.PAG_IBIG    = pagibignotb.Text;

                        //Contact Information
                        employee.PermanentAddress = permaddtb.Text;
                        employee.CurrentAddress   = currentadd.Text;
                        employee.TelephoneNo      = landlinenotb.Text;
                        employee.MobileNo         = mobilenotb.Text;
                        employee.PrimaryEmail     = primaryemailtb.Text;
                        employee.SecondaryEmail   = secondaryemailtb.Text;

                        employee.Archive     = false;
                        employee.Photo       = newimage == null ? null : File.ReadAllBytes(newimage);
                        employee.DateEncoded = DateTime.Now;


                        db.Employees.Add(employee);
                        db.SaveChanges();
                        Mouse.OverrideCursor = null;

                        MessageBox.Show("Employee was added to the database succesfully!");

                        db = new ImusCityHallEntities();
                        var newemp = db.Employees.Where(m => m.EmployeeNo == employeenotb.Text).FirstOrDefault();
                        if (db.AspNetUsers.Where(m => m.UserName == employee.EmployeeNo).FirstOrDefault() != null)
                        {
                            MessageBox.Show("User account for this person already exists!", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                        else if (db.AspNetUsers.Where(m => m.Email == primaryemailtb.Text && m.Email != "").FirstOrDefault() != null)
                        {
                            MessageBox.Show("Email already exists!", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                        else
                        {
                            string roleid = "2";
                            if (String.IsNullOrEmpty(roleid))
                            {
                                MessageBox.Show("Role is not specified", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                                return;
                            }
                            else
                            {
                                AspNetUser     aspuser     = new AspNetUser();
                                AspNetUserRole asproleuser = new AspNetUserRole();
                                aspuser.Id                   = Guid.NewGuid().ToString();
                                aspuser.UserName             = newemp.EmployeeNo;
                                aspuser.Email                = newemp.PrimaryEmail;
                                aspuser.EmailConfirmed       = true;
                                aspuser.PhoneNumberConfirmed = false;
                                aspuser.TwoFactorEnabled     = false;
                                aspuser.LockoutEnabled       = true;
                                aspuser.AccessFailedCount    = 0;
                                aspuser.SecurityStamp        = Guid.NewGuid().ToString();
                                var passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();
                                aspuser.PasswordHash = passwordHasher.HashPassword("imuscitygov");
                                var adduser = db.AspNetUsers.Add(aspuser);
                                asproleuser.UserId = adduser.Id;
                                asproleuser.RoleId = roleid;
                                db.AspNetUserRoles.Add(asproleuser);
                            }
                        }
                        db.SaveChanges();

                        var audit = new AuditTrailModel
                        {
                            Activity   = "Added new employee in the database. EMP NO: " + employeenotb.Text,
                            ModuleName = this.GetType().Name,
                            EmployeeID = App.EmployeeID
                        };

                        SystemClass.InsertLog(audit);

                        MessageBox.Show("Employee user account created" + Environment.NewLine + "Default Password: imuscitygov");
                        ClearTextBoxes();
                    }
                }
                catch (Exception ex)
                {
                    Mouse.OverrideCursor = null;
                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                MessageBox.Show(SystemClass.DBConnectionErrorMessage);
            }
        }
        internal void Seed(MachineDataContext context)
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();
            // Demo user and admin for frontend administration
            var guestRole = new ApplicationRole {
                Name = "Guest", Id = Guid.NewGuid().ToString("N")
            };
            var userRole = new ApplicationRole {
                Name = "User", Id = Guid.NewGuid().ToString("N")
            };
            var adminRole = new ApplicationRole {
                Name = "Admin", Id = Guid.NewGuid().ToString("N")
            };

            context.Roles.AddRange(new [] { guestRole, userRole, adminRole });
            var hasher = new Microsoft.AspNet.Identity.PasswordHasher();
            var guest  = new ApplicationUser
            {
                UserName     = "******",
                Id           = Guid.NewGuid().ToString("N"),
                Email        = "*****@*****.**",
                PasswordHash = hasher.HashPassword("p@ssw0rd")
            };
            var user = new ApplicationUser
            {
                UserName     = "******",
                Id           = Guid.NewGuid().ToString("N"),
                Email        = "*****@*****.**",
                PasswordHash = hasher.HashPassword("p@ssw0rd")
            };
            var admin = new ApplicationUser
            {
                UserName     = "******",
                Id           = Guid.NewGuid().ToString("N"),
                Email        = "*****@*****.**",
                PasswordHash = hasher.HashPassword("p@ssw0rd")
            };

            context.Users.Add(user);
            context.Users.Add(admin);
            // Assign users to roles
            var guestUserRole = new IdentityUserRole <string> {
                UserId = guest.Id, RoleId = guestRole.Id
            };
            var userUserRole = new IdentityUserRole <string> {
                UserId = user.Id, RoleId = userRole.Id
            };
            var adminUserRole = new IdentityUserRole <string> {
                UserId = admin.Id, RoleId = adminRole.Id
            };

            context.UserRoles.AddRange(new[] { guestUserRole, userUserRole, adminUserRole });
            context.SaveChanges();
            // Demo data
            var machine = new Machine {
                Name     = "M1",
                Location = "A-100"
            };
            var device1 = new Device {
                Name = "BG A"
            };
            var device2 = new Device {
                Name = "BG B"
            };
            var v1 = new DataValue {
                Value = 123.5, Unit = "V"
            };
            var v2 = new DataValue {
                Value = 43, Unit = "V"
            };
            var v3 = new DataValue {
                Value = 230, Unit = "V"
            };
            var v4 = new DataValue {
                Value = 380, Unit = "V"
            };
            var v5 = new DataValue {
                Value = 0.005, Unit = "A"
            };

            machine.Devices.Add(device1);
            machine.Devices.Add(device2);
            device1.DataValues.Add(v1);
            device1.DataValues.Add(v2);
            device2.DataValues.Add(v3);
            device2.DataValues.Add(v4);
            device2.DataValues.Add(v5);

            context.Machines.Add(machine);
            context.SaveChanges();
        }
Ejemplo n.º 29
0
        private void Button1_Click(object sender, EventArgs e)
        {
            var ph = new Microsoft.AspNet.Identity.PasswordHasher();

            hashPassword_tb.Text = ph.HashPassword(password_tb.Text);
        }