Пример #1
0
        public ActionResult CreateEmployee(FormCollection form)
        {
            bool isAvailable = true;

            ViewBag.error = "";
            var    UserManager = new Microsoft.AspNet.Identity.UserManager <AspNetUser>(new UserStore <AspNetUser>(context));
            string UserName    = form["txtEmail"];
            string email       = form["txtEmail"];
            string pwd         = "Caretta.97";

            List <AspNetUser> uList = db.Users.ToList();

            foreach (var item in uList)
            {
                if (item.Email == email)
                {
                    ViewBag.error = "The employee you want to add is already registered.";
                    isAvailable   = false;
                }
            }
            if (isAvailable)
            {
                var user = new AspNetUser();
                user.UserName   = UserName;
                user.Email      = email;
                user.pwdChanged = false;
                var newUser = UserManager.Create(user, pwd);
                UserManager.AddToRole(user.Id, "personel");
                ViewBag.error = "The employee you want to add has been successfully registered.";
            }

            return(View());
        }
Пример #2
0
        private void createRolesandUsers(string username, string userType)
        {
            ApplicationDbContext context = new ApplicationDbContext();

            var roleManager = new Microsoft.AspNet.Identity.RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var UserManager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));


            if (!roleManager.RoleExists("Employee") && userType == "1")
            {
                // first we create Admin rool
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Employee";
                roleManager.Create(role);
            }
            if (!roleManager.RoleExists("Customer") && userType == "2")
            {
                // first we create Admin rool
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Customer";
                roleManager.Create(role);
            }
            string s;

            if (userType == "1")
            {
                s = "Employee";
            }
            else
            {
                s = "Customer";
            }
            var result1 = UserManager.AddToRole(username, s);
        }
Пример #3
0
        protected override void Seed(MPSContext context)
        {
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new ApplicationDbContext()));
            var userManager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));

            //uzytkownicy o roli Admin
            roleManager.Create(new IdentityRole("Admin"));
            var u1 = new ApplicationUser
            {
                Email    = "*****@*****.**",
                UserName = "******"
            };
            string passwor = "Biblioteka1@";

            userManager.Create(u1, passwor);
            userManager.AddToRole(u1.Id, "Admin");

            var uu1 = new UserNew
            {
                UserName = "******",
                Id       = u1.Id
            };

            context.User.Add(uu1);
            context.SaveChanges();

            /*   var P = new Person
             * {
             *     Name = "",
             *     Surname = ""
             *
             * };*/
            // context.Person.Add(P);
            //   context.SaveChanges();
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                var um = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>
                             (new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(_context));
                um.AddToRole(user.Id, "Applicant");
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");



                    return(RedirectToAction("AddProfile", "NAAAdmin"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #5
0
        public ActionResult ManageUserRoles(string UserName, string RoleName)
        {
            ApplicationUser user     = _context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var             um       = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(_context));
            var             idResult = um.AddToRole(user.Id, RoleName);
            // Prepopulate roles for the view dropdown
            var roleList = _context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem
            {
                Value = rr.Name.ToString(),
                Text  = rr.Name
            }).ToList();

            ViewBag.Roles = roleList;

            // Prepopulate users for the view dropdown
            var userList = _context.Users.OrderBy(u => u.UserName).ToList().Select(uu => new SelectListItem
            {
                Value = uu.UserName.ToString(),
                Text  = uu.UserName
            }).ToList();

            ViewBag.Users = userList;

            return(View("ManageUserRoles"));
        }
Пример #6
0
        public ActionResult Register(RegisterModel model, HttpPostedFileBase file)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                if (ModelState.IsValid)
                {
                    var path     = Server.MapPath("~/Upload/Users"); //dosya yolu
                    var filename = Path.ChangeExtension(model.Username + "", ".jpg");

                    if (file == null)
                    {
                        filename = "place.jpg";
                    }
                    var fullpath = Path.Combine(path, filename);

                    file.SaveAs(fullpath);

                    model.UserImage = filename.ToString();

                    //Kayıt İşlemleri

                    ApplicationUser user = new ApplicationUser();

                    user.Name     = model.Name;
                    user.Surname  = model.Surname;
                    user.Email    = model.Email;
                    user.UserName = model.Username;

                    IdentityResult result = userManager.Create(user, model.Password);

                    if (result.Succeeded)
                    {
                        //Kullanıcı oluştu ve rol atanabilir.


                        if (roleManager.RoleExists("user"))
                        {
                            userManager.AddToRole(user.Id, "user");
                        }

                        return(RedirectToAction("Login", "Account"));
                    }
                    else
                    {
                        ModelState.AddModelError("RegisterUserError", "Kullanıcı oluşturulamadı.");
                    }
                }



                return(View(model));
            }
        }
        public void AddUserRole(string id, string role)
        {
            UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(db);
            Microsoft.AspNet.Identity.UserManager<ApplicationUser> userManager = new Microsoft.AspNet.Identity.UserManager<ApplicationUser>(userStore);

            userManager.AddToRole(id, role);

            db.SaveChanges();
            //return userManager;
        }
