예제 #1
0
        internal static void SeedAdmin(HotelSystemDbContext context)
        {
            const string adminEmail = "*****@*****.**";
            const string adminPassword = "******";

            if (context.Users.Any(u => u.Email == adminEmail))
            {
                return;
            }

            var admin = new User()
            {
                Email = adminEmail,
                UserName = adminEmail,
                PasswordHash = new PasswordHasher().HashPassword(adminPassword),
                FirstName = "Admin",
                LastName = "Admin",
                BirthDate = new DateTime(1950, 2, 20),
                PhoneNumber = "0888888888888",
                SecurityStamp = Guid.NewGuid().ToString()
            };

            var adminRole = new IdentityRole { Name = GlobalConstants.AdministratorRole, Id = Guid.NewGuid().ToString() };
            context.Roles.AddOrUpdate(adminRole);

            admin.Roles.Add(new IdentityUserRole { RoleId = adminRole.Id, UserId = admin.Id });
            context.Users.Add(admin);
            context.SaveChanges();
        }
        public ActionResult Add(IdentityRole model)
        {
            try
            {
                db.Roles.Add(model);
                db.SaveChanges();
                var Projectdb = new ProjectMvcDbContext();
                foreach (var p in Projectdb.WebActions)
                {
                    var perm = new Permission
                    {
                        Allow = false,
                        RoleId = model.Id,
                        WebActionId = p.Id
                    };
                    Projectdb.Permissions.Add(perm);
                }

                Projectdb.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception Ex)
            {
                ModelState.AddModelError("", Ex.Message);
                ViewBag.Role = db.Roles;
                return View("Index", model);
            }
        }
예제 #3
0
        public async Task<bool> Update(IdentityRole role)
        {
            if (!RoleManager.RoleExists(role.Name))
            {
                var roleOle = await RoleManager.FindByIdAsync(role.Id);
                if (roleOle == null) throw new KeyNotFoundException("id");
                roleOle.Name = role.Name;
                AspContext.Entry(roleOle).State = EntityState.Modified;
                try
                {
                    await AspContext.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException exception)
                {
                    throw new DbUpdateConcurrencyException(exception.Message);
                }
            }
            else
            {
                throw new ArgumentException("This name ( " + role.Name + " ) is already taken");
            }

            /*var roleresult = await RoleManager.UpdateAsync(rolePut);
            if (!roleresult.Succeeded)
            {
                ModelState.AddModelError("", roleresult.Errors.First());
                return BadRequest(ModelState);
            }*/
            //UpdateAsync is not work! or I don't know how to use it. Database not update value.

            return true;
        }
예제 #4
0
        public override void Up()
        {
            ApplicationDbContext context = new ApplicationDbContext();

            var adminUser = new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(),
                EmailConfirmed = false,
                PhoneNumberConfirmed = false,
                TwoFactorEnabled = false,
                LockoutEnabled = false,
                AccessFailedCount = 0,
                Email = "*****@*****.**",
                UserName = "******"
            };

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

                manager.Create(role);
            }

            if (!context.Users.Any(u => u.UserName == "TheGaffer"))
            {
                var store = new UserStore<ApplicationUser>(context);
                var manager = new UserManager<ApplicationUser>(store);

                manager.Create(adminUser, "Seisen1!");
                manager.AddToRole(adminUser.Id, "Admin");
            }
        }
예제 #5
0
        public ActionResult Users()
        {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
            if (!roleManager.RoleExists("user"))
            {
                var nRole = new IdentityRole("user");
                roleManager.Create(nRole);
            }
            if (!roleManager.RoleExists("admin"))
            {
                var nRole = new IdentityRole("admin");
                roleManager.Create(nRole);
            }
            if (!roleManager.RoleExists("moderator"))
            {
                var nRole = new IdentityRole("moderator");
                roleManager.Create(nRole);
            }
            if (!roleManager.RoleExists("journalist"))
            {
                var nRole = new IdentityRole("journalist");
                roleManager.Create(nRole);
            }

            var vm = new AdminUsersViewModel();

            vm.Users = db.Users.OrderBy(x => x.UserName).ToList();
            vm.Roles = db.Roles.ToList();

            return View(vm);
        }
예제 #6
0
        public async Task<IdentityResult> RegisterCustomerAsync(UserModel userModel, AppRole appRole = AppRole.customer)
        {
            var addToRoleResult = new IdentityResult();
            // Add generate username to the model
            IdentityUser user = new IdentityUser
            {
                UserName = userModel.UserName,
                Email = userModel.EmailAddress,
                EmailConfirmed = true,
                PhoneNumber = userModel.PhoneNumber,
                PhoneNumberConfirmed = true,
            };

            var result = await _userManager.CreateAsync(user, userModel.Password);

            //Role-user combination is managed as Contact-Role combination in ContactRole table
            //Create Role Admin if it does not exist
            var _role = await _roleManager.FindByNameAsync(appRole.ToString());
            if (_role == null)
            {
                _role = new IdentityRole(appRole.ToString());
                var roleresult = await _roleManager.CreateAsync(_role);
            }
            var rolesForUser = await _userManager.GetRolesAsync(user.Id);
            if (!rolesForUser.Contains(_role.Name))
            {
                addToRoleResult = await _userManager.AddToRoleAsync(user.Id, _role.Name);
            }

            return addToRoleResult;
        }
 /// <summary>
 /// Inserts a new Role in the Roles table
 /// </summary>
 /// <param name="roleName">The role's name</param>
 /// <returns></returns>
 public int Insert(IdentityRole role)
 {
     using (var db = _database.Open())
     {
         return (int)db.Insert<IdentityRole>(role);
     }
 }
        public void IdentityRoleSet_Id()
        {
            var role = new IdentityRole();
            role.Id = Guid.NewGuid().ToString();

            role.Id = null;
        }
예제 #9
0
        protected void Page_Load(object sender, EventArgs e) {
            Feedback.Visible = false;
            
            Guid roleId;
            if (!Request.QueryString["id"].TryParseGuid(out roleId)) {
                ShowError(Feedback, "The parameter for id is not in the correct format!");
                SaveButton.Visible = false;
                FormFields.Visible = false;
                return;
            }

            _roleManager = IdentityRoleManager.GetManager();
            _role = _roleManager.FindById(roleId);

            if (_role == null) {
                ShowError(Feedback, "No role was found for the given id!");
                SaveButton.Visible = false;
                FormFields.Visible = false;
                return;
            }

            SaveButton.Click += SaveButton_Click;

            if (!IsPostBack) {
                RoleId.Value = roleId.ToString();
                RoleName.Text = _role.Name;

                if (Request.QueryString["message"] == "created") {
                    ShowMessage(Feedback, "Role has been created!");
                }
            }

            RenderUsersInRole();
        }
        public JsonResult Delete(IdentityRole role)
        {
            _context.Entry(role).State = EntityState.Deleted;
            _context.SaveChanges();

            return Json(_context.Roles.ToList(), JsonRequestBehavior.AllowGet);
        }
        public JsonResult Create(IdentityRole role)
        {
            _context.Roles.Add(role);
            _context.SaveChanges();

            return Json(_context.Roles.ToList(), JsonRequestBehavior.AllowGet);
        }
        public JsonData Update(IdentityRole entity, string userId)
        {
            try
            {
                using (var db = new DataContext())
                {
                    if (entity == null) throw new ArgumentNullException("The new" + " record is null");

                    //var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));

                    //Update Role Roles if they do not exist
                    var role = db.Roles.FirstOrDefault(x => x.Id == entity.Id);
                    if (role != null)
                    {
                        role.Name = entity.Name;
                        //roleManager.Update(role);
                    }
                    db.SaveChanges();

                    return DataHelpers.ReturnJsonData(entity, true, "Updated successfully", 1);
                }
            }
            catch (Exception e)
            {
                return DataHelpers.ExceptionProcessor(e);
            }
        }
        public JsonData Insert(IdentityRole entity, string userId)
        {
            try
            {
                using (var db = new DataContext())
                {
                    if (entity == null) throw new ArgumentNullException("The new" + " record is null");

                    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));

                    //Create Roles if they do not exist
                    if (!roleManager.RoleExists(entity.Name))
                    {
                        roleManager.Create(new IdentityRole(entity.Name));
                    }
                    db.SaveChanges();

                    return DataHelpers.ReturnJsonData(entity, true, "Saved successfully", 1);
                }
            }
            catch (Exception e)
            {
                return DataHelpers.ExceptionProcessor(e);
            }
        }
        public void GetRolesForUserShouldRetrieveCorrectRoles()
        {
            var role1 = new IdentityRole(GetNewRandomName());
            var role2 = new IdentityRole(GetNewRandomName());

            _roleManager.Create<IdentityRole>(role1);
            _roleManager.Create<IdentityRole>(role2);

            var user1 = new IdentityUser(GetNewRandomName());
            var user2 = new IdentityUser(GetNewRandomName());
            var user3 = new IdentityUser(GetNewRandomName());

            _userManager.Create(user1, _password);
            _userManager.Create(user2, _password);
            _userManager.Create(user3, _password);
            _userManager.AddToRole(user1.Id, role1.Name);
            _userManager.AddToRole(user1.Id, role2.Name);
            _userManager.AddToRole(user2.Id, role1.Name);
            _userManager.AddToRole(user3.Id, role2.Name);

            var user1RoleNames = _userManager.GetRoles(user1.Id);
            var user2RoleNames = _userManager.GetRoles(user2.Id);
            var user3RoleNames = _userManager.GetRoles(user3.Id);

            Assert.AreEqual(2, user1RoleNames.Count);
            Assert.AreEqual(1, user2RoleNames.Count);
            Assert.AreEqual(1, user3RoleNames.Count);

            Assert.IsTrue(user1RoleNames.Any(r => r == role1.Name));
            Assert.IsTrue(user1RoleNames.Any(r => r == role2.Name));
            Assert.IsTrue(user2RoleNames.Any(r => r == role1.Name));
            Assert.IsTrue(user3RoleNames.Any(r => r == role2.Name));
        }
예제 #15
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Tạo role sẵn
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

            List<string> roleNameList = new List<string> { "Admin"
                                                         , "Designer"
                                                         , "Mod"
                                                         , "Uploader"
                                                         , "Subteam"
                                                         , "Subber"
                                                         , "VIP"
                                                         , "Member" };
            foreach (string roleName in roleNameList)
            {
                if (!roleManager.RoleExists(roleName))
                {
                    var newRole = new IdentityRole();
                    newRole.Name = roleName;
                    roleManager.Create(newRole);
                }
            }
        }
예제 #16
0
 public async Task<IActionResult> Editar(IdentityRole role)
 {
     var r = await _roleManager.FindByIdAsync(role.Id);
     r.Name = role.Name;
     await _roleManager.UpdateAsync(r);
     return Redirect();
 }
        public void AddRoleToUser(string userName, string roleName)
        {
            var role = this.roles.All()
                .FirstOrDefault(r => r.Name == roleName);

            if (role == null)
            {
                role = new IdentityRole
                {
                    Name = roleName
                };

                this.roles.Add(role);
                this.roles.SaveChanges();
            }

            var user = this.users.All().FirstOrDefault(u => u.UserName == userName);

            var userRole = this.userRoles.All()
                .FirstOrDefault(r => r.UserId == user.Id && r.RoleId == role.Id);

            if (userRole == null)
            {
                user.Roles.Add(new IdentityUserRole
                {
                    UserId = user.Id,
                    RoleId = role.Id
                });

                this.users.Update(user);

                this.users.SaveChanges();
            }
        }
예제 #18
0
        private async Task CreateAdminUser()
        {
          var username = "******";//ConfigurationManager.AppSettings["DefaultAdminUsername"];
          var password = "******";//ConfigurationManager.AppSettings["DefaultAdminPassword"];

          using (var context = new ApplicationDbContext())
          {
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

            var role = new IdentityRole(RoleName);

            var result = await roleManager.RoleExistsAsync(RoleName);
            if (!result)
            {
              await roleManager.CreateAsync(role);
            }

            var user = await userManager.FindByNameAsync(username);
            if (user == null)
            {
              user = new ApplicationUser { UserName = username, Email = "*****@*****.**", First = "Big", Last="Admin Person" };
              await userManager.CreateAsync(user, password);
              await userManager.AddToRoleAsync(user.Id, RoleName);
            }
          }
        }
예제 #19
0
 public ActionResult Create(IdentityRole Role)
 {
     
     context.Roles.Add(Role);
     context.SaveChanges();
     return RedirectToAction("Index");
 }
        //lsakdjf ls
        public async Task<bool> Register(string email, int? schoolid, int instructorid, string password)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = email, Email = email };

                user.SchoolIdentity = schoolid;
                user.InstructorIdentity = instructorid;

                // user.SchoolID = model.SchoolID;
                var result = await UserManager.CreateAsync(user, password);

                var role = new IdentityRole("Instructor");
                var result2 = UserManager.AddToRole(user.Id, role.Name);



                if (result.Succeeded && result2.Succeeded)
                {
                    var 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", " UserName / Email = " + email + "\n Password : "******"Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");

                    return true;
                }
                else
                    return false;
            }
            else
                return false;
        }
예제 #21
0
 public RoleViewModel(IdentityRole role)
 {
     this.Id = role.Id;
     this.Name = role.Name;
     this.ConcurrencyStamp = role.ConcurrencyStamp;
     //this.Description = role.Description;
 }
 private void Delete(IdentityRole entity)
 {
     if (context.Entry(entity).State == EntityState.Detached)
     {
         dbSet.Attach(entity);
     }
     dbSet.Remove(entity);
 }
        public void Should_throw_ArgumentException_if_role_has_no_name()
        {
            var role = new IdentityRole();

            Assert.That(
                () => _target.CreateAsync(role),
                Throws.Exception.TypeOf<ArgumentException>().With.Message.EqualTo("Missing role Name"));
        }
 public RoleReturnModel Create(IdentityRole role)
 {
     return new RoleReturnModel()
     {
         Id = role.Id,
         Name = role.Name
     };
 }
 public static RoleListViewModel FromEntity(IdentityRole role)
 {
     return new RoleListViewModel
     {
         Id = role.Id,
         Name = role.Name,
     };
 }
        public void SeedAdminRole(AuctionDbContext context)
        {
            var store = new RoleStore<IdentityRole>(context);
            var manager = new RoleManager<IdentityRole>(store);
            var role = new IdentityRole { Name = "Admin" };

            manager.Create(role);
        }
예제 #27
0
        public async Task<IdentityRole> Add(IdentityRole role)
        {
            var newRole = new IdentityRole(role.Name);
            var roleresult = await RoleManager.CreateAsync(newRole);

            if (roleresult.Succeeded) return newRole;
            throw new DbUpdateException(roleresult.Errors.First());
        }
예제 #28
0
        public RoleReturnModel Create(IdentityRole role)
        {
            if (role == null) throw new ArgumentNullException(nameof(role));

            var model = Mapper.Map<RoleReturnModel>(role);
            model.Url = _urlHelper.Link("GetRoleById", new {id = role.Id});
            return model;
        }
        internal void CreateUserAndRole()
        {
            using (var context = new WebDeveloperDbContext())
            {

                var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
                var userManager = new UserManager<WebDeveloperUser>(new UserStore<WebDeveloperUser>(context));

                // In Startup iam creating first Admin Role and creating a default Admin User
                if (!roleManager.RoleExists("Admin"))
                {

                    // first we create Admin rool
                    var role = new IdentityRole();
                    role.Name = "Admin";
                    roleManager.Create(role);

                    //Here we create a Admin super user who will maintain the website

                    var user = new WebDeveloperUser
                    {
                        UserName = "******",
                        Email = "*****@*****.**"
                    };

                    string userPassword = "******";

                    var userCreation = userManager.Create(user, userPassword);

                    //Add default User to Role Admin
                    if (userCreation.Succeeded)
                        userManager.AddToRole(user.Id, "Admin");

                }

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

                }

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

                }
            }
        }