Пример #8
0
        public ActionResult AssignRole(FormCollection form)
        {
            string username = form["txtUserName"];
            string rolname  = form["RoleName"];

            AspNetUser user = context.Users.Where(u => u.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            var userManager = new Microsoft.AspNet.Identity.UserManager <AspNetUser>(new UserStore <AspNetUser>(context));

            userManager.AddToRole(user.Id, rolname);
            return(View("Index"));
        }
        //[Authorize(Roles = "Admin")]
        public ActionResult ManageUserRoles(string UserName, string RoleName)
        {
            ApplicationUser user     = _DBcontext.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var             um       = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(_DBcontext));
            var             idResult = um.AddToRole(user.Id, RoleName);

            //populate roles for the view dropdown
            ViewBag.Roles = _abcLib.PopulateRoleListItem();

            //populate users for the view dropdown
            ViewBag.Users = _abcLib.PopulateUserListItem();
            return(View("ManageUserRoles"));
        }
Пример #10
0
        public bool AddRole(string role)
        {
            var userManager = new Microsoft.AspNet.Identity.UserManager <MyUser, int>(new MyUserStore(new ApplicationDbContext()));

            try
            {
                userManager.AddToRole(this.Id, role);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Пример #11
0
        public ActionResult ManageUserRoles(UserViewModel model)
        {
            var user = _context.Users.FirstOrDefault(u => u.UserName.Equals(model.UserName, StringComparison.CurrentCultureIgnoreCase));
            var um   = new Microsoft.AspNet.Identity.UserManager <IdentityUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore <IdentityUser>(_context));

            um.RemoveFromRole(user.Id, Helpers.Constants.Roles.Applicant);
            um.RemoveFromRole(user.Id, Helpers.Constants.Roles.Admin);
            um.RemoveFromRole(user.Id, Helpers.Constants.Roles.Staff);
            var idResult = um.AddToRole(user.Id, model.RoleName);

            model = GetUserViewModel(model.UserName);

            return(View("ManageUserRoles", model));
        }
Пример #12
0
        public void CreateAdmin()
        {
            var userManger = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));
            var user       = new ApplicationUser();

            user.Email    = "*****@*****.**";
            user.UserName = "******";
            var isUserExist = userManger.Create(user, "123456");

            if (isUserExist.Succeeded)
            {
                userManger.AddToRole(user.Id, "Admin");
            }
        }
Пример #13
0
        private void CreateRolesAndUsers()
        {
            ApplicationDbContext context = new ApplicationDbContext();

            var roleManager = new Microsoft.AspNet.Identity.RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var UserManager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

            if (!roleManager.RoleExists("Admin"))
            {
                // first we create Admin rool
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);

                var user = new ApplicationUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";

                string userPWD = "HuaTheDogN0se!";

                var chkUser = UserManager.Create(user, userPWD);


                if (chkUser.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, "Admin");
                }
            }

            // creating Creating Manager role
            if (!roleManager.RoleExists("Employee"))
            {
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Employee";
                roleManager.Create(role);
            }

            // creating Creating Employee role
            if (!roleManager.RoleExists("Customer"))
            {
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Customer";
                roleManager.Create(role);
            }
        }