예제 #30
0
 public ActionResult CreateRole(IdentityRole identity)
 {
     db.Roles.Add(identity);
     db.SaveChanges();
     return(RedirectToAction("RoleList"));
 }
예제 #31
0
        public static async Task Initialize(IServiceProvider services)
        {
            ApplicationDbContext database = services.GetRequiredService <ApplicationDbContext>();

            UserManager <ApplicationUser> userManager = services.GetRequiredService <UserManager <ApplicationUser> >();

            RoleManager <IdentityRole> roleManager = services.GetRequiredService <RoleManager <IdentityRole> >();

            string roleCoach         = "Coach";
            string roleAdministrator = "Administrator";

            if (!database.Roles.Any())
            {
                IdentityRole role = new IdentityRole(roleCoach);
                await roleManager.CreateAsync(role);

                IdentityRole roleOne = new IdentityRole(roleAdministrator);
                await roleManager.CreateAsync(roleOne);
            }


            if (!database.Coaches.Any())
            {
                ApplicationUser appUser = new ApplicationUser("Test", "Administrator", "*****@*****.**", "304.000.0001", "test.administrator1");
                await userManager.CreateAsync(appUser);

                await userManager.AddToRoleAsync(appUser, roleAdministrator);


                ApplicationUser appUserTwo = new ApplicationUser("Test", "Coach", "*****@*****.**", "304.000.0003", "Test.Coach1");
                await userManager.CreateAsync(appUserTwo);

                await userManager.AddToRoleAsync(appUserTwo, roleCoach);

                ApplicationUser appUserThree = new ApplicationUser("TestTwo", "Coach", "*****@*****.**", "304.000.0004", "Test.Coach2");
                await userManager.CreateAsync(appUserThree);

                await userManager.AddToRoleAsync(appUserThree, roleCoach);
            }


            if (!database.Schools.Any())
            {
                School schoolOne = new School("Morgantown High School", "1 High St", "AAA", 1);
                database.Schools.Add(schoolOne);
                database.SaveChanges();

                schoolOne = new School("Braxton County High School", "200 Jerry Burton Dr", "AA", 2);
                database.Schools.Add(schoolOne);
                database.SaveChanges();

                /*
                 * schoolOne = new School("Oak Hill High School", "350 W Oyler Ave", "AA", 3);
                 * database.Schools.Add(schoolOne);
                 * schoolOne = new School("Winfield High School", "3022 Winfield Rd", "AA", 4);
                 * database.Schools.Add(schoolOne);
                 * schoolOne = new School("Elkins High School", "100 Kennedy Drive", "AA", 2);
                 * database.Schools.Add(schoolOne);
                 * schoolOne = new School("Hurricane High School", "3350 Teays Valley Road", "AAA", 4);
                 * database.Schools.Add(schoolOne);
                 * schoolOne = new School("Buckhannon Upshur High School", "270 B-U Dr.", "AAA", 1);
                 * database.Schools.Add(schoolOne);
                 * schoolOne = new School("Lewis County High SChool", "205 Minuteman Drive", "AA", 2);
                 * database.Schools.Add(schoolOne);
                 * schoolOne = new School("Webster County High", "One Highlander Drive", "A", 3);
                 * database.Schools.Add(schoolOne);
                 * schoolOne = new School("Tug Valley High School", "555 Panther Avenue", "A", 4);
                 * database.Schools.Add(schoolOne);
                 */

                database.SaveChanges();
            }

            if (!database.Players.Any())
            {
                Player playerOne = new Player("Waite", "Armstrong", "F");
                //playerOne.ID = 1;
                database.Players.Add(playerOne);
                database.SaveChanges();

                playerOne = new Player("Shaun", "Armstrong", "M");
                //playerOne.ID = 2;
                database.Players.Add(playerOne);
                database.SaveChanges();

                playerOne = new Player("Sean", "Armentrout", "G");
                //playerOne.ID = 3;
                database.Players.Add(playerOne);
                database.SaveChanges();

                playerOne = new Player("Don", "Aldeen", "M");
                //playerOne.ID = 4;
                database.Players.Add(playerOne);
                database.SaveChanges();

                playerOne = new Player("Ron", "Dobb", "D");
                //playerOne.ID = 5;
                database.Players.Add(playerOne);
                database.SaveChanges();

                playerOne = new Player("Shelton", "Wyant", "M");
                //playerOne.ID = 6;
                database.Players.Add(playerOne);
                database.SaveChanges();

                playerOne = new Player("Roscoe", "Alston", "F");
                //playerOne.ID = 7;
                database.Players.Add(playerOne);
                database.SaveChanges();

                playerOne = new Player("Juan", "Rodriguez", "D");
                //playerOne.ID = 8;
                database.Players.Add(playerOne);
                database.SaveChanges();

                /*
                 *
                 * playerOne = new Player("Charlie", "Fitzgerald", "M");
                 * playerOne.ID = 9;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("Ryan", "Smith", "M");
                 * playerOne.ID = 10;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("Lazar", "Djokovic", "M");
                 * playerOne.ID = 11;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("Lionel", "Messi", "G");
                 * playerOne.ID = 12;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("Zlatan", "Ibrahamovic", "F");
                 * playerOne.ID = 13;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("Jimmy", "Wright", "M");
                 * playerOne.ID = 14;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("James", "Crowder", "G");
                 * playerOne.ID = 15;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("John", "Wheeler", "F");
                 * playerOne.ID = 16;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("Adam", "Wilson", "D");
                 * playerOne.ID = 17;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("Cameron", "Harmon", "M");
                 * playerOne.ID = 18;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("James", "Antonson", "F");
                 * playerOne.ID = 19;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("Zach", "Williams", "F");
                 * playerOne.ID = 20;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("Rex", "Williamson", "D");
                 * playerOne.ID = 21;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("Mack", "Tillerson", "F");
                 * playerOne.ID = 22;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("Aaron", "Williamson", "D");
                 * playerOne.ID = 23;
                 * database.Players.Add(playerOne);
                 *
                 * playerOne = new Player("Allison", "Williamson", "D");
                 * playerOne.ID = 24;
                 * database.Players.Add(playerOne);
                 */
                database.SaveChanges();
            }

            if (!database.Teams.Any())
            {
                Team team = new Team("Male", "Mohigans");
                team.SchoolID = 1;
                team.Coach    = database.Coaches.Where(x => x.Email == "*****@*****.**").FirstOrDefault();
                database.Teams.Add(team);
                database.SaveChanges();

                /*
                 * Team teamOne = new Team("Male","Mohigans");
                 * teamOne.SchoolID = 1;
                 * teamOne.TeamID = 1;
                 * teamOne.Coach = database.Coaches.First();
                 * teamOne.CoachID = teamOne.Coach.Id;
                 * teamOne.School = database.Schools.Find(1);
                 * database.Teams.Add(teamOne);
                 * //teamOne.TeamID = 1;
                 *
                 * database.Teams.Add(teamOne);
                 * teamOne = new Team("Female", "Lady Mohigans", 1);
                 * teamOne.School = database.Schools.Find(1);
                 * teamOne.SchoolID = 1;
                 * //teamOne.TeamID = 2;
                 * database.Teams.Add(teamOne);
                 * teamOne = new Team("Male", "Eagles", 2);
                 * teamOne.School = database.Schools.Find(2);
                 * teamOne.SchoolID = 2;
                 * //teamOne.TeamID = 3;
                 * database.Teams.Add(teamOne);
                 * teamOne = new Team("Female", "Lady Eagles", 2);
                 * teamOne.School = database.Schools.Find(2);
                 * teamOne.SchoolID = 2;
                 * //teamOne.TeamID = 4;
                 * database.Teams.Add(teamOne);
                 * database.SaveChanges();
                 */
            }



            if (!database.TeamPlayers.Any())
            {
                DateTime   startDate     = new DateTime(2018, 8, 15);
                DateTime   endDate       = new DateTime(2019, 8, 15);
                TeamPlayer teamPlayerOne = new TeamPlayer(startDate, 1, 1);
                teamPlayerOne.TeamPlayerID = 1;
                database.TeamPlayers.Add(teamPlayerOne);
                database.SaveChanges();

                teamPlayerOne = new TeamPlayer(DateTime.Now, 2, 1);
                teamPlayerOne.TeamPlayerID = 2;
                database.TeamPlayers.Add(teamPlayerOne);
                database.SaveChanges();

                teamPlayerOne = new TeamPlayer(DateTime.Now, 3, 1);
                teamPlayerOne.TeamPlayerID = 3;
                database.TeamPlayers.Add(teamPlayerOne);
                database.SaveChanges();

                teamPlayerOne              = new TeamPlayer(startDate, 4, 2);
                teamPlayerOne.EndDate      = endDate;
                teamPlayerOne.TeamPlayerID = 4;
                database.TeamPlayers.Add(teamPlayerOne);
                database.SaveChanges();
            }

            //By Monday at 4:00 update google doc with user stories, business rules
        }
예제 #32
0
 public bool IsInRole(IdentityRole role)
 {
     return(this.Roles.Any(x => x.RoleId == role.Id));
 }
예제 #33
0
        protected override void Seed(TaxiDbContext context)
        {
            foreach (UserRoles role in Enum.GetValues(typeof(UserRoles)))
            {
                if (!context.Roles.Any(r => r.Name == role.ToString()))
                {
                    var store   = new RoleStore <IdentityRole>(context);
                    var manager = new RoleManager <IdentityRole>(store);
                    var newRole = new IdentityRole {
                        Name = role.ToString()
                    };
                    manager.Create(newRole);
                }
            }

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser
                {
                    UserName    = "******",
                    FirstName   = "Borislav",
                    MiddleName  = "Vladimirov",
                    LastName    = "Boyadzhiev",
                    Email       = "*****@*****.**",
                    PhoneNumber = "0886176803"
                };

                manager.Create(user, "passW0RD");
                manager.AddToRole(user.Id, UserRoles.Administrator.ToString());
                manager.AddToRole(user.Id, UserRoles.Manager.ToString());
                manager.AddToRole(user.Id, UserRoles.Operator.ToString());
            }

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser
                {
                    UserName    = "******",
                    FirstName   = "Arif",
                    MiddleName  = "Ali",
                    LastName    = "Mondal",
                    Email       = "*****@*****.**",
                    PhoneNumber = "0538557493"
                };

                manager.Create(user, "Admin@123");
                manager.AddToRole(user.Id, UserRoles.Administrator.ToString());
                manager.AddToRole(user.Id, UserRoles.Manager.ToString());
                manager.AddToRole(user.Id, UserRoles.Operator.ToString());
            }

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);

                var demoManager = new ApplicationUser
                {
                    UserName    = "******",
                    FirstName   = "Jasper",
                    MiddleName  = "Newton",
                    LastName    = "Daniel",
                    Email       = "*****@*****.**",
                    PhoneNumber = "0888333111"
                };

                manager.Create(demoManager, "Admin@123");
                manager.AddToRole(demoManager.Id, UserRoles.Manager.ToString());
            }

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);

                var demoDriver = new ApplicationUser
                {
                    UserName    = "******",
                    FirstName   = "Shisho",
                    MiddleName  = "D.",
                    LastName    = "Bakshisho",
                    Email       = "*****@*****.**",
                    PhoneNumber = "0888000111"
                };

                manager.Create(demoDriver, "Admin@123");
                manager.AddToRole(demoDriver.Id, UserRoles.Driver.ToString());
            }

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store    = new UserStore <ApplicationUser>(context);
                var manager  = new UserManager <ApplicationUser>(store);
                var demoUser = new ApplicationUser
                {
                    UserName    = "******",
                    FirstName   = "Mary",
                    MiddleName  = "Jane",
                    LastName    = "Watson",
                    Email       = "*****@*****.**",
                    PhoneNumber = "0888222555"
                };

                manager.Create(demoUser, "Admin@123");
                manager.AddToRole(demoUser.Id, UserRoles.Driver.ToString());
            }

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);

                var demoOperator2 = new ApplicationUser
                {
                    UserName    = "******",
                    FirstName   = "Charlie",
                    MiddleName  = "Donathan",
                    LastName    = "Doe",
                    Email       = "*****@*****.**",
                    PhoneNumber = "0888222666"
                };

                manager.Create(demoOperator2, "charlie");
                manager.AddToRole(demoOperator2.Id, UserRoles.Operator.ToString());
            }
        }
        public async Task <IActionResult> CreateRole(IdentityRole role)
        {
            await rolemanager.CreateAsync(role);

            return(RedirectToAction("CreateRole"));
        }
        public void Setup()
        {
            _postRepository = new Mock <IBlogRepository>(MockBehavior.Strict);
            _userRepository = new Mock <IUserRepository>(MockBehavior.Strict);
            _adminBuilder   = new AdminModelBuilder(_userRepository.Object, _postRepository.Object);

            _user1 = new ApplicationUser()
            {
                Id       = "1",
                UserName = "******"
            };
            _user2 = new ApplicationUser()
            {
                Id       = "2",
                UserName = "******"
            };
            _user3 = new ApplicationUser()
            {
                Id       = "3",
                UserName = "******"
            };
            _userList = new List <ApplicationUser>();
            _userList.Add(_user1);
            _userList.Add(_user2);
            _userList.Add(_user3);

            _role1 = new IdentityRole()
            {
                Id   = "1",
                Name = "user"
            };
            _role2 = new IdentityRole()
            {
                Id   = "1",
                Name = "admin"
            };
            _roleList = new List <IdentityRole>();
            _roleList.Add(_role1);
            _roleList.Add(_role2);

            _userRole1 = new IdentityUserRole()
            {
                UserId = "1",
                RoleId = "1"
            };
            _userRole2 = new IdentityUserRole()
            {
                UserId = "2",
                RoleId = "1"
            };
            _userRole3 = new IdentityUserRole()
            {
                UserId = "3",
                RoleId = "2"
            };
            _userRoleList = new List <IdentityUserRole>();
            _userRoleList.Add(_userRole1);
            _userRoleList.Add(_userRole2);
            _userRoleList.Add(_userRole3);

            _report1 = new Report()
            {
                Id         = 1,
                Comment    = new Comment(),
                CommentId  = 1,
                SenderName = "shrook",
                ReportText = "sie"
            };
            _report2 = new Report()
            {
                Id         = 2,
                Comment    = new Comment(),
                CommentId  = 2,
                SenderName = "shrookster",
                ReportText = "siege"
            };
            _reportList = new List <Report>();
            _reportList.Add(_report1);
            _reportList.Add(_report2);

            _userRepository.Setup(x => x.GetUsers()).Returns(_userList);
            _userRepository.Setup(x => x.GetRoles()).Returns(_roleList);
            _userRepository.Setup(x => x.GetUserRoles()).Returns(_userRoleList);
            _userRepository.Setup(x => x.GetUserRole(_user1.Id)).Returns(_role1);
            _userRepository.Setup(x => x.GetUserRole(_user2.Id)).Returns(_role1);
            _userRepository.Setup(x => x.GetUserRole(_user3.Id)).Returns(_role2);

            _postRepository.Setup(x => x.GetReports()).Returns(_reportList);
        }