Пример #14
0
        private void createRolesandUsers(string username)
        {
            ApplicationDbContext context = new ApplicationDbContext();

            var roleManager = new Microsoft.AspNet.Identity.RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var UserManager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));


            // In Startup iam creating first Admin Role and creating a default Admin User
            if (!roleManager.RoleExists("Administrator"))
            {
                // first we create Admin rool
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Administrator";
                roleManager.Create(role);
            }
            var result1 = UserManager.AddToRole(username, "Administrator");
        }
        public ActionResult ManageUserRoles(string UserName, string RoleName)
        {
            ApplicationUser user = _context.Users.Where(u => u.UserName.Equals(UserName,
                                                                               StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var um = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>
                         (new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(_context));

            foreach (string rm in um.GetRoles(user.Id))
            {
                um.RemoveFromRoles(user.Id, rm);
            }
            um.AddToRole(user.Id, RoleName);

            ////preopulate roles for the view dropdwon
            //var roleList = _context.Roles.OrderBy(r => r.Name).ToList().Select
            //    (rr => new SelectListItem
            //    {
            //        Value = rr.Name.ToString(),
            //        Text = rr.Name
            //    }).ToList();
            //ViewBag.Roles = roleList;

            ////preopulate users for the view dropdwon
            //var userList = _context.Users.OrderBy(u => u.UserName).ToList().Select
            //    (uu => new SelectListItem
            //    {
            //        Value = uu.UserName.ToString(),
            //        Text = uu.UserName
            //    }).ToList();
            //ViewBag.Users = userList;

            ViewBag.RolesForThisUser = um.GetRoles(user.Id);
            ViewBag.ThisUser         = user.UserName;

            return(View("GetRolesforUserConfirmed"));
        }
Пример #16
0
        protected override void Seed(DashoundCoachTravels.Models.ApplicationDbContext context)
        {
            var userManager = new Microsoft.AspNet.Identity.UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

            //Creating new role types for accounts
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            IdentityResult roleResult;

            // Adding new role types named: Administrator, Employee, User
            if (!roleManager.RoleExists("Administrator")) { roleResult = roleManager.Create(new IdentityRole("Administrator")); }
            if (!roleManager.RoleExists("Employee")) { roleResult = roleManager.Create(new IdentityRole("Employee")); }
            if (!roleManager.RoleExists("User")) { roleResult = roleManager.Create(new IdentityRole("User")); }
            //Adding sample users: 1 for each role type testing only: Basic|Employee|Admin
            var sampleAccount = userManager.FindByEmail("*****@*****.**");
            if (sampleAccount == null)
            {
                var hasher = new PasswordHasher();
                sampleAccount = new ApplicationUser()
                {
                    UserName = "******",
                    Email = "*****@*****.**",
                    EmailConfirmed = true,
                    PasswordHash = hasher.HashPassword("user"),
                    Name = "Jon",
                    Surname = "Doe",
                    Town = "aaa",
                    Street = "streetA",
                    NumHouse = "1",
                    NumFlat = "12",
                    ZIPCode = "22-222",
                    Country = "Uganda"
                };
                userManager.Create(sampleAccount);
                userManager.AddToRole(sampleAccount.Id, "User");
                context.SaveChanges();
            }
            sampleAccount = userManager.FindByEmail("*****@*****.**");
            if (sampleAccount == null)
            {
                var hasher = new PasswordHasher();
                sampleAccount = new ApplicationUser()
                {
                    UserName = "******",
                    Email = "*****@*****.**",
                    EmailConfirmed = true,
                    PasswordHash = hasher.HashPassword("employee"),
                    Name = "Jonatan",
                    Surname = "Doppey",
                    Town = "bbb",
                    Street = "streetB",
                    NumHouse = "2",
                    NumFlat = "186",
                    ZIPCode = "66-666",
                    Country = "Nigeria"
                };
                userManager.Create(sampleAccount);
                userManager.AddToRole(sampleAccount.Id, "Employee");
                context.SaveChanges();
            }
            sampleAccount = userManager.FindByEmail("*****@*****.**");
            if (sampleAccount == null)
            {
                var hasher = new PasswordHasher();

                sampleAccount = new ApplicationUser()
                {
                    UserName = "******",
                    Email = "*****@*****.**",
                    EmailConfirmed = true,
                    PasswordHash = hasher.HashPassword("admin"),
                    Name = "Jonny",
                    Surname = "Dope",
                    Town = "ccc",
                    Street = "streetC",
                    NumHouse = "79",
                    NumFlat = "6",
                    ZIPCode = "99-971",
                    Country = "Egypt"
                };
                userManager.Create(sampleAccount);
                userManager.AddToRole(sampleAccount.Id, "Administrator");
                context.SaveChanges();
            }

            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data.
        }
Пример #17
0
        /// <summary>
        /// Seeds the database with data
        /// </summary>
        /// <param name="context">The context to use</param>
        protected override void Seed(PCHI.DataAccessLibrary.Context.MainDatabaseContext context)
        {
            /*
             * This method will be called after migrating to the latest version.
             *
             * You can use the DbSet<T>.AddOrUpdate() helper extension method
             * to avoid creating duplicate seed data. E.g.
             *
             *    context.People.AddOrUpdate(
             *      p => p.FullName,
             *      new Person { FullName = "Andrew Peters" },
             *      new Person { FullName = "Brice Lambson" },
             *      new Person { FullName = "Rowan Miller" }
             *    );
             */

            {
                QuestionnaireDataExtraction[] qde = new QuestionnaireDataExtraction[]
                {
                    new QuestionnaireDataExtraction()
                    {
                        QuestionnaireName = "OPSMCFirstAppointment", ItemActionId = "OPSMC.39", OptionGroupActionId = "OPSMC.39.1", OptionActionId = "OPSMC.39.1.1", TagName = "Weight"
                    },
                    new QuestionnaireDataExtraction()
                    {
                        QuestionnaireName = "OPSMCFirstAppointment", ItemActionId = "OPSMC.39", OptionGroupActionId = "OPSMC.39.2", OptionActionId = "OPSMC.39.2.1", TagName = "Height"
                    },
                    new QuestionnaireDataExtraction()
                    {
                        QuestionnaireName = "OPSMCFirstAppointment", ItemActionId = "OPSMC.15.1", OptionGroupActionId = "OPSMC.15.1.1", TagName = "Gender"
                    },
                    new QuestionnaireDataExtraction()
                    {
                        QuestionnaireName = "OPSMCFirstAppointment", ItemActionId = "OPSMC.41", OptionGroupActionId = null, TagName = "Occupation"
                    },
                    new QuestionnaireDataExtraction()
                    {
                        QuestionnaireName = "OPSMCFirstAppointment", ItemActionId = "OPSMC.45", OptionGroupActionId = "OPSMC.45.1", TagName = "Main Sport"
                    },
                    new QuestionnaireDataExtraction()
                    {
                        QuestionnaireName = "OPSMCFirstAppointment", ItemActionId = "OPSMC.45", OptionGroupActionId = "OPSMC.45.2", TagName = "Seconday Sport"
                    },
                    new QuestionnaireDataExtraction()
                    {
                        QuestionnaireName = "OPSMCFirstAppointment", ItemActionId = "OPSMC.46", OptionGroupActionId = "OPSMC.46.1", TagName = "Current sporting level"
                    },
                };
                context.QuestionnaireDataExtractions.AddOrUpdate(qde);
                context.SaveChanges();
            }

            {
                Dictionary <ErrorCodes, string> errorList = new Dictionary <ErrorCodes, string>();
                errorList.Add(ErrorCodes.ERROR_DOES_NOT_EXIST, "That error code doesn't exist");
                errorList.Add(ErrorCodes.DATA_LOAD_ERROR, "There has been a problem loading the data");
                errorList.Add(ErrorCodes.LOGIN_FAILED, "Login has failed");
                errorList.Add(ErrorCodes.USER_IS_LOCKEDOUT, "You are currently locked out.");
                errorList.Add(ErrorCodes.USER_SESSION_EXPIRED, "Session has expired");
                errorList.Add(ErrorCodes.GENERAL_IDENTITY_RESULT_ERROR, "Put error of IdentityResult here");
                errorList.Add(ErrorCodes.USER_UNKNOWN, "User doesn't exist");
                errorList.Add(ErrorCodes.QUESTIONNAIRE_NOT_ASSIGNED, "No questionnaire of this name has been assigned to this user");
                errorList.Add(ErrorCodes.ANONYMOUS_QUESTIONNAIRE_CANNOT_BE_CONTINUED_ANONYMOUSLY, "A questionnaire that already has responses filled in can not be accessed anonymously");
                errorList.Add(ErrorCodes.EPISODE_DOESNT_EXIST, "The requested episode doesn't exist");
                errorList.Add(ErrorCodes.MILESTONE_DOESNT_EXIST, "The requested milestone doesn't exist");
                errorList.Add(ErrorCodes.CODE_INCORRECT, "The provided code is incorrect");
                errorList.Add(ErrorCodes.USER_ALREADY_COMPLETED_REGISTRATION, "The user has already completed registration and cannot complete it again.");
                errorList.Add(ErrorCodes.USER_IS_REQUIRED, "The user has to be specified");
                errorList.Add(ErrorCodes.NO_ACTIVE_SESSION_SET, "No session has been set as active.");
                errorList.Add(ErrorCodes.PERMISSION_DENIED, "Permission has been denied");
                errorList.Add(ErrorCodes.SECURITY_QUESTION_ANSWER_ARE_MANDATORY, "The security question and answer are mandatory and cannot be empty.");
                errorList.Add(ErrorCodes.PASSWORD_INCORRECT, "The provided password is incorrect");
                errorList.Add(ErrorCodes.REGISTRATION_NOT_COMPLETED, "You have not yet completed your registration. Please see your email for details.");
                errorList.Add(ErrorCodes.USERNAME_ALREADY_INUSE, "The username is already in use.");
                errorList.Add(ErrorCodes.USERNAME_LENGTH_EXCEEDED, "The username must be less than 450 characters.");
                errorList.Add(ErrorCodes.USERNAME_CONTAINS_ILLEGAL_CHARACTERS, "The username contains illegal characters.");

                /*
                 * 100 - 200 Generic Errors
                 * 210 - 220 User Errors
                 * 250 - 260 Questionnaire Errors
                 */
                var x = from e in errorList select new PCHIError(e.Key, e.Value);
                context.ErrorsMessages.AddOrUpdate(x.ToArray());

                context.SaveChanges();
            }

            {
                Dictionary <string, string> text = new Dictionary <string, string>()
                {
                    { "Patient_Index_Top", "RePLAY allows you to prepare for upcoming appointments as well as track your health progress by completing questionnaires assigned by your practitioner. At OPSMC we really want to make you happy and healthy, so thank you for taking the time to fill this out." },
                    { "Patient_Index_Header", "Welcome back <%PatientDisplayName%/>" },
                    { "Patient_NewsFeed_1", "Mr Geoff Tymms Orthopaedic foot and ankle surgeon is now also consulting at OPSMC Geelong Campus." },
                    { "Patient_NewsFeed_2", "Dr. Pedro Chan brain surgeon is now also consulting at OPSMC Geelong Campus." },
                    { "Patient_NewsFeed_3", "You're what you eat, so don't be fast, cheap, easy or fake.<br /><br />Remember push hard and RePLAY!" },
                    { "Any_Score", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." },
                    { "Score_Better_Text", "Congratulations your score has improved. Keep it up!" },
                    { "Score_Same_Text", "No change has been found in the overall score for your condition however there may be some change in certain symptoms and/or your level of function. If this is unexpected, you may wish to make arrangements for follow-up with your practitioner if you haven’t already." },
                    { "Score_Worse_Text", "Your overall score suggests that your condition may have worsened. If this is unexpected or you don’t have arrangements for a follow-up you should consider reviewing your progress with your practitioner." },
                    { "Access_Registration_Top", "Dear <%DisplayName%/>,thanks for taking action. Please fill in the following security settings so your account can be fully activated and you can get on the way to recovery." },
                    { "UserName", "<%UserName%/>" }
                };

                context.PageTexts.AddOrUpdate(text.Select(t => new PageText()
                {
                    Identifier = t.Key, Text = t.Value
                }).ToArray());
                context.SaveChanges();
            }

            {
                string[] roles = new string[] { "Administrator", "PatientProxy", "Telephonist", "Practitioner", "Researcher" };

                foreach (string role in roles)
                {
                    if (!context.IdentityRoles.Any(r => r.Name == role))
                    {
                        context.IdentityRoles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(role));
                    }
                }

                context.SaveChanges();
            }

            {
                // TODO Create Roles and Permissions and assign to Users
                // context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission() { RoleId = role.Id, Permission = Permission.CREATE_USER, PermissionString = Permission.CREATE_USER.ToString() });
                {
                    IdentityRole role = context.IdentityRoles.Where(r => r.Name == "Administrator").Single();
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.CREATE_USER));
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.UPDATE_OTHER_USERS_DATA));
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.UPDATE_OTHER_USERS_PASSWORD));
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.MODIFY_QUESTIONNAIRES));
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.SAVE_PAGE_TEXT));
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.VIEW_AUDIT_TRAILS));
                }

                {
                    IdentityRole role = context.IdentityRoles.Where(r => r.Name == "Telephonist").Single();
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.CREATE_EPISODES));
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.CREATE_PATIENT));
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.VIEW_PATIENT_ASSIGNED_EPISODES));
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.VIEW_PATIENT_DATA));
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.UPDATE_PATIENT_DATA));
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.MODIFY_EPISODES));
                }

                {
                    IdentityRole role = context.IdentityRoles.Where(r => r.Name == "Practitioner").Single();
                    //context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.CREATE_EPISODES));
                    //context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.MODIFY_EPISODES));
                    //context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.VIEW_PATIENT_ASSIGNED_EPISODES));
                    //context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.VIEW_PATIENT_DATA));
                    context.IdentityRolePermission.AddOrUpdate(new IdentityRolePermission(role, Permission.UPDATE_PATIENT_DATA));
                }

                context.SaveChanges();
            }

            {
                User user = context.Users.Where(u => u.UserName == "admin").SingleOrDefault();
                if (user == null)
                {
                    AccessHandlerManager handler = new AccessHandlerManager(context);
                    user = new User()
                    {
                        UserName = "******", Email = string.Empty, EmailConfirmed = true, Title = "Mr", FirstName = "Admin", LastName = "Test"
                    };

                    Microsoft.AspNet.Identity.UserManager <User> m = new Microsoft.AspNet.Identity.UserManager <User>(handler.UserAccessHandler);
                    m.CreateAsync(user, "Welc0me!").Wait();
                }
            }

            // Add all the roles with exception of the Patient Proxy to the admin
            {
                AccessHandlerManager handler = new AccessHandlerManager(context);
                Microsoft.AspNet.Identity.UserManager <User> m = new Microsoft.AspNet.Identity.UserManager <User>(handler.UserAccessHandler);
                User u = m.FindByName("admin");

                if (u != null)
                {
                    var           userRoles = m.GetRoles(u.Id).Select(r => r.ToUpper()).ToList();
                    List <string> roles = new string[] { "Administrator" /*, "Telephonist", "Practitioner", "Researcher"*/ }.ToList();

                    foreach (string role in roles)
                    {
                        if (!userRoles.Contains(role.ToUpper()))
                        {
                            IdentityResult r = m.AddToRole(u.Id, role);

                            if (!r.Succeeded)
                            {
                                string error = r.Errors.Aggregate((s1, s2) =>
                                {
                                    return(s1 + Environment.NewLine + s2);
                                });

                                throw new Exception(error);
                            }
                        }
                    }
                }

                context.SaveChanges();
            }

            {
                List <TextReplacementCode> codes = new List <TextReplacementCode>();
                codes.Add(new TextReplacementCode()
                {
                    ReplacementCode = "<%DisplayName%/>", ObjectKey = ReplaceableObjectKeys.Patient, ObjectVariablePath = "DisplayName", UseReplacementValue = false
                });
                codes.Add(new TextReplacementCode()
                {
                    ReplacementCode = "<%DisplayName%/>", ObjectKey = ReplaceableObjectKeys.User, ObjectVariablePath = "DisplayName", UseReplacementValue = false
                });
                codes.Add(new TextReplacementCode()
                {
                    ReplacementCode = "<%PatientDisplayName%/>", ObjectKey = ReplaceableObjectKeys.Patient, ObjectVariablePath = "DisplayName", UseReplacementValue = false
                });
                codes.Add(new TextReplacementCode()
                {
                    ReplacementCode = "<%PatientTitle%/>", ObjectKey = ReplaceableObjectKeys.Patient, ObjectVariablePath = "Title", UseReplacementValue = false
                });
                codes.Add(new TextReplacementCode()
                {
                    ReplacementCode = "<%PatientFirstName%/>", ObjectKey = ReplaceableObjectKeys.Patient, ObjectVariablePath = "FirstName", UseReplacementValue = false
                });
                codes.Add(new TextReplacementCode()
                {
                    ReplacementCode = "<%PatientLastName%/>", ObjectKey = ReplaceableObjectKeys.Patient, ObjectVariablePath = "LastName", UseReplacementValue = false
                });
                codes.Add(new TextReplacementCode()
                {
                    ReplacementCode = "<%PatientPhoneNumber%/>", ObjectKey = ReplaceableObjectKeys.Patient, ObjectVariablePath = "User.PhoneNumber", UseReplacementValue = false
                });
                codes.Add(new TextReplacementCode()
                {
                    ReplacementCode = "<%PatientDateOfBirth%/>", ObjectKey = ReplaceableObjectKeys.Patient, ObjectVariablePath = "DateOfBirth", ToStringParameter = "yyyy-MM-dd", UseReplacementValue = false
                });
                codes.Add(new TextReplacementCode()
                {
                    ReplacementCode = "<%PatientEmail%/>", ObjectKey = ReplaceableObjectKeys.Patient, ObjectVariablePath = "User.Email", UseReplacementValue = false
                });
                codes.Add(new TextReplacementCode()
                {
                    ReplacementCode = "<%hostname%/>", ObjectKey = ReplaceableObjectKeys.UriHostName, ObjectVariablePath = string.Empty, ToStringParameter = string.Empty, UseReplacementValue = false
                });
                codes.Add(new TextReplacementCode()
                {
                    ReplacementCode = "<%code%/>", ObjectKey = ReplaceableObjectKeys.Code, ObjectVariablePath = string.Empty, ToStringParameter = string.Empty, UseReplacementValue = false
                });
                codes.Add(new TextReplacementCode()
                {
                    ReplacementCode = "<%UserName%/>", ObjectKey = ReplaceableObjectKeys.User, ObjectVariablePath = "UserName", ToStringParameter = string.Empty, UseReplacementValue = false
                });

                foreach (TextReplacementCode trc in codes)
                {
                    if (!context.TextReplacementCodes.Any(t => t.ReplacementCode == trc.ReplacementCode))
                    {
                        context.TextReplacementCodes.Add(trc);
                    }
                }

                context.SaveChanges();
            }

            {
                List <TextDefinition> definitions = new List <TextDefinition>()
                {
                    new TextDefinition()
                    {
                        DefinitionCode = "RegistrationEmail",
                        Text           = "Dear <%DisplayName%/>, \n Thanks for booking an appointment with OPSMC. \n\n As part of your journey with us, you will be using our ground-breaking RePLAY service, which will let you prepare for your upcoming appointment as well as help your practitioner track your health progress. \n Please click on the link below, or copy/paste it to your web browser to complete your registration in RePLAY. \n\n <%hostname%/>Access/Login?CompleteRegistration=<%code%/> \n Thanks and regards, \n The OPSMC Team (http://www.opsmc.com.au/) \nPhone: 1300 859 887 – (03) 9420 4300",
                        Html           = "Dear <%DisplayName%/>, \n<br /> Thanks for booking an appointment with OPSMC. \n<br />\n<br /> As part of your journey with us, you will be using our ground-breaking RePLAY service, which will let you prepare for your upcoming appointment as well as help your practitioner track your health progress. \n<br /> Please click on the link below, or copy/paste it to your web browser to complete your registration in RePLAY. \n<br />\n<br /> <a href=\"<%hostname%/>Access/CompleteRegistration?code=<%code%/>\"><%hostname%/>/Access/CompleteRegistration?code=<%code%/></a>  \n<br /> Thanks and regards, \n<br /> The OPSMC Team (<a href=\"http://www.opsmc.com.au/\">http://www.opsmc.com.au/</a>) \n<br />Phone: 1300 859 887 – (03) 9420 4300"
                    },

                    new TextDefinition()
                    {
                        DefinitionCode = "TwoStageCodeSubject",
                        Text           = "OPSMC RePLAY Access Code",
                        Html           = "OPSMC RePLAY Access Code"
                    },

                    new TextDefinition()
                    {
                        DefinitionCode = "TwoStageCodeBody",
                        Text           = "Your security code is <%code%/>",
                        Html           = "Your security code is <%code%/>"
                    },

                    new TextDefinition()
                    {
                        DefinitionCode = "NotificationStart",
                        Text           = "Dear <%DisplayName%/>,\n",
                        Html           = "Dear <%DisplayName%/>,\n<br>"
                    },

                    new TextDefinition()
                    {
                        DefinitionCode = "NotificationEnd",
                        Text           = "Thanks and regards,\nThe OPSMC Team (link to OPSMC website)\nPhone: 1300 859 887 – (03) 9420 4300",
                        Html           = "Thanks and regards,<br/>The OPSMC Team (link to OPSMC website)\n<br/>Phone: 1300 859 887 – (03) 9420 4300"
                    },

                    new TextDefinition()
                    {
                        DefinitionCode = "RegistrationComplete",
                        Text           = "Thank you for completing your registration here at the RePLAY service from OPSMC. You can now login and start on the path to recovery.",
                        Html           = "Thank you for completing your registration here at the RePLAY service from OPSMC. You can now login and start on the path to recovery."
                    },

                    new TextDefinition()
                    {
                        DefinitionCode = "NewQuestionnaire",
                        Text           = "Your practitioner needs to get some information from you. Please follow the link below, or copy/paste it into your web browser, and you will be taken to your pending questionnaires page.\n<%hostname%/>Utility/MyQuestionnaires",
                        Html           = "Your practitioner needs to get some information from you. Please follow the link below, or copy/paste it into your web browser, and you will be taken to your pending questionnaires page.<br /><a href=\"<%hostname%/>Utility/MyQuestionnaires\"><%hostname%/>Utility/MyQuestionnaires</a>"
                    },

                    new TextDefinition()
                    {
                        DefinitionCode = "PasswordChanged",
                        Text           = "Your password has recently been changed successfuly. \n If you have not changed your password, please contact OPSMC immediately for support as your account may have been compromised.\n",
                        Html           = "Your password has recently been changed successfuly. <br/> If you have not changed your password, please contact OPSMC immediately for support as your account may have been compromised.<br/>",
                    },

                    new TextDefinition()
                    {
                        DefinitionCode = "UserDetailsChanged",
                        Text           = "Your user details have recently been updated successfuly. \n If you have not updated your user details, please contact OPSMC immediately for support as your account may have been compromised.\n",
                        Html           = "Your user details have recently been updated successfuly. <br/> If you have not updated your user details, please contact OPSMC immediately for support as your account may have been compromised.<br/>",
                    },

                    new TextDefinition()
                    {
                        DefinitionCode = "PasswordReset",
                        Text           = "A password reset request has been received for your account. \n In order to reset your password, you will need to please follow the link below to reset your password: \n <%hostname%/>Access/ResetPassword?token=<%code%/>  \n\n ",
                        Html           = "A password reset request has been received for your account. <br/> In order to reset your password, you will need to please follow the link below to reset your password: <br/><a href=\"<%hostname%/>Access/ResetPassword?token=<%code%/>\"><%hostname%/>Access/ResetPassword?token=<%code%/> </a> <br/> ",
                    }
                };
                foreach (TextDefinition t in definitions)
                {
                    context.TextDefinitions.AddOrUpdate(t);
                }

                context.SaveChanges();
            }
        }
        protected override void  Seed(TrainerClientADOnet.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.


            if (!context.Roles.Any(r => r.Name == "Admin"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new Microsoft.AspNet.Identity.RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "Admin"
                };

                manager.Create(role);
            }



            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };

                manager.Create(user, "Teodora!1");
                context.Users.Add(user);
                manager.AddToRole(user.Id, "Admin");
            }


            //   if (!context.Roles.Any(u => u.Name == "Trener"))
            //   {
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };

                manager.Create(user, "Teodora!1");
                context.Users.Add(user);
                manager.AddToRole(user.Id, "Trener");
            }
            //  }



            if (!context.Roles.Any(u => u.Name == "Trener"))
            {
                if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
                {
                    var store   = new UserStore <ApplicationUser>(context);
                    var manager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(store);
                    var user    = new ApplicationUser {
                        UserName = "******", Email = "*****@*****.**"
                    };

                    manager.Create(user, "Teodora!1");
                    context.Users.Add(user);
                    manager.AddToRole(user.Id, "Trener");
                }
            }

            /////////////////////
            ///

            if (!context.Roles.Any(r => r.Name == "Klijent"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new Microsoft.AspNet.Identity.RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "Klijent"
                };

                manager.Create(role);
            }



            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };

                manager.Create(user, "Teodora!1");
                context.Users.Add(user);
                manager.AddToRole(user.Id, "Klijent");
            }
        }