예제 #36
0
        protected override void Seed(s00163005Week6Lab2.Models.ApplicationDbContext context)
        {
            var manager =
                new UserManager <ApplicationUser>(
                    new UserStore <ApplicationUser>(context));

            var roleManager =
                new RoleManager <IdentityRole>(
                    new RoleStore <IdentityRole>(context));

            if (context.Roles.FirstOrDefault(r => r.Name == "Admin") == null)
            {
                context.Roles.Add(new IdentityRole {
                    Name = "Admin"
                });
            }

            context.Roles.AddOrUpdate(r => r.Name,
                                      new IdentityRole {
                Name = "ClubAdmin"
            });

            context.Roles.AddOrUpdate(r => r.Name,
                                      new IdentityRole {
                Name = "Member"
            });

            context.SaveChanges();
            // Seed Users
            PasswordHasher p = new PasswordHasher();

            context.Users.AddOrUpdate(u => u.StudentID,
                                      new ApplicationUser
            {
                StudentID     = "S00000001",
                Email         = "*****@*****.**",
                PasswordHash  = p.HashPassword("Sxxxxxx1$1"),
                SignupDate    = DateTime.Now,
                UserName      = "******",
                SecurityStamp = Guid.NewGuid().ToString(),
            });
            context.SaveChanges();

            ApplicationUser usr = new ApplicationUser
            {
                StudentID     = "S00000002",
                Email         = "*****@*****.**",
                SignupDate    = DateTime.Now,
                UserName      = "******",
                PasswordHash  = p.HashPassword("Sxxxxxx2$1"),
                SecurityStamp = Guid.NewGuid().ToString(),
            };

            context.Users.AddOrUpdate(u => u.StudentID, usr);
            //manager.Create(usr, "Sxxxxxx2$1");

            var result = manager.Create(new ApplicationUser
            {
                StudentID     = "ppowell",
                Email         = "*****@*****.**",
                SignupDate    = DateTime.Now,
                UserName      = "******",
                SecurityStamp = Guid.NewGuid().ToString(),
            }, "Ppowell$1");

            if (!result.Succeeded)
            {
                throw new Exception("Manager Failed to create");
            }

            context.SaveChanges();
            // Setup Paul Powell as system Admin Role
            IdentityRole adminRole = roleManager.FindByName("Admin");

            if (adminRole != null)
            {
                ApplicationUser adminUser = manager.FindByName("PaulPowell");
                if (adminUser != null && adminUser.Roles.Count() < 1)
                {
                    adminUser.Roles.Add(new IdentityUserRole {
                        RoleId = adminRole.Id, UserId = adminUser.Id
                    });
                }
            }
            // Setup Jennifer as system Club Admin Role
            IdentityRole clubAdminRole = roleManager.FindByName("ClubAdmin");

            if (clubAdminRole != null)
            {
                ApplicationUser adminUser = manager.FindByName("Jennfer Ecceles");
                if (adminUser != null && adminUser.Roles.Count() < 1)
                {
                    adminUser.Roles.Add(new IdentityUserRole {
                        RoleId = clubAdminRole.Id, UserId = adminUser.Id
                    });
                }
            }
            // Setup Bill as system member Role
            IdentityRole memberRole = roleManager.FindByName("Member");

            if (memberRole != null)
            {
                ApplicationUser adminUser = manager.FindByName("Bill Bloggs");
                if (adminUser != null && adminUser.Roles.Count() < 1)
                {
                    adminUser.Roles.Add(new IdentityUserRole {
                        RoleId = memberRole.Id, UserId = adminUser.Id
                    });
                }
            }

            context.SaveChanges();
        }
예제 #37
0
 public virtual Task RemoveRoleFromOrganizationUnitAsync(IdentityRole role, OrganizationUnit organizationUnit)
 {
     organizationUnit.RemoveRole(role.Id);
     return(OrganizationUnitRepository.UpdateAsync(organizationUnit));
 }
예제 #38
0
        public void Setup(IServiceProvider service, IConfiguration config)
        {
            var userManager = service.GetRequiredService <UserManager <ApplicationUser> >();
            var roleManager = service.GetRequiredService <RoleManager <IdentityRole> >();

            //create admin user if not exist
            var adminUser = userManager.FindByNameAsync("admin").GetAwaiter().GetResult();

            if (adminUser == null)
            {
                adminUser = new ApplicationUser
                {
                    UserName = config["Admin:Username"],
                    Email    = config["Admin:Email"]
                };
                var result = userManager.CreateAsync(adminUser, config["Admin:Password"]).GetAwaiter().GetResult();

                if (!result.Succeeded)
                {
                    throw new Exception();
                }
            }

            //create admin role if not exist
            var adminRole = roleManager.FindByNameAsync("Admin").GetAwaiter().GetResult();

            if (adminRole == null)
            {
                adminRole = new IdentityRole("Admin");
                var result = roleManager.CreateAsync(adminRole).GetAwaiter().GetResult();
                if (!result.Succeeded)
                {
                    throw new Exception();
                }
            }

            //assign admin role if not exist
            var isAdmin = userManager.IsInRoleAsync(adminUser, adminRole.Name).GetAwaiter().GetResult();

            if (!isAdmin)
            {
                var result = userManager.AddToRoleAsync(adminUser, adminRole.Name).GetAwaiter().GetResult();
                if (!result.Succeeded)
                {
                    throw new Exception();
                }
            }

            //create customer role if not exist
            var customerRole = roleManager.FindByNameAsync("Customer").GetAwaiter().GetResult();

            if (customerRole == null)
            {
                customerRole = new IdentityRole("Customer");
                var result = roleManager.CreateAsync(customerRole).GetAwaiter().GetResult();
                if (!result.Succeeded)
                {
                    throw new Exception();
                }
            }
        }
예제 #39
0
 public ActionResult Create(IdentityRole Role)
 {
     db.Roles.Add(Role);
     db.SaveChanges();
     return(RedirectToAction("Index"));
 }
예제 #40
0
 public IdentityRoleDto GetModel(IdentityRole role)
 {
     return(new IdentityRoleDto
     {
         Id = role.Id,
         RoleName = role.Name,
         Users = role.Users.Select(u => new UserDto
         {
             Id = u.UserId,
             Links = new List <Link>
             {
                 new Link
                 {
                     Rel = "get user info - Administrators only",
                     Href = _url.Link("GetUserInfoRoute", new { id = u.UserId }),
                     Method = "GET"
                 },
                 new Link
                 {
                     Rel = "get user roles - Administrators only",
                     Href = _url.Link("GetUserRolesRoute", new { id = u.UserId }),
                     Method = "GET"
                 }
             }
         }),
         Links = new List <Link>
         {
             new Link
             {
                 Rel = "self - Administrators only",
                 Href = _url.Link("RoleRoute", new { id = role.Id }),
                 Method = "GET"
             },
             new Link
             {
                 Rel = "self by roleName- Administrators only",
                 Href = _url.Link("RoleByRoleNameRoute", new { roleName = role.Name }),
                 Method = "GET"
             },
             new Link
             {
                 Rel = "put role - Administrators only",
                 Href = _url.Link("RoleRoute", new { id = role.Id }),
                 Method = "PUT"
             },
             new Link
             {
                 Rel = "delete role - Administrators only",
                 Href = _url.Link("RoleRoute", new { id = role.Id }),
                 Method = "DELETE"
             },
             new Link
             {
                 Rel = "add user to role - Administrators only",
                 Href = _url.Link("AddUserToRoleRoute", null),
                 Method = "POST"
             },
             new Link
             {
                 Rel = "remove role from user - Administrators only",
                 Href = _url.Link("RemoveUserRoleRoute", null),
                 Method = "POST"
             },
             new Link
             {
                 Rel = "get my roles",
                 Href = _url.Link("GetMyRolesRoute", null),
                 Method = "GET"
             }
         }
     });
 }
예제 #41
0
        protected override void Seed(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. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
            var store   = new RoleStore <IdentityRole>(context);
            var manager = new RoleManager <IdentityRole>(store);
            var role    = new IdentityRole();

            if (!context.Roles.Any(r => r.Name == "Admin"))
            {
                role = new IdentityRole {
                    Name = "Admin"
                };
                manager.Create(role);
            }

            if (!context.Roles.Any(r => r.Name == "Developer"))
            {
                role = new IdentityRole {
                    Name = "Developer"
                };
                manager.Create(role);
            }

            if (!context.Roles.Any(r => r.Name == "Submitter"))
            {
                role = new IdentityRole {
                    Name = "Submitter"
                };
                manager.Create(role);
            }

            if (!context.Roles.Any(r => r.Name == "ProjectManager"))
            {
                role = new IdentityRole {
                    Name = "ProjectManager"
                };
                manager.Create(role);
            }

            if (!context.Roles.Any(r => r.Name == "Tester"))
            {
                role = new IdentityRole {
                    Name = "Tester"
                };
                manager.Create(role);
            }

            //context.Roles.AddOrUpdate(n => n.Name == "Tester");

            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new UserManager <ApplicationUser>(userStore);

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Antonio",
                    LastName    = "Raynor",
                    DisplayName = "ANIVRA"
                };

                userManager.Create(user, "Abc&123!");

                userManager.AddToRoles(user.Id,
                                       new string[] {
                    "Admin",
                    "ProjectManager",
                    "Developer",
                    "Submitter",
                    "Tester"
                });
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Administrator",
                    LastName    = "Role",
                    DisplayName = "ADMIN"
                };

                userManager.Create(user, "Abc&123!");

                userManager.AddToRoles(user.Id,
                                       new string[] {
                    "Admin"
                });
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Manager",
                    LastName    = "Role",
                    DisplayName = "MANGR"
                };

                userManager.Create(user, "Abc&123!");

                userManager.AddToRoles(user.Id,
                                       new string[] {
                    "ProjectManager"
                });
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Developer",
                    LastName    = "Role",
                    DisplayName = "DEVPR"
                };

                userManager.Create(user, "Abc&123!");

                userManager.AddToRoles(user.Id,
                                       new string[] {
                    "Developer"
                });
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Submitter",
                    LastName    = "Role",
                    DisplayName = "SUBMT"
                };

                userManager.Create(user, "Abc&123!");

                userManager.AddToRoles(user.Id,
                                       new string[] {
                    "Submitter"
                });
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                {
                    userManager.Create(new ApplicationUser
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        FirstName   = "Test1",
                        LastName    = "User1",
                        DisplayName = "ImaTest1"
                    }, "Abc&123!");
                }
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                {
                    userManager.Create(new ApplicationUser
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        FirstName   = "Test2",
                        LastName    = "User2",
                        DisplayName = "ImaTest2"
                    }, "Abc&123!");
                }
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                {
                    userManager.Create(new ApplicationUser
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        FirstName   = "Test3",
                        LastName    = "User3",
                        DisplayName = "ImaTest3"
                    }, "Abc&123!");
                }
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                {
                    userManager.Create(new ApplicationUser
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        FirstName   = "Test4",
                        LastName    = "User4",
                        DisplayName = "ImaTest4"
                    }, "Abc&123!");
                }
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                {
                    userManager.Create(new ApplicationUser
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        FirstName   = "Test5",
                        LastName    = "User5",
                        DisplayName = "ImaTest5"
                    }, "Abc&123!");
                }
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                {
                    userManager.Create(new ApplicationUser
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        FirstName   = "Test6",
                        LastName    = "User6",
                        DisplayName = "ImaTest6"
                    }, "Abc&123!");
                }
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                {
                    userManager.Create(new ApplicationUser
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        FirstName   = "Test7",
                        LastName    = "User7",
                        DisplayName = "ImaTest7"
                    }, "Abc&123!");
                }
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                {
                    userManager.Create(new ApplicationUser
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        FirstName   = "Test8",
                        LastName    = "User8",
                        DisplayName = "ImaTest8"
                    }, "Abc&123!");
                }
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                {
                    userManager.Create(new ApplicationUser
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        FirstName   = "Test9",
                        LastName    = "User9",
                        DisplayName = "ImaTest9"
                    }, "Abc&123!");
                }
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                {
                    userManager.Create(new ApplicationUser
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        FirstName   = "Test10",
                        LastName    = "User10",
                        DisplayName = "ImaTest10"
                    }, "Abc&123!");
                }
            }

            if (!context.TicketPriorities.Any(u => u.Name == "High"))
            {
                context.TicketPriorities.Add(new TicketPriority {
                    Name = "High"
                });
            }

            if (!context.TicketPriorities.Any(u => u.Name == "Medium"))
            {
                context.TicketPriorities.Add(new TicketPriority {
                    Name = "Medium"
                });
            }

            if (!context.TicketPriorities.Any(u => u.Name == "Low"))
            {
                context.TicketPriorities.Add(new TicketPriority {
                    Name = "Low"
                });
            }

            if (!context.TicketPriorities.Any(u => u.Name == "Urgent"))
            {
                context.TicketPriorities.Add(new TicketPriority {
                    Name = "Urgent"
                });
            }



            if (!context.TicketTypes.Any(u => u.Name == "Production Fix"))
            {
                context.TicketTypes.Add(new TicketType {
                    Name = "Production Fix"
                });
            }

            if (!context.TicketTypes.Any(u => u.Name == "Project Task"))
            {
                context.TicketTypes.Add(new TicketType {
                    Name = "Project Task"
                });
            }

            if (!context.TicketTypes.Any(u => u.Name == "Software Update"))
            {
                context.TicketTypes.Add(new TicketType {
                    Name = "Software Update"
                });
            }



            if (!context.TicketStatuses.Any(u => u.Name == "New"))
            {
                context.TicketStatuses.Add(new TicketStatus {
                    Name = "New"
                });
            }

            if (!context.TicketStatuses.Any(u => u.Name == "In Development"))
            {
                context.TicketStatuses.Add(new TicketStatus {
                    Name = "In Development"
                });
            }

            if (!context.TicketStatuses.Any(u => u.Name == "Completed"))
            {
                context.TicketStatuses.Add(new TicketStatus {
                    Name = "Completed"
                });
            }
        }
예제 #42
0
        public void CreateUserAndRoles()
        {
            //// get the db context
            ApplicationDbContext context = new ApplicationDbContext();

            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

            bool exists = roleManager.RoleExists("Admin");

            if (!exists)
            {
                /// if this role doesnt exist create it
                var adminrole = new IdentityRole("Admin");
                roleManager.Create(adminrole);

                /// create default user
                var user = new ApplicationUser();
                user.UserName          = "******";
                user.EmailConfirmed    = false;
                user.PhoneNumber       = null;
                user.AccessFailedCount = 0;
                user.LockoutEnabled    = true;
                user.LockoutEndDateUtc = null;
                user.TwoFactorEnabled  = false;
                user.Email             = "*****@*****.**";
                string pass = "******";


                //// takes two params IdentityUser and password
                var adminuser = userManager.Create(user, pass);
                if (adminuser.Succeeded)
                {
                    userManager.AddToRoles(user.Id, "Admin");
                }
            }
            if (!roleManager.RoleExists("StaffOfficer"))
            {
                /// if this role doesnt exist create it
                var userrole = new IdentityRole("StaffOfficer");
                roleManager.Create(userrole);

                /// create default user
                var user1 = new ApplicationUser();
                user1.UserName          = "******";
                user1.EmailConfirmed    = false;
                user1.PhoneNumber       = null;
                user1.AccessFailedCount = 0;
                user1.LockoutEnabled    = true;
                user1.LockoutEndDateUtc = null;
                user1.TwoFactorEnabled  = false;
                user1.Email             = "*****@*****.**";
                string pass = "******";

                var newuser = userManager.Create(user1, pass);
                if (newuser.Succeeded)
                {
                    userManager.AddToRoles(user1.Id, "StaffOfficer");
                }
            }
            if (!roleManager.RoleExists("StaffAdmin"))
            {
                /// if this role doesnt exist create it
                var userrole = new IdentityRole("StaffAdmin");
                roleManager.Create(userrole);

                /// create default user
                var user2 = new ApplicationUser();
                user2.UserName          = "******";
                user2.EmailConfirmed    = false;
                user2.PhoneNumber       = null;
                user2.AccessFailedCount = 0;
                user2.LockoutEnabled    = true;
                user2.LockoutEndDateUtc = null;
                user2.TwoFactorEnabled  = false;
                user2.Email             = "*****@*****.**";
                string pass = "******";

                var newuser = userManager.Create(user2, pass);
                if (newuser.Succeeded)
                {
                    userManager.AddToRoles(user2.Id, "StaffAdmin");
                }
            }
        }
예제 #43
0
        public static void Initialize(ApplicationDbContext context, UserManager <ApplicationUser> userManager, RoleManager <IdentityRole> roleManager)
        {
            if (context.Users.ToList().Count == 0)
            {
                var aUser = new ApplicationUser();
                aUser.UserName = "******";
                aUser.Email    = "*****@*****.**";
                var r = userManager.CreateAsync(aUser, "Pa$$w0rd").Result;

                var adminUser = new ApplicationUser();
                adminUser.UserName     = "******";
                adminUser.Email        = "*****@*****.**";
                adminUser.PhoneNumber  = "0701111222";
                adminUser.CustomerName = "Madoka";
                adminUser.Street       = "Kungsgatan 123";
                adminUser.PostalCode   = "12345";
                adminUser.City         = "Stockholm";

                var adminUserResult = userManager.CreateAsync(adminUser, "Pa$$w0rd").Result;

                var adminRole = new IdentityRole {
                    Name = "Admin"
                };
                var roleResult = roleManager.CreateAsync(adminRole).Result;

                userManager.AddToRoleAsync(adminUser, "Admin").Wait();
            }

            //Om det inte finns Dishes i databasen
            if (context.Dishes.ToList().Count == 0)
            {
                var pizzaImage    = LoadImage.GetPictureData("wwwroot/images/pizza.jpg");
                var carzonesImage = LoadImage.GetPictureData("wwwroot/images/carzone.jpg");
                var dessertImage  = LoadImage.GetPictureData("wwwroot/images/dessert.jpg");

                var pizza = new DishCategory {
                    Description = "Pizza"
                };
                var carzone = new DishCategory {
                    Description = "Calzone"
                };
                var dessert = new DishCategory {
                    Description = "Dessert"
                };

                context.DishCategories.Add(pizza);
                context.DishCategories.Add(carzone);
                context.DishCategories.Add(dessert);

                var cheese = new Ingredient {
                    Name = "Cheese", Price = 30
                };
                var tomato = new Ingredient {
                    Name = "Tomato", Price = 10
                };
                var ham = new Ingredient {
                    Name = "Ham", Price = 25
                };
                var pineapple = new Ingredient {
                    Name = "Pineapple", Price = 10
                };
                var bacon = new Ingredient {
                    Name = "Bacon", Price = 25
                };
                var onions = new Ingredient {
                    Name = "Onions", Price = 10
                };
                var mushrooms = new Ingredient {
                    Name = "Mushrooms", Price = 20
                };
                var apple = new Ingredient {
                    Name = "Apple", Price = 20
                };
                var currySauce = new Ingredient {
                    Name = "Curry sauce", Price = 15
                };
                var banana = new Ingredient {
                    Name = "Banana", Price = 10
                };

                var capricciosa = new Dish {
                    Name = "Capricciosa", Price = 79, Image = pizzaImage, DishCategory = pizza
                };
                var margaritha = new Dish {
                    Name = "Margaritha", Price = 69, Image = pizzaImage, DishCategory = pizza
                };
                var hawaii = new Dish {
                    Name = "Hawaii", Price = 85, Image = pizzaImage, DishCategory = pizza
                };
                var tropical = new Dish {
                    Name = "Tropical", Price = 75, Image = pizzaImage, DishCategory = pizza
                };
                var veggie = new Dish {
                    Name = "Veggie", Price = 95, Image = pizzaImage, DishCategory = pizza
                };
                var calzone = new Dish {
                    Name = "Calzone", Price = 100, Image = carzonesImage, DishCategory = carzone
                };
                var calzoneSp = new Dish {
                    Name = "Calzone SP", Price = 115, Image = carzonesImage, DishCategory = carzone
                };
                var applePie = new Dish {
                    Name = "Apple pie", Price = 70, Image = dessertImage, DishCategory = dessert
                };

                var capricciosaHam = new DishIngredient {
                    Dish = capricciosa, Ingredient = ham
                };
                var capricciosaMushrooms = new DishIngredient {
                    Dish = capricciosa, Ingredient = mushrooms
                };
                capricciosa.DishIngredients = new List <DishIngredient>();
                capricciosa.DishIngredients.Add(capricciosaHam);
                capricciosa.DishIngredients.Add(capricciosaMushrooms);

                var margarithaCheese = new DishIngredient {
                    Dish = margaritha, Ingredient = cheese
                };
                margaritha.DishIngredients = new List <DishIngredient>();
                margaritha.DishIngredients.Add(margarithaCheese);

                var hawaiiHam = new DishIngredient {
                    Dish = hawaii, Ingredient = ham
                };
                var hawaiiPineapple = new DishIngredient {
                    Dish = hawaii, Ingredient = pineapple
                };
                hawaii.DishIngredients = new List <DishIngredient>();
                hawaii.DishIngredients.Add(hawaiiHam);
                hawaii.DishIngredients.Add(hawaiiPineapple);

                var tropicalBanana = new DishIngredient {
                    Dish = tropical, Ingredient = banana
                };
                var tropicalCurrySauce = new DishIngredient {
                    Dish = tropical, Ingredient = currySauce
                };
                tropical.DishIngredients = new List <DishIngredient>();
                tropical.DishIngredients.Add(tropicalBanana);
                tropical.DishIngredients.Add(tropicalCurrySauce);

                var veggieMushrooms = new DishIngredient {
                    Dish = veggie, Ingredient = mushrooms
                };
                var veggieOnions = new DishIngredient {
                    Dish = veggie, Ingredient = onions
                };
                var veggieTomato = new DishIngredient {
                    Dish = veggie, Ingredient = tomato
                };
                veggie.DishIngredients = new List <DishIngredient>();
                veggie.DishIngredients.Add(veggieMushrooms);
                veggie.DishIngredients.Add(veggieOnions);
                veggie.DishIngredients.Add(veggieTomato);

                var calzoneHam = new DishIngredient {
                    Dish = calzone, Ingredient = ham
                };
                calzone.DishIngredients = new List <DishIngredient>();
                calzone.DishIngredients.Add(calzoneHam);

                var calzoneSpHam = new DishIngredient {
                    Dish = calzoneSp, Ingredient = ham
                };
                var calzoneSpMushrooms = new DishIngredient {
                    Dish = calzoneSp, Ingredient = mushrooms
                };
                calzoneSp.DishIngredients = new List <DishIngredient>();
                calzoneSp.DishIngredients.Add(calzoneSpHam);
                calzoneSp.DishIngredients.Add(calzoneSpMushrooms);

                var applePieApple = new DishIngredient {
                    Dish = applePie, Ingredient = apple
                };
                applePie.DishIngredients = new List <DishIngredient>();
                applePie.DishIngredients.Add(applePieApple);

                context.Dishes.Add(capricciosa);
                context.Dishes.Add(margaritha);
                context.Dishes.Add(hawaii);
                context.Dishes.Add(tropical);
                context.Dishes.Add(veggie);
                context.Dishes.Add(calzone);
                context.Dishes.Add(calzoneSp);
                context.Dishes.Add(applePie);

                var visa = new Card {
                    Name = "Visa"
                };
                var masterCard = new Card {
                    Name = "Master card"
                };

                context.Cards.Add(visa);
                context.Cards.Add(masterCard);

                context.SaveChanges();
            }
        }
        public async Task <ActionResult> Delete(string id)
        {
            IdentityRole ir = await RoleManager.FindByNameAsync(id);

            return(View(ir));
        }
예제 #45
0
        // Method shell from https://code.msdn.microsoft.com/ASPNET-MVC-5-Security-And-44cbdb97
        private void CreateUsersAndRoles()
        {
            SymHackContext context = new SymHackContext();

            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var userManager = new UserManager <SymHackUser>(new UserStore <SymHackUser>(context));


            // In Startup iam creating first Admin Role and creating a default Admin User
            if (!roleManager.RoleExists("Admin"))
            {
                // first we create Admin role
                var role = new IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);

                //Here we create a Admin super user who will maintain the website
                var user = new SymHackUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";

                string userPWD = "Mohawk1234!";

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

                //Add default User to Role Admin
                if (chkUser.Succeeded)
                {
                    var result1 = userManager.AddToRole(user.Id, "Admin");
                }
            }

            // Creating teacher role
            if (!roleManager.RoleExists("Teacher"))
            {
                var role = new IdentityRole();
                role.Name = "Teacher";
                roleManager.Create(role);

                // Create default teacher - in future move to a request admin must confirm
                var user = new SymHackUser();
                user.UserName = "";
                user.Email    = "*****@*****.**";

                string userPWD = "Mohawk1234!";

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

                //Add default User to Role Admin
                if (chkUser.Succeeded)
                {
                    var result1 = userManager.AddToRole(user.Id, "Admin");
                }
            }

            // Creating student role
            if (!roleManager.RoleExists("Student"))
            {
                var role = new IdentityRole();
                role.Name = "Student";
                roleManager.Create(role);
            }

            // Creating pending teacher role
            if (!roleManager.RoleExists("PendingTeacher"))
            {
                var role = new IdentityRole();
                role.Name = "PendingTeacher";
                roleManager.Create(role);
            }
        }
예제 #46
0
        public async Task <IActionResult> Create(IdentityRole role)
        {
            await _roleManager.CreateAsync(role);

            return(RedirectToAction("Index"));
        }
 private void SeedAllRoles(ApplicationDbContext dbContext)
 {
     this.AdminRole = SeedRolesMethods.SeedAdminRole(dbContext);
     this.UserRole  = SeedRolesMethods.SeedUserRole(dbContext);
 }
예제 #48
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var serviceScope = host.Services.CreateScope())
            {
                var identityContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                var dbContext       = serviceScope.ServiceProvider.GetRequiredService <DataContext>();

                await identityContext.Database.MigrateAsync();

                await dbContext.Database.MigrateAsync();

                var roleManager = serviceScope.ServiceProvider.GetRequiredService <RoleManager <IdentityRole> >();
                var userManager = serviceScope.ServiceProvider.GetRequiredService <UserManager <IdentityUser> >();
                var dataContext = serviceScope.ServiceProvider.GetRequiredService <DataContext>();

                if (!await roleManager.RoleExistsAsync("Administrator"))
                {
                    var adminRole = new IdentityRole("Administrator");
                    await roleManager.CreateAsync(adminRole);
                }

                if (!await roleManager.RoleExistsAsync("Volunteer"))
                {
                    var adminRole = new IdentityRole("Volunteer");
                    await roleManager.CreateAsync(adminRole);
                }

                if (!await dataContext.ApplicationUsers.AnyAsync())
                {
                    var user = new IdentityUser
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        PhoneNumber = "0000000000"
                    };
                    var response = await userManager.CreateAsync(user, "MasterPassword@1992");

                    if (response.Succeeded)
                    {
                        var newUser = await userManager.FindByEmailAsync(user.Email);

                        var roleResponse = await userManager.AddToRoleAsync(newUser, "Administrator");

                        if (roleResponse.Succeeded)
                        {
                            ApplicationUser applicationUser = new ApplicationUser
                            {
                                Name        = "Master User",
                                Gender      = "Male",
                                DateOfBirth = DateTime.Now.Date,
                                UserId      = newUser.Id,
                                DateAdded   = DateTime.Now.Date,
                                Nationality = "Ghanaian"
                            };

                            await dataContext.ApplicationUsers.AddAsync(applicationUser);

                            await dataContext.SaveChangesAsync();
                        }
                    }
                }

                await host.RunAsync();
            }
        }
예제 #49
0
        public static void EnsureSeedData(string connectionString)
        {
            var services = new ServiceCollection();

            services.AddLogging();
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(connectionString));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            using (var serviceProvider = services.BuildServiceProvider())
            {
                using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    var context = scope.ServiceProvider.GetService <ApplicationDbContext>();
                    context.Database.Migrate();

                    var roleMgr   = scope.ServiceProvider.GetRequiredService <RoleManager <IdentityRole> >();
                    var adminrole = roleMgr.FindByNameAsync("Administrator").Result;
                    if (adminrole == null)
                    {
                        adminrole = new IdentityRole
                        {
                            Name           = "Administrator",
                            NormalizedName = "Administrator"
                        };
                        var res = roleMgr.CreateAsync(adminrole).Result;
                    }
                    var userRole = roleMgr.FindByNameAsync("User").Result;
                    if (userRole == null)
                    {
                        userRole = new IdentityRole
                        {
                            Name           = "User",
                            NormalizedName = "User"
                        };
                        var res = roleMgr.CreateAsync(userRole).Result;
                    }

                    var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();
                    var alice   = userMgr.FindByNameAsync("alice").Result;
                    if (alice == null)
                    {
                        alice = new ApplicationUser
                        {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            EmailConfirmed = true,
                        };
                        var result = userMgr.CreateAsync(alice, "Pass123$").Result;
                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }
                        else
                        {
                            if (roleMgr.RoleExistsAsync("Administrator").Result)
                            {
                                var i = userMgr.AddToRoleAsync(alice, "Administrator").Result;
                            }
                        }

                        result = userMgr.AddClaimsAsync(alice, new Claim[] {
                            new Claim(JwtClaimTypes.Name, "Alice Smith"),
                            new Claim(JwtClaimTypes.GivenName, "Alice"),
                            new Claim(JwtClaimTypes.FamilyName, "Smith"),
                            new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
                            new Claim(JwtClaimTypes.Role, "Administrator"),
                            new Claim(JwtClaimTypes.Email, alice.Email),
                        }).Result;
                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }

                        Log.Debug("alice created");
                    }
                    else
                    {
                        Log.Debug("alice already exists");
                    }

                    var bob = userMgr.FindByNameAsync("bob").Result;
                    if (bob == null)
                    {
                        bob = new ApplicationUser
                        {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            EmailConfirmed = true
                        };
                        var result = userMgr.CreateAsync(bob, "Pass123$").Result;
                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }
                        else
                        {
                            if (roleMgr.RoleExistsAsync("User").Result)
                            {
                                var ii = userMgr.AddToRoleAsync(bob, "User").Result;
                            }
                        }

                        result = userMgr.AddClaimsAsync(bob, new Claim[] {
                            new Claim(JwtClaimTypes.Name, "Bob Smith"),
                            new Claim(JwtClaimTypes.GivenName, "Bob"),
                            new Claim(JwtClaimTypes.FamilyName, "Smith"),
                            new Claim(JwtClaimTypes.WebSite, "http://bob.com"),
                            new Claim(JwtClaimTypes.Email, bob.Email),
                            new Claim("location", "somewhere"),
                            new Claim(JwtClaimTypes.Role, "User")
                        }).Result;
                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }
                        Log.Debug("bob created");
                    }
                    else
                    {
                        Log.Debug("bob already exists");
                    }
                }
            }
        }
예제 #50
0
        protected override void Seed(CrowdTouring_Projeto.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. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

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

                manager.Create(role);
            }

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

                manager.Create(role);
            }

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

                manager.Create(role);
            }

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

                manager.Create(role);
            }

            context.Tags.AddOrUpdate(x => x.Id,
                                     new Tag()
            {
                Id = 1, NomeTag = "Restauração", cor = "blue"
            },
                                     new Tag()
            {
                Id = 2, NomeTag = "Hotelaria", cor = "green"
            },
                                     new Tag()
            {
                Id = 3, NomeTag = "Lazer", cor = "red"
            },
                                     new Tag()
            {
                Id = 4, NomeTag = "Trilhos", cor = "yellow"
            },
                                     new Tag()
            {
                Id = 5, NomeTag = "Transportes", cor = "grey"
            },
                                     new Tag()
            {
                Id = 6, NomeTag = "Praias", cor = "orange"
            },
                                     new Tag()
            {
                Id = 7, NomeTag = "Lembranças", cor = "Pink"
            },
                                     new Tag()
            {
                Id = 7, NomeTag = "Tecnologia", cor = "black"
            },
                                     new Tag()
            {
                Id = 7, NomeTag = "Outros", cor = "DarkGray"
            }
                                     );

            context.TiposAvaliacao.AddOrUpdate(x => x.TipoAvaliacaoId,
                                               new TipoAvaliacao()
            {
                TipoAvaliacaoId = 1, Descricao = "AceitarSolucoes"
            },
                                               new TipoAvaliacao()
            {
                TipoAvaliacaoId = 2, Descricao = "Votacao"
            },
                                               new TipoAvaliacao()
            {
                TipoAvaliacaoId = 3, Descricao = "Avaliacao"
            },
                                               new TipoAvaliacao()
            {
                TipoAvaliacaoId = 4, Descricao = "Fechado"
            }
                                               );
        }
예제 #51
0
        private async void CreateOrCheckAdminUser()
        {
            var userStore   = new UserStore <IdentityUser>();
            var userManager = new UserManager <IdentityUser>(userStore);
            var roleStore   = new RoleStore <IdentityRole>();
            var roleManager = new RoleManager <IdentityRole>(roleStore);

            if (!roleManager.RoleExists("Admin"))
            {
                var role = new IdentityRole();
                role.Name = Roles.Admin.ToString();
                roleManager.Create(role);
            }
            if (!roleManager.RoleExists("Manager"))
            {
                var role = new IdentityRole();
                role.Name = Roles.Manager.ToString();
                roleManager.Create(role);
            }
            if (!roleManager.RoleExists("SiteEngineer"))
            {
                var role = new IdentityRole();
                role.Name = Roles.SiteEngineer.ToString();
                roleManager.Create(role);
            }
            if (!roleManager.RoleExists("Accountant"))
            {
                var role = new IdentityRole();
                role.Name = Roles.Accountant.ToString();
                roleManager.Create(role);
            }

            var findAdmin          = userManager.FindByEmail("*****@*****.**");
            var findAccountant     = userManager.FindByEmail("*****@*****.**");
            var findManager        = userManager.FindByEmail("*****@*****.**");
            var findSiteEngineer   = userManager.FindByEmail("*****@*****.**");
            var findSiteEngineer2  = userManager.FindByEmail("*****@*****.**");
            var findManager2       = userManager.FindByEmail("*****@*****.**");
            var findSiteEngineer3  = userManager.FindByEmail("*****@*****.**");
            var findSiteEngineer4  = userManager.FindByEmail("*****@*****.**");
            var findManager3       = userManager.FindByEmail("*****@*****.**");
            var findSiteEngineer5  = userManager.FindByEmail("*****@*****.**");
            var findSiteEngineer6  = userManager.FindByEmail("*****@*****.**");
            var findManager4       = userManager.FindByEmail("*****@*****.**");
            var findSiteEngineer7  = userManager.FindByEmail("*****@*****.**");
            var findSiteEngineer8  = userManager.FindByEmail("*****@*****.**");
            var findManager5       = userManager.FindByEmail("*****@*****.**");
            var findSiteEngineer9  = userManager.FindByEmail("*****@*****.**");
            var findSiteEngineer10 = userManager.FindByEmail("*****@*****.**");
            var findManager6       = userManager.FindByEmail("*****@*****.**");
            var findSiteEngineer11 = userManager.FindByEmail("*****@*****.**");
            var findSiteEngineer12 = userManager.FindByEmail("*****@*****.**");

            if (Utils.getInstance.isNullOrEmpty(findAdmin) && Utils.getInstance.isNullOrEmpty(findManager) &&
                Utils.getInstance.isNullOrEmpty(findAccountant) && Utils.getInstance.isNullOrEmpty(findSiteEngineer) &&
                Utils.getInstance.isNullOrEmpty(findSiteEngineer2) && Utils.getInstance.isNullOrEmpty(findManager2) &&
                Utils.getInstance.isNullOrEmpty(findSiteEngineer3) && Utils.getInstance.isNullOrEmpty(findSiteEngineer4) &&
                Utils.getInstance.isNullOrEmpty(findManager3) && Utils.getInstance.isNullOrEmpty(findSiteEngineer5) &&
                Utils.getInstance.isNullOrEmpty(findSiteEngineer6) && Utils.getInstance.isNullOrEmpty(findManager4) &&
                Utils.getInstance.isNullOrEmpty(findSiteEngineer7) && Utils.getInstance.isNullOrEmpty(findSiteEngineer8) &&
                Utils.getInstance.isNullOrEmpty(findManager5) && Utils.getInstance.isNullOrEmpty(findSiteEngineer9) &&
                Utils.getInstance.isNullOrEmpty(findSiteEngineer10) && Utils.getInstance.isNullOrEmpty(findManager6) &&
                Utils.getInstance.isNullOrEmpty(findSiteEngineer11) && Utils.getInstance.isNullOrEmpty(findSiteEngineer12)
                )
            {
                var admin = new IdentityUser()
                {
                    UserName = "******", Email = "*****@*****.**"
                };
                IdentityResult resultAdmin = await userManager.CreateAsync(admin, "123456");

                if (resultAdmin.Succeeded)
                {
                    userManager.AddToRole(admin.Id, Roles.Admin.ToString());
                }
                var manager1 = new IdentityUser()
                {
                    UserName = "******", Email = "*****@*****.**"
                };
                IdentityResult resultManager1 = await userManager.CreateAsync(manager1, "123456");

                if (resultManager1.Succeeded)
                {
                    userManager.AddToRole(manager1.Id, Roles.Manager.ToString());

                    var factory = new DbConnectionFactory("CustomDatabase");
                    var context = new DbContext(factory);
                    var repos   = new UserRepository(context);
                    var user    = new Users();
                    user.UserId       = manager1.Id;
                    user.MaximumHours = 100;
                    user.MaximumCost  = 5000;
                    user.District     = (int)Districts.Urban_Indonesia;
                    repos.Insert(user);
                }
                var manager2 = new IdentityUser()
                {
                    UserName = "******", Email = "*****@*****.**"
                };
                IdentityResult resultManager2 = await userManager.CreateAsync(manager2, "123456");

                if (resultManager2.Succeeded)
                {
                    userManager.AddToRole(manager2.Id, Roles.Manager.ToString());

                    var factory = new DbConnectionFactory("CustomDatabase");
                    var context = new DbContext(factory);
                    var repos   = new UserRepository(context);
                    var user    = new Users();
                    user.UserId       = manager2.Id;
                    user.MaximumHours = 100;
                    user.MaximumCost  = 5000;
                    user.District     = (int)Districts.Rural_Indonesia;
                    repos.Insert(user);
                }
                var manager3 = new IdentityUser()
                {
                    UserName = "******", Email = "*****@*****.**"
                };
                IdentityResult resultManager3 = await userManager.CreateAsync(manager3, "123456");

                if (resultManager3.Succeeded)
                {
                    userManager.AddToRole(manager3.Id, Roles.Manager.ToString());

                    var factory = new DbConnectionFactory("CustomDatabase");
                    var context = new DbContext(factory);
                    var repos   = new UserRepository(context);
                    var user    = new Users();
                    user.UserId       = manager3.Id;
                    user.MaximumHours = 100;
                    user.MaximumCost  = 5000;
                    user.District     = (int)Districts.Urban_Papua_New_Guinea;
                    repos.Insert(user);
                }
                var manager4 = new IdentityUser()
                {
                    UserName = "******", Email = "*****@*****.**"
                };
                IdentityResult resultManager4 = await userManager.CreateAsync(manager4, "123456");

                if (resultManager4.Succeeded)
                {
                    userManager.AddToRole(manager4.Id, Roles.Manager.ToString());

                    var factory = new DbConnectionFactory("CustomDatabase");
                    var context = new DbContext(factory);
                    var repos   = new UserRepository(context);
                    var user    = new Users();
                    user.UserId       = manager4.Id;
                    user.MaximumHours = 100;
                    user.MaximumCost  = 5000;
                    user.District     = (int)Districts.Rural_Papua_New_Guinea;
                    repos.Insert(user);
                }
                var manager5 = new IdentityUser()
                {
                    UserName = "******", Email = "*****@*****.**"
                };
                IdentityResult resultManager5 = await userManager.CreateAsync(manager5, "123456");

                if (resultManager5.Succeeded)
                {
                    userManager.AddToRole(manager5.Id, Roles.Manager.ToString());

                    var factory = new DbConnectionFactory("CustomDatabase");
                    var context = new DbContext(factory);
                    var repos   = new UserRepository(context);
                    var user    = new Users();
                    user.UserId       = manager5.Id;
                    user.MaximumHours = 100;
                    user.MaximumCost  = 5000;
                    user.District     = (int)Districts.Sydney;
                    repos.Insert(user);
                }
                var manager6 = new IdentityUser()
                {
                    UserName = "******", Email = "*****@*****.**"
                };
                IdentityResult resultManager6 = await userManager.CreateAsync(manager6, "123456");

                if (resultManager6.Succeeded)
                {
                    userManager.AddToRole(manager6.Id, Roles.Manager.ToString());

                    var factory = new DbConnectionFactory("CustomDatabase");
                    var context = new DbContext(factory);
                    var repos   = new UserRepository(context);
                    var user    = new Users();
                    user.UserId       = manager6.Id;
                    user.MaximumHours = 100;
                    user.MaximumCost  = 5000;
                    user.District     = (int)Districts.Rural_New_South_Wales;
                    repos.Insert(user);
                }
                var accountant = new IdentityUser()
                {
                    UserName = "******", Email = "*****@*****.**"
                };
                IdentityResult resultAccountant = await userManager.CreateAsync(accountant, "123456");

                if (resultAccountant.Succeeded)
                {
                    userManager.AddToRole(accountant.Id, Roles.Accountant.ToString());
                }
                var siteEngineer1 = new IdentityUser()
                {
                    UserName = "******", Email = "*****@*****.**"
                };
                IdentityResult resultSiteEngineer1 = await userManager.CreateAsync(siteEngineer1, "123456");

                if (resultSiteEngineer1.Succeeded)
                {
                    userManager.AddToRole(siteEngineer1.Id, Roles.SiteEngineer.ToString());

                    var factory = new DbConnectionFactory("CustomDatabase");
                    var context = new DbContext(factory);
                    var repos   = new UserRepository(context);
                    var user    = new Users();
                    user.UserId       = siteEngineer1.Id;
                    user.MaximumHours = 50;
                    user.MaximumCost  = 2000;
                    user.District     = (int)Districts.Urban_Indonesia;
                    repos.Insert(user);
                }
                var siteEngineer2 = new IdentityUser()
                {
                    UserName = "******", Email = "*****@*****.**"
                };
                IdentityResult resultSiteEngineer2 = await userManager.CreateAsync(siteEngineer2, "123456");

                if (resultSiteEngineer2.Succeeded)
                {
                    userManager.AddToRole(siteEngineer2.Id, Roles.SiteEngineer.ToString());

                    var factory = new DbConnectionFactory("CustomDatabase");
                    var context = new DbContext(factory);
                    var repos2  = new UserRepository(context);
                    var user2   = new Users();
                    user2.UserId       = siteEngineer2.Id;
                    user2.MaximumHours = 25;
                    user2.MaximumCost  = 1000;
                    user2.District     = (int)Districts.Urban_Indonesia;
                    repos2.Insert(user2);
                }
            }
            var siteEngineer3 = new IdentityUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer3 = await userManager.CreateAsync(siteEngineer3, "123456");

            if (resultsiteEngineer3.Succeeded)
            {
                userManager.AddToRole(siteEngineer3.Id, Roles.SiteEngineer.ToString());

                var factory = new DbConnectionFactory("CustomDatabase");
                var context = new DbContext(factory);
                var repos   = new UserRepository(context);
                var user    = new Users();
                user.UserId       = siteEngineer3.Id;
                user.MaximumHours = 50;
                user.MaximumCost  = 2000;
                user.District     = (int)Districts.Rural_Indonesia;
                repos.Insert(user);
            }
            var siteEngineer4 = new IdentityUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer4 = await userManager.CreateAsync(siteEngineer4, "123456");

            if (resultsiteEngineer4.Succeeded)
            {
                userManager.AddToRole(siteEngineer4.Id, Roles.SiteEngineer.ToString());

                var factory = new DbConnectionFactory("CustomDatabase");
                var context = new DbContext(factory);
                var repos2  = new UserRepository(context);
                var user2   = new Users();
                user2.UserId       = siteEngineer4.Id;
                user2.MaximumHours = 25;
                user2.MaximumCost  = 1000;
                user2.District     = (int)Districts.Rural_Indonesia;
                repos2.Insert(user2);
            }
            var siteEngineer5 = new IdentityUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer5 = await userManager.CreateAsync(siteEngineer5, "123456");

            if (resultsiteEngineer5.Succeeded)
            {
                userManager.AddToRole(siteEngineer5.Id, Roles.SiteEngineer.ToString());

                var factory = new DbConnectionFactory("CustomDatabase");
                var context = new DbContext(factory);
                var repos   = new UserRepository(context);
                var user    = new Users();
                user.UserId       = siteEngineer5.Id;
                user.MaximumHours = 50;
                user.MaximumCost  = 2000;
                user.District     = (int)Districts.Urban_Papua_New_Guinea;
                repos.Insert(user);
            }
            var siteEngineer6 = new IdentityUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer6 = await userManager.CreateAsync(siteEngineer6, "123456");

            if (resultsiteEngineer6.Succeeded)
            {
                userManager.AddToRole(siteEngineer6.Id, Roles.SiteEngineer.ToString());

                var factory = new DbConnectionFactory("CustomDatabase");
                var context = new DbContext(factory);
                var repos2  = new UserRepository(context);
                var user2   = new Users();
                user2.UserId       = siteEngineer6.Id;
                user2.MaximumHours = 25;
                user2.MaximumCost  = 1000;
                user2.District     = (int)Districts.Urban_Papua_New_Guinea;
                repos2.Insert(user2);
            }
            var siteEngineer7 = new IdentityUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer7 = await userManager.CreateAsync(siteEngineer7, "123456");

            if (resultsiteEngineer7.Succeeded)
            {
                userManager.AddToRole(siteEngineer7.Id, Roles.SiteEngineer.ToString());

                var factory = new DbConnectionFactory("CustomDatabase");
                var context = new DbContext(factory);
                var repos   = new UserRepository(context);
                var user    = new Users();
                user.UserId       = siteEngineer7.Id;
                user.MaximumHours = 50;
                user.MaximumCost  = 2000;
                user.District     = (int)Districts.Rural_Papua_New_Guinea;
                repos.Insert(user);
            }
            var siteEngineer8 = new IdentityUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer8 = await userManager.CreateAsync(siteEngineer8, "123456");

            if (resultsiteEngineer8.Succeeded)
            {
                userManager.AddToRole(siteEngineer8.Id, Roles.SiteEngineer.ToString());

                var factory = new DbConnectionFactory("CustomDatabase");
                var context = new DbContext(factory);
                var repos2  = new UserRepository(context);
                var user2   = new Users();
                user2.UserId       = siteEngineer8.Id;
                user2.MaximumHours = 25;
                user2.MaximumCost  = 1000;
                user2.District     = (int)Districts.Rural_Papua_New_Guinea;
                repos2.Insert(user2);
            }
            var siteEngineer9 = new IdentityUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer9 = await userManager.CreateAsync(siteEngineer9, "123456");

            if (resultsiteEngineer9.Succeeded)
            {
                userManager.AddToRole(siteEngineer9.Id, Roles.SiteEngineer.ToString());

                var factory = new DbConnectionFactory("CustomDatabase");
                var context = new DbContext(factory);
                var repos   = new UserRepository(context);
                var user    = new Users();
                user.UserId       = siteEngineer9.Id;
                user.MaximumHours = 50;
                user.MaximumCost  = 2000;
                user.District     = (int)Districts.Sydney;
                repos.Insert(user);
            }
            var siteEngineer10 = new IdentityUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer10 = await userManager.CreateAsync(siteEngineer10, "123456");

            if (resultsiteEngineer10.Succeeded)
            {
                userManager.AddToRole(siteEngineer10.Id, Roles.SiteEngineer.ToString());

                var factory = new DbConnectionFactory("CustomDatabase");
                var context = new DbContext(factory);
                var repos2  = new UserRepository(context);
                var user2   = new Users();
                user2.UserId       = siteEngineer10.Id;
                user2.MaximumHours = 25;
                user2.MaximumCost  = 1000;
                user2.District     = (int)Districts.Sydney;
                repos2.Insert(user2);
            }
            var siteEngineer11 = new IdentityUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer11 = await userManager.CreateAsync(siteEngineer11, "123456");

            if (resultsiteEngineer11.Succeeded)
            {
                userManager.AddToRole(siteEngineer11.Id, Roles.SiteEngineer.ToString());

                var factory = new DbConnectionFactory("CustomDatabase");
                var context = new DbContext(factory);
                var repos   = new UserRepository(context);
                var user    = new Users();
                user.UserId       = siteEngineer11.Id;
                user.MaximumHours = 50;
                user.MaximumCost  = 2000;
                user.District     = (int)Districts.Rural_New_South_Wales;
                repos.Insert(user);
            }
            var siteEngineer12 = new IdentityUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer12 = await userManager.CreateAsync(siteEngineer12, "123456");

            if (resultsiteEngineer12.Succeeded)
            {
                userManager.AddToRole(siteEngineer12.Id, Roles.SiteEngineer.ToString());

                var factory = new DbConnectionFactory("CustomDatabase");
                var context = new DbContext(factory);
                var repos2  = new UserRepository(context);
                var user2   = new Users();
                user2.UserId       = siteEngineer12.Id;
                user2.MaximumHours = 25;
                user2.MaximumCost  = 1000;
                user2.District     = (int)Districts.Rural_New_South_Wales;
                repos2.Insert(user2);
            }
        }
예제 #52
0
 protected async System.Threading.Tasks.Task Load()
 {
     role = new IdentityRole();
 }
예제 #53
0
 public SelectUserViewModel(IdentityRole role)
 {
     this.Name = role.Name;
     this.Id   = role.Id;
 }
예제 #54
0
        private void createRolesandUsers()
        {
            ApplicationDbContext context = new ApplicationDbContext();
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

            if (!roleManager.RoleExists("Super Admin"))
            {
                // first we create Admin rool
                var role = new IdentityRole();
                role.Name = "Super Admin";
                roleManager.Create(role);
            }
            if (roleManager.RoleExists("Super Admin"))
            {
                var userName = userManager.FindByName("shsohel20");
                if (userName == null)
                {
                    var user = new ApplicationUser();
                    user.UserName = "******";
                    user.Email    = "*****@*****.**";
                    string userPWD = "Shs@12320";
                    var    chkUser = userManager.Create(user, userPWD);

                    //Add default User to Role Admin
                    if (chkUser.Succeeded)
                    {
                        var result1        = userManager.AddToRole(user.Id, "Super Admin");
                        var personalDetail = new PersonalDetail();
                        var education      = new Education();
                        var experience     = new Experience();
                        var address        = new Address();
                        var skill          = new Skill();
                        var training       = new Training();

                        personalDetail.UserName     = user.UserName;
                        personalDetail.Email        = user.Email;
                        personalDetail.UserId       = user.Id;
                        education.PersonalDetailID  = personalDetail.PersonalDetailID;
                        experience.PersonalDetailID = personalDetail.PersonalDetailID;
                        address.PersonalDetailID    = personalDetail.PersonalDetailID;
                        skill.PersonalDetailID      = personalDetail.PersonalDetailID;
                        training.PersonalDetailID   = personalDetail.PersonalDetailID;


                        context.PersonalDetails.Add(personalDetail);
                        context.Educations.Add(education);
                        context.Experiences.Add(experience);
                        context.Addresses.Add(address);
                        context.Skills.Add(skill);
                        context.Trainings.Add(training);
                        context.SaveChanges();
                    }
                }
            }
            // In Startup iam creating first Admin Role and creating a default Admin User
            if (!roleManager.RoleExists("Admin"))
            {
                // first we create Admin rool
                var role = new IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);
            }
            //Here we create a Admin super user who will maintain the website
            if (roleManager.RoleExists("Admin"))
            {
                var userName = userManager.FindByName("shsohel");
                if (userName == null)
                {
                    var user = new ApplicationUser();
                    user.UserName = "******";
                    user.Email    = "*****@*****.**";
                    string userPWD = "Shs@123";
                    var    chkUser = userManager.Create(user, userPWD);

                    //Add default User to Role Admin
                    if (chkUser.Succeeded)
                    {
                        var result1        = userManager.AddToRole(user.Id, "Admin");
                        var personalDetail = new PersonalDetail();
                        var education      = new Education();
                        var experience     = new Experience();
                        var address        = new Address();
                        var skill          = new Skill();
                        var training       = new Training();

                        personalDetail.UserName     = user.UserName;
                        personalDetail.Email        = user.Email;
                        personalDetail.UserId       = user.Id;
                        education.PersonalDetailID  = personalDetail.PersonalDetailID;
                        experience.PersonalDetailID = personalDetail.PersonalDetailID;
                        address.PersonalDetailID    = personalDetail.PersonalDetailID;
                        skill.PersonalDetailID      = personalDetail.PersonalDetailID;
                        training.PersonalDetailID   = personalDetail.PersonalDetailID;


                        context.PersonalDetails.Add(personalDetail);
                        context.Educations.Add(education);
                        context.Experiences.Add(experience);
                        context.Addresses.Add(address);
                        context.Skills.Add(skill);
                        context.Trainings.Add(training);
                        context.SaveChanges();
                    }
                }
            }
            // creating Creating Employee role
            if (!roleManager.RoleExists("Employer"))
            {
                var role = new IdentityRole();
                role.Name = "Employer";
                roleManager.Create(role);
            }
            if (!roleManager.RoleExists("Jobseeker"))
            {
                var role = new IdentityRole();
                role.Name = "Jobseeker";
                roleManager.Create(role);
            }
        }
예제 #55
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, FirstName = model.FirsName, LastName = model.LastName
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //Simon
                    //first User that will be generated will be a admin user!!!!
                    //this code should be deleted and users + roles created on startup
                    //of the application.
                    if (!await _roleManager.RoleExistsAsync("Administrator"))
                    {
                        var role = new IdentityRole("Administrator");

                        var res = await _roleManager.CreateAsync(role);

                        if (res.Succeeded)
                        {
                            await _userManager.AddToRoleAsync(user, "Administrator");

                            _logger.LogInformation("User created a new admin account with password.");

                            var _code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                            var _callbackUrl = Url.EmailConfirmationLink(user.Id, _code, Request.Scheme);
                            await _emailSender.SendEmailConfirmationAsync(model.Email, _callbackUrl);

                            await _signInManager.SignInAsync(user, isPersistent : false);

                            _logger.LogInformation("User created a new admin account with password.");
                            return(RedirectToLocal(returnUrl));
                        }
                    }

                    //normal login procedure for a normal user
                    if (!await _roleManager.RoleExistsAsync("User"))
                    {
                        var role = new IdentityRole("User");

                        var res = await _roleManager.CreateAsync(role);

                        if (res.Succeeded)
                        {
                            await _userManager.AddToRoleAsync(user, "User");

                            _logger.LogInformation("User created a new admin account with password.");

                            var _code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                            var _callbackUrl = Url.EmailConfirmationLink(user.Id, _code, Request.Scheme);
                            await _emailSender.SendEmailConfirmationAsync(model.Email, _callbackUrl);

                            await _signInManager.SignInAsync(user, isPersistent : false);

                            _logger.LogInformation("User created a new admin account with password.");
                            return(RedirectToLocal(returnUrl));
                        }
                    }

                    await _userManager.AddToRoleAsync(user, "User");

                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation("User created a new account with password.");
                    return(RedirectToLocal(returnUrl));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #56
0
        public ActionResult CreateRole()
        {
            var role = new IdentityRole();

            return(View(role));
        }
예제 #57
0
        public static IApplicationBuilder Seed(this IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                serviceScope.ServiceProvider.GetService <IntelliMoodDbContext>().Database.Migrate();

                var userManager = serviceScope.ServiceProvider.GetService <UserManager <User> >();
                var roleManager = serviceScope.ServiceProvider.GetService <RoleManager <IdentityRole> >();
                var db          = serviceScope.ServiceProvider.GetService <IntelliMoodDbContext>();

                Task
                .Run(async() =>
                {
                    if (!await roleManager.RoleExistsAsync("Admin"))
                    {
                        var admin = new User
                        {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            DiaryName      = "Admin",
                            PrimaryColor   = "#000000",
                            SecondaryColor = "#00ff7f"
                        };
                        await userManager.CreateAsync(admin, "test12");

                        var adminRole = new IdentityRole("Admin");
                        await roleManager.CreateAsync(adminRole);
                        await userManager.AddToRoleAsync(admin, "Admin");
                    }

                    if (!db.Recommendations.Any())
                    {
                        var recommendations = new List <Recommendation>();

                        recommendations.Add(new Recommendation()
                        {
                            Content = "Take a walk outside",
                            Type    = RecommendationTypes.Activity
                        });

                        recommendations.Add(new Recommendation()
                        {
                            Content = "Take a cold shower",
                            Type    = RecommendationTypes.Activity
                        });

                        recommendations.Add(new Recommendation()
                        {
                            Content = "WarCross",
                            Type    = RecommendationTypes.Book
                        });
                        recommendations.Add(new Recommendation()
                        {
                            Content = "Mr. Perfect",
                            Type    = RecommendationTypes.Book
                        });
                        recommendations.Add(new Recommendation()
                        {
                            Content = "50 shades of grey",
                            Type    = RecommendationTypes.Book
                        });

                        recommendations.Add(new Recommendation()
                        {
                            Content = "American pie",
                            Type    = RecommendationTypes.Movie
                        });
                        recommendations.Add(new Recommendation()
                        {
                            Content = "Despicable Me",
                            Type    = RecommendationTypes.Movie
                        });

                        recommendations.Add(new Recommendation()
                        {
                            Content = "Bach",
                            Type    = RecommendationTypes.Music
                        });
                        recommendations.Add(new Recommendation()
                        {
                            Content = "Vivaldi",
                            Type    = RecommendationTypes.Music
                        });
                        recommendations.Add(new Recommendation()
                        {
                            Content = "Vagner",
                            Type    = RecommendationTypes.Music
                        });
                        recommendations.Add(new Recommendation()
                        {
                            Content = "Mozzart",
                            Type    = RecommendationTypes.Music
                        });

                        recommendations.Add(new Recommendation()
                        {
                            Content = "Memes",
                            Type    = RecommendationTypes.Other
                        });

                        db.Recommendations.AddRange(recommendations);

                        await db.SaveChangesAsync();

                        var stamat = new User
                        {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            DiaryName      = "Artie",
                            PrimaryColor   = "#000000",
                            SecondaryColor = "#00ff7f"
                        };

                        var neti = new User
                        {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            DiaryName      = "Artie",
                            PrimaryColor   = "#000000",
                            SecondaryColor = "#00ff7f"
                        };

                        var kalin = new User
                        {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            DiaryName      = "Artie",
                            PrimaryColor   = "#000000",
                            SecondaryColor = "#00ff7f"
                        };

                        var kosta = new User
                        {
                            UserName       = "******",
                            Email          = "*****@*****.**",
                            DiaryName      = "Haralampi",
                            PrimaryColor   = "#000000",
                            SecondaryColor = "#00ff7f"
                        };


                        await userManager.CreateAsync(stamat, "test12");
                        await userManager.CreateAsync(neti, "test12");
                        await userManager.CreateAsync(kalin, "test12");
                        await userManager.CreateAsync(kosta, "test12");


                        var random = new Random();

                        foreach (var recommendation in db.Recommendations.ToList())
                        {
                            foreach (var user in db.Users.ToList())
                            {
                                var shouldAdd = random.Next(0, 10);
                                if (shouldAdd < 7)
                                {
                                    db.UserRecommendations.Add(new UserRecommendation()
                                    {
                                        UserId           = user.Id,
                                        RecommendationId = recommendation.Id,
                                        Mood             = "Bad",
                                        Rating           = random.Next(5) + 1
                                    });
                                }
                            }
                        }

                        var lovedByEverybody = new Recommendation()
                        {
                            Content = "Playing with animals",
                            Type    = RecommendationTypes.Other
                        };

                        db.Recommendations.Add(lovedByEverybody);
                        db.SaveChanges();

                        foreach (var user in db.Users.ToList())
                        {
                            db.UserRecommendations.Add(new UserRecommendation()
                            {
                                Mood             = "Sad",
                                Rating           = 5,
                                UserId           = user.Id,
                                RecommendationId = lovedByEverybody.Id
                            });
                        }

                        await db.SaveChangesAsync();
                    }
                })
                .Wait();
            }

            return(app);
        }
        protected override void Seed(ApplicationDbContext context)
        {
            //Users
            var roleStore   = new RoleStore <IdentityRole>(context);
            var roleManager = new RoleManager <IdentityRole>(roleStore);
            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new UserManager <ApplicationUser>(userStore);

            var role = roleManager.FindByName("Admin");

            if (role == null)
            {
                role = new IdentityRole("Admin");
                roleManager.Create(role);
            }

            var adminUser = userManager.FindByName("admin");

            if (adminUser == null)
            {
                var newUser = new ApplicationUser()
                {
                    UserName           = "******",
                    ScheduleAccessMode = ScheduleAccessMode.Edit
                };
                var result = userManager.Create(newUser, "111111");
                if (result.Succeeded)
                {
                    //userManager.SetLockoutEnabled(newUser.Id, false);
                    userManager.AddToRole(newUser.Id, "Admin");
                }
            }

            List <Group> groups = new List <Group>()
            {
                new Group()
                {
                    Title = "ПК-15-1", StudentsAmount = 33, Course = 1
                },
                new Group()
                {
                    Title = "ПК-15-2", StudentsAmount = 22, Course = 1
                },
                new Group()
                {
                    Title = "ПМ-15-1", StudentsAmount = 12, Course = 1
                },
                new Group()
                {
                    Title = "ПМ-15-2", StudentsAmount = 13, Course = 1
                },
                new Group()
                {
                    Title = "ПЗ-15-1", StudentsAmount = 24, Course = 1
                },
                new Group()
                {
                    Title = "ПЗ-15-2", StudentsAmount = 21, Course = 1
                },
                new Group()
                {
                    Title = "ПС-15-1", StudentsAmount = 13, Course = 1
                },
                new Group()
                {
                    Title = "ПС-15-2", StudentsAmount = 42, Course = 1
                },

                new Group()
                {
                    Title = "ПК-14-1", StudentsAmount = 31, Course = 2
                },
                new Group()
                {
                    Title = "ПК-14-2", StudentsAmount = 22, Course = 2
                },
                new Group()
                {
                    Title = "ПМ-14-1", StudentsAmount = 13, Course = 2
                },
                new Group()
                {
                    Title = "ПМ-14-2", StudentsAmount = 24, Course = 2
                },
                new Group()
                {
                    Title = "ПЗ-14-1", StudentsAmount = 21, Course = 2
                },
                new Group()
                {
                    Title = "ПЗ-14-2", StudentsAmount = 22, Course = 2
                },
                new Group()
                {
                    Title = "ПС-14-1", StudentsAmount = 13, Course = 2
                },
                new Group()
                {
                    Title = "ПС-14-2", StudentsAmount = 24, Course = 2
                },

                new Group()
                {
                    Title = "ПК-13-1", StudentsAmount = 20, Course = 3
                },
                new Group()
                {
                    Title = "ПК-13-2", StudentsAmount = 11, Course = 3
                },
                new Group()
                {
                    Title = "ПМ-13-1", StudentsAmount = 12, Course = 3
                },
                new Group()
                {
                    Title = "ПМ-13-2", StudentsAmount = 21, Course = 3
                },
                new Group()
                {
                    Title = "ПЗ-13-1", StudentsAmount = 14, Course = 3
                },
                new Group()
                {
                    Title = "ПЗ-13-2", StudentsAmount = 12, Course = 3
                },
                new Group()
                {
                    Title = "ПС-13-1", StudentsAmount = 15, Course = 3
                },
                new Group()
                {
                    Title = "ПС-13-2", StudentsAmount = 22, Course = 3
                },

                new Group()
                {
                    Title = "ПК-12-1", StudentsAmount = 18, Course = 4
                },
                new Group()
                {
                    Title = "ПК-12-2", StudentsAmount = 16, Course = 4
                },
                new Group()
                {
                    Title = "ПМ-12-1", StudentsAmount = 15, Course = 4
                },
                new Group()
                {
                    Title = "ПМ-12-2", StudentsAmount = 25, Course = 4
                },
                new Group()
                {
                    Title = "ПЗ-12-1", StudentsAmount = 21, Course = 4
                },
                new Group()
                {
                    Title = "ПЗ-12-2", StudentsAmount = 20, Course = 4
                },
                new Group()
                {
                    Title = "ПС-12-1", StudentsAmount = 16, Course = 4
                },
                new Group()
                {
                    Title = "ПС-12-2", StudentsAmount = 21, Course = 4
                },

                new Group()
                {
                    Title = "ПК-11м-1", StudentsAmount = 13, Course = 5
                },
                new Group()
                {
                    Title = "ПМ-11м-1", StudentsAmount = 10, Course = 5
                },
                new Group()
                {
                    Title = "ПЗ-11м-1", StudentsAmount = 8, Course = 5
                },
                new Group()
                {
                    Title = "ПС-11м-1", StudentsAmount = 6, Course = 5
                },
            };

            //groups.Add(new Group() {Title = "ПК-12-1"});

            foreach (var group in groups)
            {
                context.Groups.AddOrUpdate(i => i.Title, group);
            }
            context.SaveChanges();

            //Teachers
            List <Teacher> teachers = new List <Teacher>()
            {
                new Teacher()
                {
                    DateOfBirth = DateTime.Now,
                    FirstName   = "Ivan",
                    MiddleName  = "Olegovich",
                    LastName    = "Gromov",
                    Gender      = "male"
                },
                new Teacher()
                {
                    DateOfBirth = DateTime.Now,
                    FirstName   = "Vladimir",
                    MiddleName  = "Ivanovich",
                    LastName    = "Rakov",
                    Gender      = "male"
                },
                new Teacher()
                {
                    DateOfBirth = DateTime.Now,
                    FirstName   = "Elena",
                    MiddleName  = "Viktorovna",
                    LastName    = "Fomenko",
                    Gender      = "female"
                },
                new Teacher()
                {
                    DateOfBirth = DateTime.Now,
                    FirstName   = "Nikita",
                    MiddleName  = "Olegovich",
                    LastName    = "Zarev",
                    Gender      = "male"
                },
                new Teacher()
                {
                    DateOfBirth = DateTime.Now,
                    FirstName   = "Oleg",
                    MiddleName  = "Ivanovich",
                    LastName    = "Branev",
                    Gender      = "male"
                },
            };

            foreach (var item in teachers)
            {
                context.Teachers.AddOrUpdate(i => i.LastName, item);
            }
            context.SaveChanges();

            //Classrooms
            List <Classroom> classrooms = new List <Classroom>()
            {
                new Classroom()
                {
                    Capacity = 10, Type = ClassroomType.Lab, Number = "3/41"
                },
                new Classroom()
                {
                    Capacity = 10, Type = ClassroomType.Lab, Number = "3/42"
                },
                new Classroom()
                {
                    Capacity = 15, Type = ClassroomType.Lab, Number = "3/43"
                },
                new Classroom()
                {
                    Capacity = 15, Type = ClassroomType.Lab, Number = "3/44"
                },
                new Classroom()
                {
                    Capacity = 8, Type = ClassroomType.Lab, Number = "3/45"
                },
                new Classroom()
                {
                    Capacity = 8, Type = ClassroomType.Lab, Number = "3/46"
                },
                new Classroom()
                {
                    Capacity = 16, Type = ClassroomType.Lab, Number = "3/47"
                },
                new Classroom()
                {
                    Capacity = 16, Type = ClassroomType.Lab, Number = "3/48"
                },

                new Classroom()
                {
                    Capacity = 20, Type = ClassroomType.Prac, Number = "3/31"
                },
                new Classroom()
                {
                    Capacity = 20, Type = ClassroomType.Prac, Number = "3/32"
                },
                new Classroom()
                {
                    Capacity = 24, Type = ClassroomType.Prac, Number = "3/33"
                },
                new Classroom()
                {
                    Capacity = 28, Type = ClassroomType.Prac, Number = "3/34"
                },
                new Classroom()
                {
                    Capacity = 30, Type = ClassroomType.Prac, Number = "3/35"
                },
                new Classroom()
                {
                    Capacity = 30, Type = ClassroomType.Prac, Number = "3/36"
                },

                new Classroom()
                {
                    Capacity = 30, Type = ClassroomType.Lec, Number = "3/21"
                },
                new Classroom()
                {
                    Capacity = 35, Type = ClassroomType.Lec, Number = "3/22"
                },
                new Classroom()
                {
                    Capacity = 50, Type = ClassroomType.Lec, Number = "3/23"
                },
                new Classroom()
                {
                    Capacity = 60, Type = ClassroomType.Lec, Number = "3/24"
                },
                new Classroom()
                {
                    Capacity = 60, Type = ClassroomType.Lec, Number = "3/25"
                },
            };

            foreach (var item in classrooms)
            {
                context.Classrooms.AddOrUpdate(i => i.Number, item);
            }
            context.SaveChanges();

            //Classrooms
            List <Lesson> lessons = new List <Lesson>()
            {
                new Lesson()
                {
                    Title = "Programming"
                },
                new Lesson()
                {
                    Title = "OS"
                },
                new Lesson()
                {
                    Title = "Data protection"
                },
                new Lesson()
                {
                    Title = "Design of software systems"
                },
                new Lesson()
                {
                    Title = "Intelligent information systems"
                },
                new Lesson()
                {
                    Title = "Distributed information-analytical systems"
                },
                new Lesson()
                {
                    Title = "Differential equations"
                },
                new Lesson()
                {
                    Title = "Elements of chaotic dynamics"
                },
                new Lesson()
                {
                    Title = "Digital Image Processing"
                },
                new Lesson()
                {
                    Title = "Computer graphics"
                },
            };

            foreach (var item in lessons)
            {
                context.Lessons.AddOrUpdate(i => i.Title, item);
            }
            context.SaveChanges();

            //Form3
            List <Form3> form3s = new List <Form3>()
            {
                new Form3()
                {
                    TeacherId = teachers[0].Id, LessonId = lessons[0].Id, LessonType = LessonType.Lec, Hours = 10
                },
                new Form3()
                {
                    TeacherId = teachers[0].Id, LessonId = lessons[1].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[0].Id, LessonId = lessons[2].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[0].Id, LessonId = lessons[3].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[0].Id, LessonId = lessons[4].Id, LessonType = LessonType.Lec, Hours = 1
                },

                new Form3()
                {
                    TeacherId = teachers[1].Id, LessonId = lessons[0].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[1].Id, LessonId = lessons[1].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[1].Id, LessonId = lessons[2].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[1].Id, LessonId = lessons[3].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[1].Id, LessonId = lessons[4].Id, LessonType = LessonType.Lab, Hours = 1
                },

                new Form3()
                {
                    TeacherId = teachers[2].Id, LessonId = lessons[3].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[2].Id, LessonId = lessons[3].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[2].Id, LessonId = lessons[3].Id, LessonType = LessonType.Prac, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[2].Id, LessonId = lessons[4].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[2].Id, LessonId = lessons[4].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[2].Id, LessonId = lessons[4].Id, LessonType = LessonType.Prac, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[2].Id, LessonId = lessons[5].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[2].Id, LessonId = lessons[5].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[2].Id, LessonId = lessons[5].Id, LessonType = LessonType.Prac, Hours = 1
                },

                new Form3()
                {
                    TeacherId = teachers[3].Id, LessonId = lessons[5].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[3].Id, LessonId = lessons[5].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[3].Id, LessonId = lessons[6].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[3].Id, LessonId = lessons[6].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[3].Id, LessonId = lessons[7].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[3].Id, LessonId = lessons[7].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[3].Id, LessonId = lessons[8].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[3].Id, LessonId = lessons[8].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[3].Id, LessonId = lessons[9].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[3].Id, LessonId = lessons[9].Id, LessonType = LessonType.Lab, Hours = 1
                },

                new Form3()
                {
                    TeacherId = teachers[4].Id, LessonId = lessons[8].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[4].Id, LessonId = lessons[8].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[4].Id, LessonId = lessons[8].Id, LessonType = LessonType.Prac, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[4].Id, LessonId = lessons[9].Id, LessonType = LessonType.Lec, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[4].Id, LessonId = lessons[9].Id, LessonType = LessonType.Lab, Hours = 1
                },
                new Form3()
                {
                    TeacherId = teachers[4].Id, LessonId = lessons[9].Id, LessonType = LessonType.Prac, Hours = 1
                },
            };

            foreach (var item in form3s)
            {
                context.Form3s.AddOrUpdate(item);
            }
            context.SaveChanges();

//            //GroupWorkload
//            List<GroupWorkload> groupWorkloads = new List<GroupWorkload>()
//            {
//                new GroupWorkload()
//                {
//                    GroupId = ,
//                    LessonId = ,
//                    Hours = 5,
//                    LessonType = "lection"
//                },
//            };
//            foreach (var item in groupWorkloads)
//            {
//                //context.GroupsWorkload.AddOrUpdate(i => i.Title, item);
            //   context.GroupsWorkload.AddOrUpdate(item);
//            }
//            context.SaveChanges();

            //Semester
            List <Semester> semesters = new List <Semester>()
            {
                new Semester()
                {
                    StartsOn = DateTime.Parse("2016-02-01"), EndsOn = DateTime.Parse("2016-05-01")
                },
            };

            foreach (var item in semesters)
            {
                context.Semesters.AddOrUpdate(i => i.StartsOn, item);
            }
            context.SaveChanges();

            //Schedule
            List <ScheduleItem> schedules = new List <ScheduleItem>()
            {
                new ScheduleItem()
                {
                    LessonId        = lessons[0].Id,
                    TeacherId       = teachers[0].Id,
                    ClassroomId     = classrooms[0].Id,
                    SemesterId      = semesters[0].Id,
                    LessonType      = LessonType.Lec,
                    DayOfWeek       = "Monday",
                    LessonNumber    = 1,
                    GroupId         = groups[0].Id,
                    LessonFrequency = LessonFrequency.Constant
                },
                new ScheduleItem()
                {
                    LessonId        = lessons[1].Id,
                    TeacherId       = teachers[1].Id,
                    ClassroomId     = classrooms[3].Id,
                    SemesterId      = semesters[0].Id,
                    LessonType      = LessonType.Lec,
                    DayOfWeek       = "Monday",
                    LessonNumber    = 2,
                    GroupId         = groups[0].Id,
                    LessonFrequency = LessonFrequency.Nominator
                },
                new ScheduleItem()
                {
                    LessonId        = lessons[2].Id,
                    TeacherId       = teachers[2].Id,
                    ClassroomId     = classrooms[2].Id,
                    SemesterId      = semesters[0].Id,
                    LessonType      = LessonType.Lec,
                    DayOfWeek       = "Monday",
                    LessonNumber    = 3,
                    GroupId         = groups[0].Id,
                    LessonFrequency = LessonFrequency.Denominator
                },
                new ScheduleItem()
                {
                    LessonId        = lessons[3].Id,
                    TeacherId       = teachers[3].Id,
                    ClassroomId     = classrooms[3].Id,
                    SemesterId      = semesters[0].Id,
                    LessonType      = LessonType.Lec,
                    DayOfWeek       = "Monday",
                    LessonNumber    = 4,
                    GroupId         = groups[0].Id,
                    LessonFrequency = LessonFrequency.Denominator
                },
                new ScheduleItem()
                {
                    LessonId        = lessons[4].Id,
                    TeacherId       = teachers[4].Id,
                    ClassroomId     = classrooms[3].Id,
                    SemesterId      = semesters[0].Id,
                    LessonType      = LessonType.Lec,
                    DayOfWeek       = "Monday",
                    LessonNumber    = 5,
                    GroupId         = groups[0].Id,
                    LessonFrequency = LessonFrequency.Constant
                },

                //тест макс занятий преподавателя
                new ScheduleItem()
                {
                    LessonId        = lessons[0].Id,
                    TeacherId       = teachers[0].Id,
                    ClassroomId     = classrooms[0].Id,
                    SemesterId      = semesters[0].Id,
                    LessonType      = LessonType.Lec,
                    DayOfWeek       = "Monday",
                    LessonNumber    = 1,
                    GroupId         = groups[1].Id,
                    LessonFrequency = LessonFrequency.Constant
                },
                new ScheduleItem()
                {
                    LessonId        = lessons[0].Id,
                    TeacherId       = teachers[0].Id,
                    ClassroomId     = classrooms[0].Id,
                    SemesterId      = semesters[0].Id,
                    LessonType      = LessonType.Lec,
                    DayOfWeek       = "Monday",
                    LessonNumber    = 2,
                    GroupId         = groups[1].Id,
                    LessonFrequency = LessonFrequency.Constant
                },
                new ScheduleItem()
                {
                    LessonId        = lessons[0].Id,
                    TeacherId       = teachers[0].Id,
                    ClassroomId     = classrooms[0].Id,
                    SemesterId      = semesters[0].Id,
                    LessonType      = LessonType.Lec,
                    DayOfWeek       = "Monday",
                    LessonNumber    = 3,
                    GroupId         = groups[1].Id,
                    LessonFrequency = LessonFrequency.Constant
                },
            };

            foreach (var item in schedules)
            {
                //context.ScheduleItems.AddOrUpdate(item);
                context.ScheduleItems.Add(item);
            }
            context.SaveChanges();


            //Restrictions
            List <Restriction> restrictions = new List <Restriction>()
            {
                new Restriction()
                {
                    Name        = "MaxLessonsPerDayForTeachers",
                    Type        = RestrictionType.Integer,
                    Value       = "3",
                    Description = "Max Lessons Per Day For Teachers",
                },
                new Restriction()
                {
                    Name        = "MaxLessonsPerDayForStudents",
                    Type        = RestrictionType.Integer,
                    Value       = "4",
                    Description = "Max Lessons Per Day For Teachers",
                },
                new Restriction()
                {
                    Name        = "SelfStudyDaysAmount",
                    Type        = RestrictionType.Integer,
                    Value       = "1",
                    Description = "",
                },
                new Restriction()
                {
                    Name        = "SelfStudyDaysCourses",
                    Type        = RestrictionType.List,
                    Value       = "4,5",
                    Description = "",
                },
            };

            foreach (var item in restrictions)
            {
                context.Restrictions.AddOrUpdate(i => i.Name, item);
            }
            context.SaveChanges();

            base.Seed(context);
        }
예제 #59
0
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity <ApplicationUser>().HasOne(p => p.Employee).WithOne(i => i.ApplicationUser).HasForeignKey <Employee>(e => e.UserForeignKey);
            builder.Entity <AnswerSection>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <Answer>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <AnswerDetail>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <City>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <Employee>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <Exam>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <Section>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <ExamEmployee>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <ExamQuestion>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <ExamSchedule>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <ExamSection>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <Gender>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <MaritalStatus>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <Question>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <QuestionDetail>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <QuestionType>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            builder.Entity <Religion>().Property(m => m.CreatedDate).HasDefaultValueSql("NOW()").ValueGeneratedOnAdd();
            //builder.Entity<City>().ToTable("Cities", "coba");

            #region RoleSeed
            var roleAdmin = new IdentityRole
            {
                Id               = "32ff273e-e327-4f0b-b08e-a2e02b0880d6",
                Name             = "Admin",
                NormalizedName   = "Admin",
                ConcurrencyStamp = "c6c609bd-85da-4629-9c56-f23c489830d2"
            };
            var rolePeserta = new IdentityRole
            {
                Id               = "04e83eaf-298f-4be6-9f05-2956b2030e5e",
                Name             = "Peserta",
                NormalizedName   = "Peserta",
                ConcurrencyStamp = "5402d890-3359-4b8f-a144-9d2afee67e1d"
            };
            builder.Entity <IdentityRole>().HasData(roleAdmin, rolePeserta);
            #endregion

            #region UserSeed
            var userAdmin = new ApplicationUser
            {
                Id                   = "f91a6f48-4c5b-4750-8341-bbb4d6905c74",
                Email                = "*****@*****.**",
                NormalizedEmail      = "*****@*****.**",
                UserName             = "******",
                NormalizedUserName   = "******",
                SecurityStamp        = "7a1e8e47-50f4-4922-a855-7001a615fb5e",
                PasswordHash         = "AQAAAAEAACcQAAAAEEp1sap4dxD2mtlMuEPd5CIN2p1lcaKGjOejHk2GjLl+BwkmCW38AtHU5fhBkmlOOA==",
                ConcurrencyStamp     = "233e5870-bfa6-4ba4-b3bd-73cf85c5d173",
                PhoneNumberConfirmed = true,
                EmailConfirmed       = true
            };
            //userAdmin.PasswordHash = new PasswordHasher<ApplicationUser>().HashPassword(userAdmin, "123qwe");
            var userPeserta = new ApplicationUser
            {
                Id                   = "77e285fb-43e8-4846-b763-9fcc0138ea99",
                Email                = "*****@*****.**",
                NormalizedEmail      = "*****@*****.**",
                UserName             = "******",
                NormalizedUserName   = "******",
                SecurityStamp        = "80b9327b-15db-49c9-86fa-1e3f21b74bb7",
                PasswordHash         = "AQAAAAEAACcQAAAAEMiQscjx4+VAFyt6lKUPW2AkZ6mLOtJcnTST6KOYclS3VFLwMFKdD61UA2S9iVlYig==",
                ConcurrencyStamp     = "93182e87-c18a-4fc7-8ac7-63100c9e803e",
                PhoneNumberConfirmed = true,
                EmailConfirmed       = true
            };
            //userPeserta.PasswordHash = new PasswordHasher<ApplicationUser>().HashPassword(userPeserta, "123qwe");
            var userPeserta2 = new ApplicationUser
            {
                Id                   = "02840db7-b582-454f-a83b-802b68cd33f0",
                Email                = "*****@*****.**",
                NormalizedEmail      = "*****@*****.**",
                UserName             = "******",
                NormalizedUserName   = "******",
                SecurityStamp        = "8067b3a3-a100-43a5-ae6a-0e294f817f9e",
                PasswordHash         = "AQAAAAEAACcQAAAAEMiQscjx4+VAFyt6lKUPW2AkZ6mLOtJcnTST6KOYclS3VFLwMFKdD61UA2S9iVlYig==",
                ConcurrencyStamp     = "216c4a56-0c6d-4908-87d4-7388153f4926",
                PhoneNumberConfirmed = true,
                EmailConfirmed       = true
            };
            builder.Entity <ApplicationUser>().HasData(userAdmin, userPeserta, userPeserta2);
            #endregion

            #region UserRoleSeed
            builder.Entity <IdentityUserRole <string> >().HasData(
                new IdentityUserRole <string>
            {
                UserId = userAdmin.Id,
                RoleId = roleAdmin.Id
            },
                new IdentityUserRole <string>
            {
                UserId = userPeserta.Id,
                RoleId = rolePeserta.Id
            },
                new IdentityUserRole <string>
            {
                UserId = userPeserta2.Id,
                RoleId = rolePeserta.Id
            }
                );
            #endregion

            #region GenderSeed
            builder.Entity <Gender>().HasData(
                new Gender {
                Id = 1, CreatedId = userAdmin.Id, Code = "L", Name = "Laki-laki", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new Gender {
                Id = 2, CreatedId = userAdmin.Id, Code = "P", Name = "Perempuan", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            }
                );
            #endregion

            #region ReligionSeed
            builder.Entity <Religion>().HasData(
                new Religion {
                Id = 1, CreatedId = userAdmin.Id, Code = "ISL", Name = "Islam", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new Religion {
                Id = 2, CreatedId = userAdmin.Id, Code = "KTP", Name = "Kristen Protestan", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new Religion {
                Id = 3, CreatedId = userAdmin.Id, Code = "KTK", Name = "Kristen Katolik", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new Religion {
                Id = 4, CreatedId = userAdmin.Id, Code = "HIN", Name = "Hindu", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new Religion {
                Id = 5, CreatedId = userAdmin.Id, Code = "BUD", Name = "Buddha", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new Religion {
                Id = 6, CreatedId = userAdmin.Id, Code = "KHO", Name = "Khonghucu", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            }
                );
            #endregion

            #region MaritalStatusSeed
            builder.Entity <MaritalStatus>().HasData(
                new MaritalStatus {
                Id = 1, CreatedId = userAdmin.Id, Code = "BK", Name = "Belum Kawin", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new MaritalStatus {
                Id = 2, CreatedId = userAdmin.Id, Code = "K", Name = "Kawin", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            }
                );
            #endregion

            #region CitySeed
            builder.Entity <City>().HasData(
                new City {
                Id = 1, CreatedId = userAdmin.Id, Code = "SUB", Name = "Surabaya", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new City {
                Id = 2, CreatedId = userAdmin.Id, Code = "CGK", Name = "Jakarta", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            }
                );
            #endregion

            #region EmployeeSeed
            builder.Entity <Employee>().HasData(
                new Employee {
                Id = 1, UserForeignKey = userPeserta.Id, GenderId = 2, ReligionId = 1, MaritalStatusId = 1, CityId = 1, CreatedId = userAdmin.Id, IdentityNumber = 1234567890, Name = "Adinda Namira", BirthDate = new DateTime(1990, 4, 28), BirthDatePlace = "Surabaya", Address = "Jl Surabaya No 1", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new Employee {
                Id = 2, UserForeignKey = userPeserta2.Id, GenderId = 2, ReligionId = 1, MaritalStatusId = 1, CityId = 1, CreatedId = userAdmin.Id, IdentityNumber = 9999999999, Name = "Testing Dua", BirthDate = new DateTime(1991, 4, 28), BirthDatePlace = "Surabaya", Address = "Jl Surabaya No 1", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            }
                );
            #endregion

            #region QuestionTypeSeed
            builder.Entity <QuestionType>().HasData(
                new QuestionType {
                Id = 1, CreatedId = userAdmin.Id, Name = "Multiple Choice", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionType {
                Id = 2, CreatedId = userAdmin.Id, Name = "Multiple Answer", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionType {
                Id = 3, CreatedId = userAdmin.Id, Name = "Essay", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            }
                );
            #endregion

            #region QuestionSeed
            builder.Entity <Question>().HasData(
                new Question {
                Id = 1, QuestionTypeId = 1, CreatedId = userAdmin.Id, Item = "1, 3, 2, 6, 5, 15, 14, ....", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new Question {
                Id = 2, QuestionTypeId = 1, CreatedId = userAdmin.Id, Item = "100, 95, ..., 91, 92, 87, 88, 83.", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new Question {
                Id = 3, QuestionTypeId = 1, CreatedId = userAdmin.Id, Item = "INSOMNIA = ...", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new Question {
                Id = 4, QuestionTypeId = 1, CreatedId = userAdmin.Id, Item = "BONGSOR >< ...", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            }
                );
            #endregion

            #region QuestionDetailSeed
            builder.Entity <QuestionDetail>().HasData(
                new QuestionDetail {
                Id = 1, Item = "24", IsTrue = false, QuestionId = 1, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 2, Item = "28", IsTrue = false, QuestionId = 1, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 3, Item = "32", IsTrue = false, QuestionId = 1, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 4, Item = "42", IsTrue = true, QuestionId = 1, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 5, Item = "52", IsTrue = false, QuestionId = 1, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 6, Item = "90", IsTrue = false, QuestionId = 2, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 7, Item = "92", IsTrue = false, QuestionId = 2, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 8, Item = "94", IsTrue = false, QuestionId = 2, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 9, Item = "96", IsTrue = true, QuestionId = 2, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 10, Item = "97", IsTrue = false, QuestionId = 2, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 11, Item = "Cemas", IsTrue = false, QuestionId = 3, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 12, Item = "Sedih", IsTrue = false, QuestionId = 3, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 13, Item = "Tidak bisa tidur", IsTrue = true, QuestionId = 3, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 14, Item = "Kenyataanya", IsTrue = false, QuestionId = 3, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 15, Item = "Menumpuk", IsTrue = false, QuestionId = 4, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 16, Item = "Kerdil", IsTrue = true, QuestionId = 4, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 17, Item = "Macet", IsTrue = false, QuestionId = 4, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new QuestionDetail {
                Id = 18, Item = "Susut", IsTrue = false, QuestionId = 4, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            }
                );
            #endregion

            #region ExamSeed
            builder.Entity <Exam>().HasData(
                new Exam {
                Id = 1, CreatedId = userAdmin.Id, Name = "Rekrutmen Grade 6A", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new Exam {
                Id = 2, CreatedId = userAdmin.Id, Name = "Rekrutmen Grade 7A", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            }
                );
            #endregion

            #region SectionSeed
            builder.Entity <Section>().HasData(
                new Section {
                Id = 1, CreatedId = userAdmin.Id, Name = "Tes Potensi Akademik", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new Section {
                Id = 2, CreatedId = userAdmin.Id, Name = "Tes Psikotes", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            }
                );
            #endregion

            #region ExamSectionSeed
            builder.Entity <ExamSection>().HasData(
                new ExamSection {
                Id = 1, ExamId = 1, SectionId = 1, CreatedId = userAdmin.Id, Name = "Tes Potensi Akademik 6A", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new ExamSection {
                Id = 2, ExamId = 1, SectionId = 2, CreatedId = userAdmin.Id, Name = "Tes Psikotes 6A", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new ExamSection {
                Id = 3, ExamId = 2, SectionId = 1, CreatedId = userAdmin.Id, Name = "Tes Potensi Akademik 7A", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new ExamSection {
                Id = 4, ExamId = 2, SectionId = 2, CreatedId = userAdmin.Id, Name = "Tes Psikotes 7A", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            }
                );
            #endregion

            #region ExamQuestionSeed
            builder.Entity <ExamQuestion>().HasData(
                new ExamQuestion {
                Id = 1, ExamSectionId = 1, QuestionId = 1, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new ExamQuestion {
                Id = 2, ExamSectionId = 1, QuestionId = 2, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new ExamQuestion {
                Id = 3, ExamSectionId = 2, QuestionId = 3, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new ExamQuestion {
                Id = 4, ExamSectionId = 2, QuestionId = 4, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new ExamQuestion {
                Id = 5, ExamSectionId = 3, QuestionId = 1, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new ExamQuestion {
                Id = 6, ExamSectionId = 3, QuestionId = 2, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new ExamQuestion {
                Id = 7, ExamSectionId = 4, QuestionId = 3, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new ExamQuestion {
                Id = 8, ExamSectionId = 4, QuestionId = 4, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            }
                );
            #endregion

            #region ExamScheduleSeed
            builder.Entity <ExamSchedule>().HasData(
                new ExamSchedule {
                Id = 1, CreatedId = userAdmin.Id, ExamId = 1, DateExam = new DateTime(2019, 10, 11), Notes = "", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            },
                new ExamSchedule {
                Id = 2, CreatedId = userAdmin.Id, ExamId = 2, DateExam = new DateTime(2019, 10, 12), Notes = "", CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local), Duration = new TimeSpan()
            }
                );
            #endregion

            #region ExamEmployeeSeed
            builder.Entity <ExamEmployee>().HasData(
                new ExamEmployee {
                Id = 1, ExamScheduleId = 1, EmployeeId = 1, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new ExamEmployee {
                Id = 2, ExamScheduleId = 1, EmployeeId = 2, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            }
                );
            #endregion

            #region AnswerSeed
            builder.Entity <Answer>().HasData(
                new Answer {
                Id = 1, ExamEmployeeId = 1, ExamSectionId = 1, QuestionId = 1, Item = "1, 3, 2, 6, 5, 15, 14, ....", CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new Answer {
                Id = 2, ExamEmployeeId = 1, ExamSectionId = 1, QuestionId = 2, Item = "100, 95, ..., 91, 92, 87, 88, 83.", CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new Answer {
                Id = 3, ExamEmployeeId = 1, ExamSectionId = 2, QuestionId = 3, Item = "INSOMNIA = ...", CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new Answer {
                Id = 4, ExamEmployeeId = 1, ExamSectionId = 2, QuestionId = 4, Item = "BONGSOR >< ...", CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            }
                );
            #endregion

            #region AnswerDetailSeed
            builder.Entity <AnswerDetail>().HasData(
                new AnswerDetail {
                Id = 1, AnswerId = 1, QuestionDetailId = 4, Item = "42", IsTrue = true, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new AnswerDetail {
                Id = 2, AnswerId = 2, QuestionDetailId = 9, Item = "96", IsTrue = true, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new AnswerDetail {
                Id = 3, AnswerId = 3, QuestionDetailId = 13, Item = "Tidak bisa tidur", IsTrue = true, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            },
                new AnswerDetail {
                Id = 4, AnswerId = 4, QuestionDetailId = 16, Item = "Kerdil", IsTrue = true, CreatedId = userAdmin.Id, CreatedDate = new DateTime(2019, 10, 14, 18, 2, 41, 714, DateTimeKind.Local)
            }
                );
            #endregion
        }
예제 #60
-1
        public async Task<IdentityResult> RegisterUser(UserModel userModel, string roleName)
        {
            IdentityUser user = new IdentityUser
            {
                UserName = userModel.UserName,
                Email = userModel.UserName
            };

            var result = await _userManager.CreateAsync(user, userModel.Password);

            if (result == IdentityResult.Success)
            {
                var role = await _roleManager.FindByNameAsync(roleName);
                if (role == null)
                {
                    role = new IdentityRole(roleName);
                    var roleresult = await _roleManager.CreateAsync(role);
                }

                var userFromDb = await _userManager.FindByNameAsync(user.UserName);

                if (userFromDb != null)
                {
                    await _userManager.AddToRoleAsync(userFromDb.Id, roleName);
                }
            }

            return result;
        }