public IIdentityManagerService Create()
        {
            var db = new IdentityDbContext<IdentityUser>(_connString);
            var userstore = new UserStore<IdentityUser>(db);
            var usermgr = new Microsoft.AspNet.Identity.UserManager<IdentityUser>(userstore);
            usermgr.PasswordValidator = new Microsoft.AspNet.Identity.PasswordValidator
            {
                RequiredLength = 3
            };
            var rolestore = new RoleStore<IdentityRole>(db);
            var rolemgr = new Microsoft.AspNet.Identity.RoleManager<IdentityRole>(rolestore);

            var svc = new Thinktecture.IdentityManager.AspNetIdentity.AspNetIdentityManagerService<IdentityUser, string, IdentityRole, string>(usermgr, rolemgr);

            var dispose = new DisposableIdentityManagerService(svc, db);
            return dispose;

            //var db = new CustomDbContext(_connString);
            //var userstore = new CustomUserStore(db);
            //var usermgr = new CustomUserManager(userstore);
            //var rolestore = new CustomRoleStore(db);
            //var rolemgr = new CustomRoleManager(rolestore);

            //var svc = new Thinktecture.IdentityManager.AspNetIdentity.AspNetIdentityManagerService<CustomUser, int, CustomRole, int>(usermgr, rolemgr);
            //var dispose = new DisposableIdentityManagerService(svc, db);
            //return dispose;
        }
示例#2
0
        internal void AddUserAndRole()
        {
            ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

            RoleStore<IdentityRole> roleStore = new RoleStore<IdentityRole>(context);
            RoleManager<IdentityRole> roleMgr = new RoleManager<IdentityRole>(roleStore);

            //create admin role
            if(!roleMgr.RoleExists("admin")) {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "admin" });
            }

            //create master user
            UserManager<ApplicationUser> userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            ApplicationUser appUser = new ApplicationUser {
                UserName = "******",
                Email = "*****@*****.**"
            };
            IdUserResult = userMgr.Create(appUser, "Baseball1!");

            //add to admin role
            if(!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "admin")) {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "admin");
            }
        }
        public ActionResult Menu()
        {
            ApplicationDbContext userscontext = new ApplicationDbContext();
            var userStore = new UserStore<ApplicationUser>(userscontext);
            var userManager = new UserManager<ApplicationUser>(userStore);

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

            if (User.Identity.IsAuthenticated)
            {

                if (userManager.IsInRole(this.User.Identity.GetUserId(), "Admin"))
                {
                    return PartialView("_AdminMenuView");
                }
                else if (userManager.IsInRole(this.User.Identity.GetUserId(), "Principal"))
                {
                    return PartialView("_PrincipalenuView");
                }
                else
                {
                    return PartialView("_Student");
                }
            }

            return PartialView("_Empty");
        }
        internal void AddUserAndRole()
        {
            Models.ApplicationDbContext context = new Models.ApplicationDbContext();

            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

            var roleStore = new RoleStore<IdentityRole>(context);

            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            if (!roleMgr.RoleExists("administrator"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "administrator" });
            }

            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var appUser = new ApplicationUser
            {
                UserName = "******",
            };
            IdUserResult = userMgr.Create(appUser, "1qaz2wsxE");
            var user = userMgr.FindByName("administrator");
            if (!userMgr.IsInRole(user.Id, "administrator"))
            {
                //userMgr.RemoveFromRoles(user.Id, "read", "edit");
                IdUserResult = userMgr.AddToRole(userMgr.FindByName("administrator").Id, "administrator");
            }
        }
示例#5
0
        internal void AddUserAndRole()
        {
            ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleMgr = new RoleManager<IdentityRole>(roleStore);
            if (!roleMgr.RoleExists("Admin"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "Admin" });
            }

            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var appUser = new ApplicationUser
            {

                Email = "*****@*****.**"
            };
            IdUserResult = userMgr.Create(appUser, "adminA123...");

            if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "Admin"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "canEdit");
            }
        }
示例#6
0
        internal void AddUserAndRole()
        {
            // access the application context and create result variables.
            Models.ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

            // create roleStore object that can only contain IdentityRole objects by using the ApplicationDbContext object.
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            // create admin role if it doesn't already exist
            if (!roleMgr.RoleExists("admin"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "admin" });
            }

            // create a UserManager object based on the UserStore object and the ApplicationDbContext object.
            // defines admin email account
            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var appUser = new ApplicationUser
            {
                UserName = "******",
                Email = "*****@*****.**"
            };
            IdUserResult = userMgr.Create(appUser, "Pa$$word1");

            // If the new admin user was successfully created, add the new user to the "admin" role.
            if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "admin"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "admin");
            }
        }
        public ActionResult Create(ClientViewModel client)
        {
            if (!ModelState.IsValid) return View();

            //Register user and SingIn
            var accountController = new AccountController {ControllerContext = this.ControllerContext};
            var user = accountController.RegisterAccount(new RegisterViewModel() { Email = client.Email, Password = client.Password });
            accountController.SignInManager.SignIn(user, isPersistent: false, rememberBrowser: false);

            //Add user to client role
            var userStore = new UserStore<ApplicationUser>(_context);
            var userManager = new UserManager<ApplicationUser>(userStore);
            var roleStore = new RoleStore<IdentityRole>(_context);
            var roleManager = new RoleManager<IdentityRole>(roleStore);
            
            if (!roleManager.RoleExists("Client")) 
                roleManager.Create(new IdentityRole("Client"));
            
            userManager.AddToRole(user.Id, "Client");

            //Register client
            if (string.IsNullOrWhiteSpace(user.Id)) return View();
            _context.Clients.Add(new Client()
            {
                Id = user.Id,
                Name = client.Name,
                Age = client.Age
            });
            _context.SaveChanges();

            return RedirectToAction("Index", "Home");
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     var roles = new RoleStore<IdentityRole>();
     var rolesManager = new RoleManager<IdentityRole>(roles);
     ddlRol.DataSource = rolesManager.Roles.ToList();
     ddlRol.DataBind();
 }
        public IQueryable<IdentityRole> GetRoles()
        {
            var roleStore = new RoleStore<IdentityRole>();
            var roles = new RoleManager<IdentityRole>(roleStore);

            return roles.Roles;
        }
示例#10
0
        internal void AddUserAndRole()
        {
            Models.ApplicationDbContext db = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

            var roleStore = new RoleStore<IdentityRole>(db);

            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            if (!roleMgr.RoleExists("canEdit"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "canEdit" });
            }

            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            var appUser = new ApplicationUser
            {
                UserName = "******",
                Email = "*****@*****.**"
            };
            IdUserResult = userMgr.Create(appUser, "NhatSinh123*");

            if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "canEdit"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "canEdit");
            }
        }
        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");
            }
        }
        internal void AddUserAndRole()
        {
            Models.ApplicationDbContext context = new Models.ApplicationDbContext();

            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

            var roleStore = new RoleStore<IdentityRole>(context);

            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            if (!roleMgr.RoleExists("administrator"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "administrator" });
            }

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

            var appUser = new ApplicationUser
            {
                UserName = "******",
                ImgUrl = "user2-160x160.jpg",
                Description = "High Level",
                SinceDate = new DateTime(2016, 1, 1)
            };

            IdUserResult = userMgr.Create(appUser, "1qaz2wsxE");
            var user = userMgr.FindByName("administrator");
            if (!userMgr.IsInRole(user.Id, "administrator"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByName("administrator").Id, "administrator");
            }
        }
        public static void SeedRoles()
        {
            var context = new ApplicationDbContext();
            if (!context.Roles.Any())
            {
                if (!context.Roles.Any())
                {
                    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

                    var roleCreateResult = roleManager.Create(new IdentityRole("Admin"));
                    if (!roleCreateResult.Succeeded)
                    {
                        throw new Exception(string.Join("; ", roleCreateResult.Errors));
                    }

                    var roleStore = new RoleStore<IdentityRole>(context);

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

                    var userManager = new UserManager<ApplicationUser>(userStore);
                    var user = new ApplicationUser() { UserName = "******", Email = "*****@*****.**" };


                    var createResult = userManager.Create(user, "123456");
                    if (!createResult.Succeeded)
                    {
                        throw new Exception(string.Join("; ", createResult.Errors));
                    }
                    userManager.AddToRole(user.Id, "admin");
                    context.SaveChanges();
                }
            }
        }
示例#14
0
        public static void AddUserRole(string userName, string roleName)
        {
            using (var context = new ApplicationDbContext())
            {
                try
                {
                    if (!context.Roles.Any(r => r.Name == roleName)) return;

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

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

                    var user = userManager.FindByName(userName);
                    var role = roleManager.FindByName(roleName);

                    if (userManager.IsInRole(user.Id, role.Name)) return;

                    userManager.AddToRole(user.Id, role.Name);
                    context.SaveChanges();
                }
                catch (DbEntityValidationException ex)
                {
                    // Retrieve the error messages as a list of strings.

                    // ReSharper disable once UnusedVariable
                    var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                    throw;
                }
            }
        }
示例#15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            HtmlGenericControl body = (HtmlGenericControl)Master.FindControl("BodyTag");
            body.Attributes.Add("class", "login");

            RoleStore<IdentityRole> roleStore = new RoleStore<IdentityRole>();
            RoleManager<IdentityRole> roleMgr = new RoleManager<IdentityRole>(roleStore);

            if (User.Identity.IsAuthenticated)
            {
                Response.Redirect("~/MainPage.aspx");
            }

            //creating roles//
            if (!roleMgr.RoleExists("Admin"))
            {
                IdentityResult roleResult = roleMgr.Create(new IdentityRole("Admin"));
            }
            if (!roleMgr.RoleExists("Manager"))
            {
                IdentityResult roleResult = roleMgr.Create(new IdentityRole("Manager"));
            }
            if (!roleMgr.RoleExists("SalesAssoc"))
            {
                IdentityResult roleResult = roleMgr.Create(new IdentityRole("SalesAssoc"));
            }
            if (!roleMgr.RoleExists("Designer"))
            {
                IdentityResult roleResult = roleMgr.Create(new IdentityRole("Designer"));
            }
            if (!roleMgr.RoleExists("Laborers"))
            {
                IdentityResult roleResult = roleMgr.Create(new IdentityRole("Laborers"));
            }
        }
        /*This should be removed after the first admin gets made */
        // GET: MakeMeAdmin/Create
        public ActionResult Create(string email)
        {
            using (var context = new ApplicationDbContext())
            {
                var fadmin = context.KeyValueSettings.FirstOrDefault(s => s.Key == "FirstAdminSet");
                if (fadmin == null || fadmin.Value == "false")
                {
                    var roleStore = new RoleStore<IdentityRole>(context);
                    var roleManager = new RoleManager<IdentityRole>(roleStore);

                    roleManager.Create(new IdentityRole("Admin"));

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

                    var user = userManager.FindByEmail(email);
                    userManager.AddToRole(user.Id, "Admin");
                    if (fadmin == null)
                    {
                        context.KeyValueSettings.Add(new KeyValueSettings() { Key = "FirstAdminSet", Value = "true" });
                    }
                    else
                    {
                        fadmin.Value = "true";
                    }
                    context.SaveChanges();
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            return Json(false, JsonRequestBehavior.AllowGet);
        }
示例#17
0
        private void InitializeAppEnvironment()
        {
            //app environment configuration
            using (var db = new ApplicationDbContext())
            {
                db.Database.CreateIfNotExists();
                var roleStore = new RoleStore<IdentityRole>(db);
                var role = roleStore.FindByNameAsync("Admin").Result;
                if (role == null)
                {
                    roleStore.CreateAsync(new IdentityRole("Admin")).Wait();
                }

                var userStore = new UserStore<ApplicationUser>(db);
                var manager = new ApplicationUserManager(userStore);

                var admin = manager.FindByName("admin");
                if (admin == null)
                {
                    admin = new ApplicationUser
                    {
                        UserName = "******",
                        Email = "*****@*****.**",
                        EmailConfirmed = true,
                        CreateDate = DateTime.Now
                    };
                    var r = manager.CreateAsync(admin, "~Pwd123456").Result;
                }
                if (!manager.IsInRole(admin.Id, role.Name))
                {
                    manager.AddToRole(admin.Id, role.Name);
                }
            }
        }
示例#18
0
        internal void createStudent()
        {
            // Access the application context and create result variables.
            Models.ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

            // Create a RoleStore object by using the ApplicationDbContext object.
            // The RoleStore is only allowed to contain IdentityRole objects.
            var roleStore = new RoleStore<IdentityRole>(context);

            // Create a RoleManager object that is only allowed to contain IdentityRole objects.
            // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object.
            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            // Then, you create the "Student" role if it doesn't already exist.
            if (!roleMgr.RoleExists("Student"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole("Student"));
                if (!IdRoleResult.Succeeded)
                {
                    // Handle the error condition if there's a problem creating the RoleManager object.
                }
            }
        }
示例#19
0
        public IHttpActionResult addRole(RoleAddModel role)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleManager = new RoleManager<IdentityRole>(roleStore);
            if (roleManager.RoleExists(role.roleName) == false)
            {

                try
                {
                    var sa = roleManager.Create(new IdentityRole(role.roleName));
                    if (sa.Succeeded == true)
                    {
                        return Ok(sa);
                    }
                    else
                    {
                        return BadRequest();
                    }

                }
                catch (Exception)
                {
                    return BadRequest();
                }

            }
            return Conflict();
        }
示例#20
0
        public async Task<ActionResult> Create(UserRoles role)
        {
            if (ModelState.IsValid)
            {
                // Create a RoleStore object by using the ApplicationDbContext object. 
                // The RoleStore is only allowed to contain IdentityRole objects. 
                var roleStore = new RoleStore<IdentityRole>(context);
                // Create a RoleManager object that is only allowed to contain IdentityRole objects. 
                // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object. 
                var roleMgr = new RoleManager<IdentityRole>(roleStore);
                // Then, you create the "Administrator" role if it doesn't already exist.
                if (!roleMgr.RoleExists(role.RoleName))
                {
                    IdRoleResult = roleMgr.Create(new IdentityRole(role.RoleName));
                    if (IdRoleResult.Succeeded)
                    { // Handle the error condition if there's a problem creating the RoleManager object. 
                        ViewBag.StatusMessage = "Role has been added Successfully";
                    }
                    else
                    {
                        ViewBag.StatusMessage = "The Role Already Exists";
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View();
        }
示例#21
0
        internal void AddUserAndRole()
        {
            // Access the application context and create result variable.
            Models.ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

            // Create a RoleStore object by using the ApplicationDbContext object.
            // The RoleStore is only allowed to contain IdentityRole Objects.
            var roleStore = new RoleStore<IdentityRole>(context);

            // Create a RoleManager object that is only allowed to contain IdentityRole objects.
            // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object.
            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            // Then, you create the "canEdit" role if it doesn't already exist.
            if (!roleMgr.RoleExists("canEdit"))
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "canEdit" });

            // Create a UserManager object based on the UserStore objcet and the ApplicationDbContext objcet.
            // Note that you can create new objects and use them as parameters in a single line of code, rather than using multiple lines of code, as you did for the RoleManager object.
            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var appUser = new ApplicationUser
            {
                UserName = "******",
                Email = "*****@*****.**"
            };
            IdUserResult = userMgr.Create(appUser, "Pa$$word1");

            // If the new "canEdit" user was successfully created, add the "canEdit" user to the "canEdit" role.
            if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "canEdit"))
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "canEdit");
        }
    /// <summary>
    /// Checks for the three roles - Admin, Employee and Complainant and 
    /// creates them if not present
    /// </summary>
    public static void InitializeRoles()
    {  // Access the application context and create result variables.
        ApplicationDbContext context = new ApplicationDbContext();
        IdentityResult IdUserResult;

        // Create a RoleStore object by using the ApplicationDbContext object. 
        // The RoleStore is only allowed to contain IdentityRole objects.
        var roleStore = new RoleStore<IdentityRole>(context);

        RoleManager roleMgr = new RoleManager();
        if (!roleMgr.RoleExists("Administrator"))
        {
            roleMgr.Create(new ApplicationRole { Name = "Administrator" });
        }
        if (!roleMgr.RoleExists("Employee"))
        {
            roleMgr.Create(new ApplicationRole { Name = "Employee" });
        }
        if (!roleMgr.RoleExists("Complainant"))
        {
            roleMgr.Create(new ApplicationRole { Name = "Complainant" });
        }
        if (!roleMgr.RoleExists("Auditor"))
        {
            roleMgr.Create(new ApplicationRole { Name = "Auditor" });
        }
      

        // Create a UserManager object based on the UserStore object and the ApplicationDbContext  
        // object. Note that you can create new objects and use them as parameters in
        // a single line of code, rather than using multiple lines of code, as you did
        // for the RoleManager object.
        var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
        var appUser = new ApplicationUser
        {
            UserName = "******",
            Email = "*****@*****.**"
        };
        IdUserResult = userMgr.Create(appUser, "Admin123");

        // If the new "canEdit" user was successfully created, 
        // add the "canEdit" user to the "canEdit" role. 
        if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "Administrator"))
        {
            IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "Administrator");
        }
         appUser = new ApplicationUser
        {
            UserName = "******",
            Email = "*****@*****.**"
        };
        IdUserResult = userMgr.Create(appUser, "Auditor123");

        // If the new "canEdit" user was successfully created, 
        // add the "canEdit" user to the "canEdit" role. 
        if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "Auditor"))
        {
            IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "Auditor");
        }
    }
示例#23
0
        protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    DropDownList ddList = (DropDownList)e.Row.FindControl("DropDownList1");

                    Models.ApplicationDbContext context = new ApplicationDbContext();
                    var roleStore = new RoleStore<IdentityRole>(context);

                    var myRoles = new List<string>();

                    var roleMgr = new RoleManager<IdentityRole>(roleStore);
                    foreach (var role in roleMgr.Roles.ToList())
                    {
                        myRoles.Add(role.Name);
                    }
                    ddList.DataSource = myRoles;
                    ddList.DataBind();

                    DataRowView dr = e.Row.DataItem as DataRowView;
                    ddList.SelectedValue = dr["role"].ToString();
                }
            }
        }
示例#24
0
 public int GetUsersCountInRole(string role)
 {
     var roleStore = new RoleStore<IdentityRole>(this.dbContext);
     var roleManager = new RoleManager<IdentityRole>(roleStore);
     int count = roleManager.FindByName(role).Users.Count;
     return count;
 }
示例#25
0
        internal void createAdmin()
        {
            Models.ApplicationDbContext context = new Models.ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

            var roleStore = new RoleStore<IdentityRole>(context);
        }
        public ActionResult Create()
        {
            var roleStore = new RoleStore<IdentityRole>(db);
            var roleManager = new RoleManager<IdentityRole>(roleStore);

            ViewBag.RolesList = new MultiSelectList(roleManager.Roles, "Name", "Name");
            return View();
        }
        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);
        }
示例#28
0
		/// <summary>
		/// Default constructor.
		/// </summary>
		public SecurityManager(Db db = null) {
			if (db == null)
				db = new Db();
			this.db = db;

			UserManager = new UserManager<Entities.User>(new UserStore<Entities.User>(this.db));
			RoleStore = new RoleStore<IdentityRole>(this.db);
		}
示例#29
0
 public AccountRepo(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
 {
     UserManager = userManager;
     SignInManager = signInManager;
     Db = new ApplicationDbContext();
     RoleStore = new RoleStore<IdentityRole>(Db);
     UserStore = new UserStore<ApplicationUser>(Db);
 }
示例#30
0
        protected override void Seed(BlogFall.Models.ApplicationDbContext context)
        {
            #region Admin Rolünü ve Kullanýcýsýný Oluþtur
            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 == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                };

                manager.Create(user, "Ankara1.");
                manager.AddToRole(user.Id, "Admin");

                // Oluþturulan bu kullanýcýya ait yazýlar ekleyelim:

                #region Kategoriler ve Yazýlar
                if (!context.Categories.Any())
                {
                    Category cat1 = new Category
                    {
                        CategoryName = "Gezi Yazýlarý"
                    };

                    cat1.Posts = new List <Post>();

                    cat1.Posts.Add(new Post
                    {
                        Title        = "Gezi Yazýsý 1",
                        AuthorId     = user.Id,
                        Content      = @"<p>Tincidunt integer eu augue augue nunc elit dolor, luctus placerat scelerisque euismod, iaculis eu lacus nunc mi elit, vehicula ut laoreet ac, aliquam sit amet justo nunc tempor, metus vel.</p>
<p>Placerat suscipit, orci nisl iaculis eros, a tincidunt nisi odio eget lorem nulla condimentum tempor mattis ut vitae feugiat augue cras ut metus a risus iaculis scelerisque eu ac ante.</p>
<p>Fusce non varius purus aenean nec magna felis fusce vestibulum velit mollis odio sollicitudin lacinia aliquam posuere, sapien elementum lobortis tincidunt, turpis dui ornare nisl, sollicitudin interdum turpis nunc eget.</p>",
                        CreationTime = DateTime.Now
                    });

                    cat1.Posts.Add(new Post
                    {
                        Title        = "Gezi Yazýsý 2",
                        AuthorId     = user.Id,
                        Content      = @"<p>Tincidunt integer eu augue augue nunc elit dolor, luctus placerat scelerisque euismod, iaculis eu lacus nunc mi elit, vehicula ut laoreet ac, aliquam sit amet justo nunc tempor, metus vel.</p>
<p>Placerat suscipit, orci nisl iaculis eros, a tincidunt nisi odio eget lorem nulla condimentum tempor mattis ut vitae feugiat augue cras ut metus a risus iaculis scelerisque eu ac ante.</p>
<p>Fusce non varius purus aenean nec magna felis fusce vestibulum velit mollis odio sollicitudin lacinia aliquam posuere, sapien elementum lobortis tincidunt, turpis dui ornare nisl, sollicitudin interdum turpis nunc eget.</p>",
                        CreationTime = DateTime.Now
                    });

                    Category cat2 = new Category
                    {
                        CategoryName = "Ýþ Yazýlarý"
                    };

                    cat2.Posts = new List <Post>();
                    cat2.Posts.Add(new Post
                    {
                        Title        = "Ýþ Yazýsý 1",
                        AuthorId     = user.Id,
                        Content      = @"<p>Tincidunt integer eu augue augue nunc elit dolor, luctus placerat scelerisque euismod, iaculis eu lacus nunc mi elit, vehicula ut laoreet ac, aliquam sit amet justo nunc tempor, metus vel.</p>
<p>Placerat suscipit, orci nisl iaculis eros, a tincidunt nisi odio eget lorem nulla condimentum tempor mattis ut vitae feugiat augue cras ut metus a risus iaculis scelerisque eu ac ante.</p>
<p>Fusce non varius purus aenean nec magna felis fusce vestibulum velit mollis odio sollicitudin lacinia aliquam posuere, sapien elementum lobortis tincidunt, turpis dui ornare nisl, sollicitudin interdum turpis nunc eget.</p>",
                        CreationTime = DateTime.Now
                    });

                    cat2.Posts.Add(new Post
                    {
                        Title        = "Ýþ Yazýsý 2",
                        AuthorId     = user.Id,
                        Content      = @"<p>Tincidunt integer eu augue augue nunc elit dolor, luctus placerat scelerisque euismod, iaculis eu lacus nunc mi elit, vehicula ut laoreet ac, aliquam sit amet justo nunc tempor, metus vel.</p>
<p>Placerat suscipit, orci nisl iaculis eros, a tincidunt nisi odio eget lorem nulla condimentum tempor mattis ut vitae feugiat augue cras ut metus a risus iaculis scelerisque eu ac ante.</p>
<p>Fusce non varius purus aenean nec magna felis fusce vestibulum velit mollis odio sollicitudin lacinia aliquam posuere, sapien elementum lobortis tincidunt, turpis dui ornare nisl, sollicitudin interdum turpis nunc eget.</p>",
                        CreationTime = DateTime.Now
                    });

                    context.Categories.Add(cat1);
                    context.Categories.Add(cat2);
                }
                #endregion
            }
            #endregion

            #region Admin kullanýcýsýna 77 yazý ekle
            if (!context.Categories.Any(x => x.CategoryName == "Diðer"))
            {
                ApplicationUser admin = context.Users
                                        .Where(x => x.UserName == "*****@*****.**")
                                        .FirstOrDefault();

                if (admin != null)
                {
                    if (!context.Categories.Any(x => x.CategoryName == "Diðer"))
                    {
                        Category diger = new Category
                        {
                            CategoryName = "Diðer",
                            Posts        = new HashSet <Post>()
                        };
                        for (int i = 0; i <= 77; i++)
                        {
                            diger.Posts.Add(new Post
                            {
                                Title        = "Diðer Yazý " + i,
                                AuthorId     = admin.Id,
                                Content      = @"<p>Tincidunt integer eu augue augue nunc elit dolor, luctus placerat scelerisque euismod, iaculis eu lacus nunc mi elit, vehicula ut laoreet ac, aliquam sit amet justo nunc tempor, metus vel.</p>",
                                CreationTime = DateTime.Now.AddMinutes(i)
                            });
                        }
                        context.Categories.Add(diger);
                    }
                }
            }
            #endregion
        }
示例#31
0
        protected override void Seed(Blog.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

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

            if (!context.Categories.Any())
            {
                context.Categories.AddRange(new List <Category>
                {
                    new Category {
                        CategoryName = "Sport", Description = "Sport (or sports) is all forms of usually competitive physical activity which, through casual or organised participation, aim to use, maintain or improve physical ability and skills while providing entertainment to participants, and in some cases, spectators."
                    },
                    new Category {
                        CategoryName = "Politic", Description = "Politics is the set of activities that are associated with making decisions in groups, or other forms of power relations between individuals, such as the distribution of resources or status. The academic study of politics is referred to as political science."
                    },
                    new Category {
                        CategoryName = "Software", Description = "Software, instructions that tell a computer what to do. Software comprises the entire set of programs, procedures, and routines associated with the operation of a computer system. The term was coined to differentiate these instructions from hardware, the physical components of a computer system."
                    },
                    new Category {
                        CategoryName = "Future", Description = "Future studies, futures research or futurology is the systematic, interdisciplinary and holistic study of social and technological advancement, and other environmental trends, often for the purpose of exploring how people will live and work in the future. "
                    },
                    new Category {
                        CategoryName = "Movie", Description = "Movies, or films, are a type of visual communication which uses moving pictures and sound to tell stories or teach people something. Most people watch (view) movies as a type of entertainment or a way to have fun."
                    }
                });
            }

            if (!context.Roles.Any(x => x.Name == "admin"))
            {
                var roleStore   = new RoleStore <IdentityRole>(context);
                var roleManager = new RoleManager <IdentityRole>(roleStore);
                roleManager.Create(new IdentityRole("admin"));
            }


            if (!context.Users.Any(x => x.UserName == "*****@*****.**"))
            {
                var userStore   = new UserStore <ApplicationUser>(context);
                var userManager = new ApplicationUserManager(userStore);
                var user        = new ApplicationUser()
                {
                    Nickname       = "administrator",
                    UserName       = "******",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true
                };
                userManager.Create(user, "Ankara1.");
                userManager.AddToRole(user.Id, "admin");
            }

            if (!context.ReportCategories.Any())
            {
                ReportCategory report1 = new ReportCategory()
                {
                    Name = "Spam"
                };
                ReportCategory report2 = new ReportCategory()
                {
                    Name = "Harassment"
                };
                ReportCategory report3 = new ReportCategory()
                {
                    Name = "Rules Violation"
                };
                context.ReportCategories.AddRange(new List <ReportCategory>()
                {
                    report1, report2, report3
                });
            }
        }
示例#32
0
        public ActionResult Details(string id, string FlowPageType = "", string ReturnAction = "")
        {
            var  store       = new UserStore <ApplicationUser>(ctx);
            var  manager     = new UserManager <ApplicationUser>(store);
            var  user        = manager.FindByName(User.Identity.Name);
            var  roleStore   = new RoleStore <ApplicationRole>(ctx);
            var  roleManager = new RoleManager <ApplicationRole>(roleStore);
            bool isAdmin     = false;

            FlowMain fmain = ctx.FlowMainList.Where(x => x.id == id).FirstOrDefault();

            ViewBag.flowMain = fmain;
            vwEmployee employee = ctx.getUserByWorkNo(fmain.senderNo);

            ViewBag.Employee = employee;

            foreach (var role in roleManager.Roles)
            {
                if (user.Roles.Where(x => x.RoleId == role.Id && role.Name.ToUpper() == "ADMIN").Count() > 0)
                {
                    isAdmin = true;
                    break;
                }
            }

            if (!isAdmin && fmain.defId != "EventSchedule")
            {
                if (ctx.FlowSubList.Where(x => x.pid == id && x.workNo == User.Identity.Name).Count() == 0)
                {
                    return(RedirectToAction("AccessDenied", "Account"));
                }
            }

            if (ctx.FlowSubList.Where(x => x.pid == id && x.workNo == User.Identity.Name && x.signType == 701).Count() > 0)
            {
                FlowPageType = "HRCheck";
            }

            if (FlowPageType == "")
            {
                FlowPageType = fmain.defId == "EventSchedule" ? "EventSchedule" : "";
            }

            var context = new ApplicationDbContext();

            ViewBag.FlowPageType = FlowPageType;
            ViewBag.ReturnAction = ReturnAction;

            List <vwFlowSub> list     = new List <vwFlowSub>();
            List <FlowSub>   fsubList = context.FlowSubList.Where(x => x.pid == id).OrderBy(x => x.seq).ToList <FlowSub>();

            foreach (FlowSub sitem in fsubList)
            {
                var       signResultObj = context.signResultList().Where(x => x.id == sitem.signResult).FirstOrDefault();
                var       signTypeObj   = context.signTypeList().Where(x => x.id == sitem.signType).FirstOrDefault();
                var       signUser      = context.Users.Where(x => x.workNo == sitem.workNo).FirstOrDefault();
                vwFlowSub item          = new vwFlowSub
                {
                    id         = sitem.id,
                    seq        = sitem.seq,
                    signDate   = sitem.signDate,
                    signResult = signResultObj == null ? "" : signResultObj.nm,
                    signType   = signTypeObj == null ? "會簽" : signTypeObj.nm,
                    signer     = signUser == null ? "" : signUser.workNo + "-" + signUser.cName,
                    comment    = sitem.comment
                };
                list.Add(item);
            }


            #region "非工作時間廠務申請單"
            if (fmain.defId == "OverTime")
            {
                fmain.flowName += "(P016A1)";
                ReqOverTime   reqOverTimeObj   = context.reqOverTimeList.Where(x => x.flowId == id).FirstOrDefault();
                vwReqOverTime vwReqOverTimeObj = null;
                if (reqOverTimeObj != null)
                {
                    vwReqOverTimeObj = new vwReqOverTime
                    {
                        billNo  = fmain.billNo,
                        dtBegin = reqOverTimeObj.dtBegin,
                        dtEnd   = reqOverTimeObj.dtEnd,
                        hours   = reqOverTimeObj.hours,
                        sMemo   = reqOverTimeObj.sMemo
                    };
                    JObject jobjext = null;
                    try
                    {
                        jobjext = JObject.Parse(reqOverTimeObj.jext);
                        vwReqOverTimeObj.sType      = jobjext["stype"] == null ? "" : jobjext["stype"].ToString();
                        vwReqOverTimeObj.place      = jobjext["place"] == null ? "" : jobjext["place"].ToString();
                        vwReqOverTimeObj.otherPlace = jobjext["otherPlace"] == null ? "" : jobjext["otherPlace"].ToString();
                        vwReqOverTimeObj.prjId      = jobjext["prjId"] == null ? "" : jobjext["prjId"].ToString();

                        vwReqOverTimeObj.sMemo2 = jobjext["sMemo2"] == null ? "" : jobjext["sMemo2"].ToString();
                        vwReqOverTimeObj.worker = jobjext["worker"] == null ? "" : jobjext["worker"].ToString();
                        vwReqOverTimeObj.depNo  = jobjext["depNo"] == null ? "" : jobjext["depNo"].ToString();

                        vwReqOverTimeObj.poNo = jobjext["poNo"] == null ? "" : jobjext["poNo"].ToString();
                        vwReqOverTimeObj.poNm = jobjext["poNo"] == null ? "" : context.jobPos.Where(x => x.poNo.Equals(vwReqOverTimeObj.poNo)).FirstOrDefault().poNm;

                        jobPo  poObj = context.jobPos.Where(x => x.poNo == vwReqOverTimeObj.poNo).First();
                        string depNo = poObj.depNo;
                        string depNm = context.getParentDeps(depNo, context) + " : " + poObj.poNm;
                        vwReqOverTimeObj.depNm = depNm;
                    }
                    catch (Exception ex)
                    {
                    }
                }
                ViewBag.SubModel = vwReqOverTimeObj;
                return(View(list));
            }
            #endregion

            #region "加班單"
            if (fmain.defId == "RealOverTime")
            {
                fmain.flowName += "(P017A1)";
                ReqOverTime    reqOverTimeObj   = context.reqOverTimeList.Where(x => x.flowId == id).FirstOrDefault();
                vwRealOverTime vwReqOverTimeObj = null;
                if (reqOverTimeObj != null)
                {
                    vwReqOverTimeObj = new vwRealOverTime
                    {
                        user    = ctx.getUserByWorkNo(fmain.senderNo),
                        billNo  = fmain.billNo,
                        dtBegin = reqOverTimeObj.dtBegin,
                        dtEnd   = reqOverTimeObj.dtEnd,
                        hours   = reqOverTimeObj.hours,
                        sMemo   = reqOverTimeObj.sMemo
                    };
                    JObject jobjext = null;
                    try
                    {
                        jobjext = JObject.Parse(reqOverTimeObj.jext);
                        vwReqOverTimeObj.sMemo2 = jobjext["sMemo2"] == null ? "" : jobjext["sMemo2"].ToString();
                    }
                    catch (Exception ex)
                    {
                    }
                }
                ViewBag.SubModel = vwReqOverTimeObj;
                return(View(list));
            }
            #endregion

            #region "請假單"
            if (fmain.defId == "DayOff")
            {
                fmain.flowName += "(P018A1)";
                vwDayOffForm subModel  = new vwDayOffForm();
                dayOff       dayOffObj = ctx.dayOffList.Where(x => x.flowId == fmain.id).FirstOrDefault();
                subModel.dayOffForm = new vwdayOff
                {
                    id       = dayOffObj.id,
                    billNo   = fmain.billNo,
                    dtBegin  = dayOffObj.dtBegin,
                    dtEnd    = dayOffObj.dtEnd,
                    hours    = dayOffObj.hours,
                    dType    = dayOffObj.dType,
                    sMemo    = dayOffObj.sMemo,
                    jobAgent = dayOffObj.jobAgent
                };
                ViewBag.SubModel = subModel;
                return(View("Details", list));
            }
            #endregion

            #region "外出申請單"
            if (fmain.defId == "PublicOut")
            {
                fmain.flowName += "(P019A1)";
                publicOut   publicOutObj = ctx.publicOutList.Where(x => x.flowId == fmain.id).FirstOrDefault();
                vwPublicOut subModel     = new vwPublicOut
                {
                    id          = publicOutObj.id,
                    billNo      = fmain.billNo,
                    user        = ctx.getUserByWorkNo(fmain.senderNo),
                    requestDate = publicOutObj.requestDate,
                    dtBegin     = publicOutObj.dtBegin,
                    dtEnd       = publicOutObj.dtEnd,
                    subject     = publicOutObj.subject,
                    destination = publicOutObj.destination,
                    transport   = publicOutObj.transport
                };
                ViewBag.SubModel = subModel;
                return(View("Details", list));
            }

            #endregion

            #region "訪客申請單"
            if (fmain.defId == "GuestForm")
            {
                fmain.flowName += "(P011A1)";
                guestForm   formObj  = ctx.guestFormList.Where(x => x.flowId == fmain.id).FirstOrDefault();
                vwGuestForm subModel = new vwGuestForm
                {
                    id          = formObj.id,
                    user        = ctx.getUserByWorkNo(fmain.senderNo),
                    requestDate = formObj.requestDate,
                    dtBegin     = formObj.dtBegin,
                    dtEnd       = formObj.dtEnd,
                    subject     = formObj.subject,
                    to          = formObj.to,
                    toDep       = formObj.toDep,
                    guestCmp    = formObj.guestCmp,
                    guestName   = formObj.guestName,
                    guestCnt    = formObj.guestCnt,
                    cellPhone   = formObj.cellPhone,
                    area1       = formObj.area1,
                    area2       = formObj.area2,
                    area21      = formObj.area21,
                    area3       = formObj.area3,
                    area4       = formObj.area4,
                    area41      = formObj.area41,
                    sMemo       = formObj.sMemo
                };
                ViewBag.SubModel = subModel;
                return(View("Details", list));
            }
            #endregion

            #region "廠務派工及總務需求申請單"
            if (fmain.defId == "ReqInHouse")
            {
                fmain.flowName += "(P020A1)";
                ReqInHouse   formObj  = ctx.reqInHouseList.Where(x => x.flowId == fmain.id).FirstOrDefault();
                vwReqInHouse subModel = new vwReqInHouse
                {
                    id       = formObj.id,
                    user     = ctx.getUserByWorkNo(fmain.senderNo),
                    billDate = fmain.billDate,
                    contact  = formObj.contact,
                    depNo    = formObj.depNo,
                    reqLimit = formObj.reqLimit,
                    reqMemo  = formObj.reqMemo,
                    sMemo    = formObj.sMemo
                };
                ViewBag.SubModel = subModel;
                return(View("Details", list));
            }
            #endregion

            #region "公司行程規劃表"
            if (fmain.defId == "EventSchedule")
            {
                fmain.flowName += "(B001A1)";
                EventSchedule   formObj  = ctx.eventScheduleList.Where(x => x.flowId == fmain.id).FirstOrDefault();
                vwEventSchedule subModel = new vwEventSchedule
                {
                    id        = formObj.id,
                    user      = ctx.getUserByWorkNo(fmain.senderNo),
                    billDate  = fmain.billDate,
                    beginHH   = formObj.beginHH,
                    beginMM   = formObj.beginMM,
                    subject   = formObj.subject,
                    location  = formObj.location,
                    eventType = formObj.eventType,
                    sMemo     = formObj.sMemo
                };
                ViewBag.SubModel = subModel;
                return(View("Details", list));
            }
            #endregion

            return(View(list));
        }
        protected override void Seed(BlogContext db)
        {
            var categories = new List <Category>
            {
                new Category {
                    Id = 1, Name = "Travel", Description = "Category about Travel"
                },
                new Category {
                    Id = 2, Name = "Technology", Description = "Category about Technology"
                },
                new Category {
                    Id = 3, Name = "Sport", Description = "Category about Sport"
                },
                new Category {
                    Id = 4, Name = "Recreation", Description = "Category about Recreation"
                },
                new Category {
                    Id = 5, Name = "Misc", Description = "Category about Misc"
                }
            };

            categories.ForEach(c => db.Categories.Add(c));
            db.SaveChanges();

            var posts = new List <Post>()
            {
                new Post
                {
                    Id          = 1,
                    Title       = "Amazon",
                    Description = "Amazon daily deals for Tuesday, April 17",
                    Category    = "Technology",
                    Content     =
                        "If you\'re looking to add a little extra security for your house, Amazon has plenty of deals on surveillance cameras so you can keep an eye on things.\r\nDIYers can also pick up a DeWALT drill and impact combo kit for their next project, and outdoor enthusiasts can save up to 25% on boating and fishing gear. \r\n\r\nThere are also lightning deals on summer wear like tank tops and water shoes, not to mention smartphone charging accessories like an Anker power bank and a Qi-enabled wireless charger.\r\n",
                    Author           = "*****@*****.**",
                    DefaultImageName = "amazon.jpg",
                    ImageMimeType    = "image / jpeg",
                    ImageData        = FileToByteArray("~/Images/Default/amazon.jpg"),
                    IsApproved       = true
                },
                new Post
                {
                    Id          = 2,
                    Title       = "Ford",
                    Description = "Ford charges into electric bike-sharing",
                    Category    = "Technology",
                    Content     =
                        "I got to try one out ahead of time, taking a test ride through San Francisco\'s crowded South of Market and hilly Potrero Hill neighborhoods. My prediction: The e-bike, a Ford GoBike Plus, will be in high demand. The motor provides a jolt of pep, and I was able to climb a fairly steep two blocks of Mississippi Street — something I never would have done on a regular bicycle.\r\n\r\nMotivate, the bike-share operator behind Citi Bike in New York City, rushed to bring the new e-bikes into the Bay Area after a spate of other e-bikes and scooters flooded the market. Like its pedal-powered cousin, the new bikes require a dock. These aren\'t a jump-on-and-drop-off anywhere option, but you don\'t have to worry about blocking the sidewalk or walkway, since the bike has a designated space. \r\n\r\nFord’s e-bikes follow the trend from Chinese bike companies that have crept into North American cities. In China, the electric bikes have been popular for the past few years, but the easy-to-ride bicycles come with major issues, like sidewalk litter, rampant theft, and mass bicycle graves filled with broken and abandoned bikes. \r\n\r\nAlso in the mix is Uber\'s recently acquired Jump e-bikes, a San-Francisco-based share program. Those don\'t require a dock, but they feel less zippy compared to the Ford bikes. The built-in U-locks on the red Jump bikes do make it easier to use a bike rack wherever you go. A Motivate spokesperson said Ford is researching a dockless version of its bicycles.",
                    Author           = "*****@*****.**",
                    DefaultImageName = "ford.jpg",
                    ImageMimeType    = "image / jpeg",
                    ImageData        = FileToByteArray("~/Images/Default/ford.jpg"),
                    IsApproved       = true
                },
                new Post
                {
                    Id          = 3,
                    Title       = "RAVPower",
                    Description = "These deals on RAVPower chargers are too good to pass up",
                    Category    = "Technology",
                    Content     =
                        "You have plenty of gadgets, new and old, that need charging. Save big while RAVPower devices are on sale and charge them all.\r\n\r\nSEE ALSO: This glow-in-the-dark MFi-certified charging cable is just $20\r\n\r\nAmazon has some great deals today on RAVPower chargers to keep your devices juiced up. From Qi-enabled wireless charging to USB devices, there are plenty of deals to help you make sure you don\'t run out of power. \r\n\r\nCheck out the RAVPower chargers on sale today:\r\n\r\nWireless and ready\r\nThis charging pad works with any newer phone like the iPhone X and Samsung Galaxy S9. It also features an indicator light to let you know when your device is done charging. You can save a whopping 82% on it today.",
                    Author           = "*****@*****.**",
                    DefaultImageName = "ravp.jpg",
                    ImageMimeType    = "image / jpeg",
                    ImageData        = FileToByteArray("~/Images/Default/ravp.jpg"),
                    IsApproved       = true
                },
                new Post
                {
                    Id          = 4,
                    Title       = "EarthDay",
                    Description = "The Samsung Galaxy S8, Echo devices, and more used items are on sale for Earth Day",
                    Category    = "Technology",
                    Content     =
                        "While April 22 isn\'t typically a huge shopping holiday, you didn\'t think Amazon was about to not use this as an excuse to have a giant sale, did you? In honor of Earth Day, save big on select used tech items across the site. Sales end at 11:59 pm PST on April 22.\r\n\r\nSEE ALSO: Solar-charging backpacks let you power up while on the go and these are some of our favorites\r\n\r\nE-waste is wreaking havoc on the Earth at a pretty alarming rate, with nearly 70% of toxins in landfills coming from electronics. \r\n\r\nThe Amazon Warehouse is aiming to give used items a new home. In the spirit of reducing, reusing, and recycling, Amazon is offering tons of deals, plus an extra 20% off on select used items. \r\n\r\nSave on everything from smartphones, to robot vacuums, to kitchen gadgets, and more. Many of these items are high-end and don\'t usually see discounts, so this sale is kind of a big deal.",
                    Author           = "*****@*****.**",
                    DefaultImageName = "samsung.jpg",
                    ImageMimeType    = "image / jpeg",
                    ImageData        = FileToByteArray("~/Images/Default/samsung.jpg"),
                    IsApproved       = true
                },
                new Post
                {
                    Id          = 5,
                    Title       = "Headphones",
                    Description = "These Bose wireless headphones are sweat-resistant and $50 off",
                    Category    = "Technology",
                    Content     =
                        "Break free from wires for good and make those trips to the gym even easier with these Bose SoundSport wireless headphones that are on sale today for $50 off.\r\n\r\nSEE ALSO: Make any headphones wireless with this $20 Bluetooth receiver\r\n\r\nThese headphones are sweat and weather-resistant so you can go HAM without worry. They comes with three different tips to fit comfortably and provide up to five hours of play time on a single charge. They also come with a charging case to keep them powered up on the go, and you can even keep track of them with Bose\'s \"Find My Buds\" app.\r\n\r\nPlus, they look super badass.\r\n\r\nAmazon lists the price at $249, but you can get them now for only $199 — a 20% savings.",
                    Author           = "*****@*****.**",
                    DefaultImageName = "bose.jpg",
                    ImageMimeType    = "image / jpeg",
                    ImageData        = FileToByteArray("~/Images/Default/bose.jpg"),
                    IsApproved       = true
                },
                new Post
                {
                    Id          = 6,
                    Title       = "MothersDay",
                    Description = "21 Mother's Day gifts for the tech-savvy mom",
                    Category    = "Technology",
                    Content     =
                        "Paying back our moms for all that they do is no easy task. But we can always try come Mother\'s Day with some sweet, tech-centric gifts.\r\n\r\nSEE ALSO: Traditional anniversary gifts, reimagined for millennial couples\r\n\r\nNot all moms need special instructions just for turning on the TV. If your mom is the first to adopt the latest streaming device, knows all the iPhone hacks, and is even teaching you a thing or two, then these are the gifts for her. From portable tech that she can take to work to home gadgets that she can use around the house, these awesome tech gifts are sure to be right in her wheelhouse.\r\n\r\nFor moms who hit the gym\r\nA Fitbit is a great go-to gift for anyone who wants to get fit, or is looking to download all the data or their latest sweat session. This classic, easy-to-use fitness tracker is a bestseller for a reason and could help your fitness fanatic mom stay on her toes.",
                    Author     = "*****@*****.**",
                    IsDeclined = true
                },
                new Post
                {
                    Id          = 7,
                    Title       = "Madrid",
                    Description = "Travelling to Madrid? Here are some of the best spots off the beaten path",
                    Category    = "Travel",
                    Content     =
                        "With its beautiful architecture, lively culture, and delicious cuisine, few cities can compare to the wonders that can be found in Madrid. And while locations like the Prado museum, Retiro park, and Royal Palace usually top visitors’ bucket list, oftentimes it’s the lesser-known spots that create the richest experiences.\r\n\r\nIn the spirit of channelling our inner wanderlust, we set out to discover the best places in Madrid that fly under the radar. This isn’t your ordinary travel guide: read on to discover our picks for some of the best things to do, see, and eat in Madrid — and experience the city like a true Madrileño.   \r\n\r\nWHAT TO DO\r\n\r\nFor couples: Most people think of the Rioja region when they think of Spanish wine, but Madrid is actually surrounded by vineyards — some of which are just a bus or train ride away. You and your significant other can take a day trip to the Vinos de Madrid, which includes three different subsections, and sample local wines while taking in the breath-taking scenery. There are plenty of tour options for each area.\r\n\r\nFor business travellers: If you’re in Madrid on business, Miss Filatelista blogger Lola Mendez recommends you check out Google Campus Madrid, a collaborative space made for everyone from entrepreneurs to freelancers. You can sign up for free access and use it as a makeshift office during your travels. There’s also an onsite café if you prefer a more laid-back",
                    Author     = "*****@*****.**",
                    IsDeclined = true
                },
                new Post
                {
                    Id          = 8,
                    Title       = "Madrid",
                    Description = "Travelling to Madrid? Here are some of the best spots off the beaten path",
                    Category    = "Travel",
                    Content     =
                        "With its beautiful architecture, lively culture, and delicious cuisine, few cities can compare to the wonders that can be found in Madrid. And while locations like the Prado museum, Retiro park, and Royal Palace usually top visitors’ bucket list, oftentimes it’s the lesser-known spots that create the richest experiences.\r\n\r\nIn the spirit of channelling our inner wanderlust, we set out to discover the best places in Madrid that fly under the radar. This isn’t your ordinary travel guide: read on to discover our picks for some of the best things to do, see, and eat in Madrid — and experience the city like a true Madrileño.   \r\n\r\nWHAT TO DO\r\n\r\nFor couples: Most people think of the Rioja region when they think of Spanish wine, but Madrid is actually surrounded by vineyards — some of which are just a bus or train ride away. You and your significant other can take a day trip to the Vinos de Madrid, which includes three different subsections, and sample local wines while taking in the breath-taking scenery. There are plenty of tour options for each area.\r\n\r\nFor business travellers: If you’re in Madrid on business, Miss Filatelista blogger Lola Mendez recommends you check out Google Campus Madrid, a collaborative space made for everyone from entrepreneurs to freelancers. You can sign up for free access and use it as a makeshift office during your travels. There’s also an onsite café if you prefer a more laid-back",
                    Author     = "*****@*****.**",
                    IsDeclined = true
                },
                new Post
                {
                    Id          = 9,
                    Title       = "Madrid",
                    Description = "Travelling to Madrid? Here are some of the best spots off the beaten path",
                    Category    = "Travel",
                    Content     =
                        "With its beautiful architecture, lively culture, and delicious cuisine, few cities can compare to the wonders that can be found in Madrid. And while locations like the Prado museum, Retiro park, and Royal Palace usually top visitors’ bucket list, oftentimes it’s the lesser-known spots that create the richest experiences.\r\n\r\nIn the spirit of channelling our inner wanderlust, we set out to discover the best places in Madrid that fly under the radar. This isn’t your ordinary travel guide: read on to discover our picks for some of the best things to do, see, and eat in Madrid — and experience the city like a true Madrileño.   \r\n\r\nWHAT TO DO\r\n\r\nFor couples: Most people think of the Rioja region when they think of Spanish wine, but Madrid is actually surrounded by vineyards — some of which are just a bus or train ride away. You and your significant other can take a day trip to the Vinos de Madrid, which includes three different subsections, and sample local wines while taking in the breath-taking scenery. There are plenty of tour options for each area.\r\n\r\nFor business travellers: If you’re in Madrid on business, Miss Filatelista blogger Lola Mendez recommends you check out Google Campus Madrid, a collaborative space made for everyone from entrepreneurs to freelancers. You can sign up for free access and use it as a makeshift office during your travels. There’s also an onsite café if you prefer a more laid-back",
                    Author     = "*****@*****.**",
                    IsDeclined = true
                },
                new Post
                {
                    Id          = 10,
                    Title       = "Madrid",
                    Description = "Travelling to Madrid? Here are some of the best spots off the beaten path",
                    Category    = "Travel",
                    Content     =
                        "With its beautiful architecture, lively culture, and delicious cuisine, few cities can compare to the wonders that can be found in Madrid. And while locations like the Prado museum, Retiro park, and Royal Palace usually top visitors’ bucket list, oftentimes it’s the lesser-known spots that create the richest experiences.\r\n\r\nIn the spirit of channelling our inner wanderlust, we set out to discover the best places in Madrid that fly under the radar. This isn’t your ordinary travel guide: read on to discover our picks for some of the best things to do, see, and eat in Madrid — and experience the city like a true Madrileño.   \r\n\r\nWHAT TO DO\r\n\r\nFor couples: Most people think of the Rioja region when they think of Spanish wine, but Madrid is actually surrounded by vineyards — some of which are just a bus or train ride away. You and your significant other can take a day trip to the Vinos de Madrid, which includes three different subsections, and sample local wines while taking in the breath-taking scenery. There are plenty of tour options for each area.\r\n\r\nFor business travellers: If you’re in Madrid on business, Miss Filatelista blogger Lola Mendez recommends you check out Google Campus Madrid, a collaborative space made for everyone from entrepreneurs to freelancers. You can sign up for free access and use it as a makeshift office during your travels. There’s also an onsite café if you prefer a more laid-back",
                    Author     = "*****@*****.**",
                    IsDeclined = true
                },
                new Post
                {
                    Id          = 11,
                    Title       = "Madrid",
                    Description = "Travelling to Madrid? Here are some of the best spots off the beaten path",
                    Category    = "Travel",
                    Content     =
                        "With its beautiful architecture, lively culture, and delicious cuisine, few cities can compare to the wonders that can be found in Madrid. And while locations like the Prado museum, Retiro park, and Royal Palace usually top visitors’ bucket list, oftentimes it’s the lesser-known spots that create the richest experiences.\r\n\r\nIn the spirit of channelling our inner wanderlust, we set out to discover the best places in Madrid that fly under the radar. This isn’t your ordinary travel guide: read on to discover our picks for some of the best things to do, see, and eat in Madrid — and experience the city like a true Madrileño.   \r\n\r\nWHAT TO DO\r\n\r\nFor couples: Most people think of the Rioja region when they think of Spanish wine, but Madrid is actually surrounded by vineyards — some of which are just a bus or train ride away. You and your significant other can take a day trip to the Vinos de Madrid, which includes three different subsections, and sample local wines while taking in the breath-taking scenery. There are plenty of tour options for each area.\r\n\r\nFor business travellers: If you’re in Madrid on business, Miss Filatelista blogger Lola Mendez recommends you check out Google Campus Madrid, a collaborative space made for everyone from entrepreneurs to freelancers. You can sign up for free access and use it as a makeshift office during your travels. There’s also an onsite café if you prefer a more laid-back",
                    Author     = "*****@*****.**",
                    IsDeclined = true
                },
                new Post
                {
                    Id          = 12,
                    Title       = "Madrid",
                    Description = "Travelling to Madrid? Here are some of the best spots off the beaten path",
                    Category    = "Travel",
                    Content     =
                        "With its beautiful architecture, lively culture, and delicious cuisine, few cities can compare to the wonders that can be found in Madrid. And while locations like the Prado museum, Retiro park, and Royal Palace usually top visitors’ bucket list, oftentimes it’s the lesser-known spots that create the richest experiences.\r\n\r\nIn the spirit of channelling our inner wanderlust, we set out to discover the best places in Madrid that fly under the radar. This isn’t your ordinary travel guide: read on to discover our picks for some of the best things to do, see, and eat in Madrid — and experience the city like a true Madrileño.   \r\n\r\nWHAT TO DO\r\n\r\nFor couples: Most people think of the Rioja region when they think of Spanish wine, but Madrid is actually surrounded by vineyards — some of which are just a bus or train ride away. You and your significant other can take a day trip to the Vinos de Madrid, which includes three different subsections, and sample local wines while taking in the breath-taking scenery. There are plenty of tour options for each area.\r\n\r\nFor business travellers: If you’re in Madrid on business, Miss Filatelista blogger Lola Mendez recommends you check out Google Campus Madrid, a collaborative space made for everyone from entrepreneurs to freelancers. You can sign up for free access and use it as a makeshift office during your travels. There’s also an onsite café if you prefer a more laid-back",
                    Author     = "*****@*****.**",
                    IsDeclined = true
                },
                new Post
                {
                    Id          = 13,
                    Title       = "Instagram",
                    Description = "Instagram blogger Photoshops her body to look how trolls want it to look",
                    Category    = "Recreation",
                    Content     =
                        "Sadly, the reality of having any kind of online presence in this day and age seems to come hand in hand with receiving negative and abusive comments. It\'s unpleasant, upsetting, and sometimes, deeply personal. \r\n\r\nSEE ALSO: How to protect yourself when social media is harming your self-esteem\r\n\r\n\r\nA popular British fitness blogger did something rather unusual with the negative Instagram DMs she received after posting shots of herself working out on her Instagram Story. She Photoshopped the images to reflect the abusive comments left by trolls and added them to her Story. And, the results were nothing short of terrifying.\r\n\r\nChessie King worked with anti-cyberbullying non-profit organisation Cybersmile to highlight the harmful effect of online abuse on young people.\r\n\r\nKing, who has over 330K Instagram followers, posted a series of photos and video of herself on her Instagram Story. Those photos and videos were then \"altered in real-time\" to reflect the replies she was receiving from trolls. \r\n\r\nTrolling is something that\'s sadly become part of King\'s everyday life as an Instagram blogger. But, research shows that it\'s not just bloggers and influencers who receive online abuse. Research conducted by Data and Society Research Institute found that 47 percent of internet users have \"personally experienced online harassment or abuse.\"",
                    Author    = "*****@*****.**",
                    IsDeleted = true
                },
                new Post
                {
                    Id          = 14,
                    Title       = "Instagram",
                    Description = "Instagram blogger Photoshops her body to look how trolls want it to look",
                    Category    = "Misc",
                    Content     =
                        "Sadly, the reality of having any kind of online presence in this day and age seems to come hand in hand with receiving negative and abusive comments. It\'s unpleasant, upsetting, and sometimes, deeply personal. \r\n\r\nSEE ALSO: How to protect yourself when social media is harming your self-esteem\r\n\r\n\r\nA popular British fitness blogger did something rather unusual with the negative Instagram DMs she received after posting shots of herself working out on her Instagram Story. She Photoshopped the images to reflect the abusive comments left by trolls and added them to her Story. And, the results were nothing short of terrifying.\r\n\r\nChessie King worked with anti-cyberbullying non-profit organisation Cybersmile to highlight the harmful effect of online abuse on young people.\r\n\r\nKing, who has over 330K Instagram followers, posted a series of photos and video of herself on her Instagram Story. Those photos and videos were then \"altered in real-time\" to reflect the replies she was receiving from trolls. \r\n\r\nTrolling is something that\'s sadly become part of King\'s everyday life as an Instagram blogger. But, research shows that it\'s not just bloggers and influencers who receive online abuse. Research conducted by Data and Society Research Institute found that 47 percent of internet users have \"personally experienced online harassment or abuse.\"",
                    Author    = "*****@*****.**",
                    IsDeleted = true
                },
                new Post
                {
                    Id          = 15,
                    Title       = "Instagram",
                    Description = "Instagram blogger Photoshops her body to look how trolls want it to look",
                    Category    = "Sport",
                    Content     =
                        "Sadly, the reality of having any kind of online presence in this day and age seems to come hand in hand with receiving negative and abusive comments. It\'s unpleasant, upsetting, and sometimes, deeply personal. \r\n\r\nSEE ALSO: How to protect yourself when social media is harming your self-esteem\r\n\r\n\r\nA popular British fitness blogger did something rather unusual with the negative Instagram DMs she received after posting shots of herself working out on her Instagram Story. She Photoshopped the images to reflect the abusive comments left by trolls and added them to her Story. And, the results were nothing short of terrifying.\r\n\r\nChessie King worked with anti-cyberbullying non-profit organisation Cybersmile to highlight the harmful effect of online abuse on young people.\r\n\r\nKing, who has over 330K Instagram followers, posted a series of photos and video of herself on her Instagram Story. Those photos and videos were then \"altered in real-time\" to reflect the replies she was receiving from trolls. \r\n\r\nTrolling is something that\'s sadly become part of King\'s everyday life as an Instagram blogger. But, research shows that it\'s not just bloggers and influencers who receive online abuse. Research conducted by Data and Society Research Institute found that 47 percent of internet users have \"personally experienced online harassment or abuse.\"",
                    Author    = "*****@*****.**",
                    IsDeleted = true
                }
            };

            posts.ForEach(p => db.Posts.Add(p));
            db.SaveChanges();

            var comments = new List <Comment>()
            {
                new Comment
                {
                    Id            = 1,
                    Author        = "blogger123",
                    Content       = "Very usefull post.Thanks.",
                    CurrentPost   = db.Posts.Where(p => p.Id == 1).ToList().FirstOrDefault(),
                    CurrentPostId = 1
                },
                new Comment
                {
                    Id            = 2,
                    Author        = "traveller",
                    Content       = "That is not true!",
                    CurrentPost   = db.Posts.Where(p => p.Id == 1).ToList().FirstOrDefault(),
                    CurrentPostId = 1
                },
                new Comment
                {
                    Id            = 3,
                    Author        = "sportsman",
                    Content       = "Hello everybody",
                    CurrentPost   = db.Posts.Where(p => p.Id == 1).ToList().FirstOrDefault(),
                    CurrentPostId = 1
                }
            };

            comments.ForEach(c => db.Comments.Add(c));
            db.SaveChanges();

            var passwordHash = new PasswordHasher();
            var users        = new List <ApplicationUser>()
            {
                new ApplicationUser()
                {
                    Id           = "2",
                    UserName     = "******",
                    Email        = "*****@*****.**",
                    PasswordHash = passwordHash.HashPassword("blogger123")
                },
                new ApplicationUser()
                {
                    Id           = "3",
                    UserName     = "******",
                    Email        = "*****@*****.**",
                    PasswordHash = passwordHash.HashPassword("travel123")
                },
                new ApplicationUser()
                {
                    Id           = "4",
                    UserName     = "******",
                    Email        = "*****@*****.**",
                    PasswordHash = passwordHash.HashPassword("sportl123")
                },
                new ApplicationUser()
                {
                    Id           = "4",
                    UserName     = "******",
                    Email        = "*****@*****.**",
                    PasswordHash = passwordHash.HashPassword("profl123")
                }
            };

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

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

            foreach (var user in users)
            {
                var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));
                if (db.Users.Any(u => u.Id == user.Id))
                {
                    continue;
                }
                userManager.Create(user);
                userManager.AddToRole(user.Id, "User");
            }


            if (!db.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));
                var user        = new ApplicationUser
                {
                    Id           = "1",
                    UserName     = "******",
                    Email        = "*****@*****.**",
                    PasswordHash = passwordHash.HashPassword("admin")
                };

                userManager.Create(user);
                userManager.AddToRole(user.Id, "Admin");
            }
        }
示例#34
0
        protected override void Seed(FastBusDbContext context)
        {
            #region CreateRoles
            var roleStore   = new RoleStore <Role, int, UserRole>(context);
            var roleManager = new RoleManager <Role, int>(roleStore);
            roleManager.Create(new Role {
                Name = UserRoles.Admin, Description = UserRoles.AdminDescription
            });
            roleManager.Create(new Role {
                Name = UserRoles.Dispatcher, Description = UserRoles.DispatcherDescription
            });
            roleManager.Create(new Role {
                Name = UserRoles.Driver, Description = UserRoles.DriverDescription
            });
            roleManager.Create(new Role {
                Name = UserRoles.Buyer, Description = UserRoles.ClientDescription
            });
            context.SaveChanges();
            #endregion

            #region CreateUsers
            var userStore   = new UserStore <User, Role, int, UserLogin, UserRole, UserClaim>(context);
            var userManager = new UserManager <User, int>(userStore);

            if (!context.Users.Any(n => n.UserName == UserRoles.Admin))
            {
                var user = new User
                {
                    UserName      = UserRoles.Admin,
                    FirstName     = UserRoles.AdminDescription,
                    LastName      = UserRoles.AdminDescription,
                    RegistredDate = DateTime.Now,
                    Email         = "*****@*****.**"
                };
                userManager.Create(user, "Qq!123");
                userManager.AddToRole(user.Id, UserRoles.Admin);
            }

            if (!context.Users.Any(n => n.UserName == UserRoles.Dispatcher))
            {
                var user = new Dispatcher
                {
                    UserName      = UserRoles.Dispatcher,
                    FirstName     = "Павел",
                    LastName      = "Макаренко",
                    Patronymic    = "Иванович",
                    RegistredDate = DateTime.Now,
                    DateBorn      = DateTime.Now.AddYears(-20),
                    Email         = "*****@*****.**"
                };
                userManager.Create(user, "Qq!123");
                userManager.AddToRole(user.Id, UserRoles.Dispatcher);
            }

            context.SaveChanges();
            #endregion

            #region CreateData

            if (!context.Cars.Any())
            {
                context.Cars.AddRange(new[]
                {
                    new Car
                    {
                        GovermentNumber = "AA3338PP",
                        Year            = 1999,
                        Model           = "Audi",
                        Color           = "White",
                        Seats           = 14
                    },
                    new Car
                    {
                        GovermentNumber = "A999AA",
                        Year            = 2000,
                        Model           = "BWM",
                        Color           = "Black",
                        Seats           = 32
                    },
                    new Car
                    {
                        GovermentNumber = "08483AE",
                        Year            = 2001,
                        Model           = "Ford",
                        Color           = "Blue",
                        Seats           = 32
                    },
                    new Car
                    {
                        GovermentNumber = "019140B",
                        Year            = 2000,
                        Model           = "Volkswagen",
                        Color           = "Blue",
                        Seats           = 20
                    },
                    new Car
                    {
                        GovermentNumber = "E102CH",
                        Year            = 2003,
                        Model           = "Audi",
                        Color           = "White",
                        Seats           = 20
                    },
                    new Car
                    {
                        GovermentNumber = "C065MK",
                        Year            = 1995,
                        Model           = "Audi",
                        Color           = "Black",
                        Seats           = 14
                    }
                });
                context.SaveChanges();

                var cars = context.Cars.ToList();
                if (!context.Users.Any(n => n.UserName == UserRoles.Driver))
                {
                    var user = new Driver
                    {
                        UserName      = UserRoles.Driver,
                        FirstName     = "Мстислав",
                        LastName      = "Данилов",
                        Patronymic    = "Святославович",
                        RegistredDate = DateTime.Now,
                        DateBorn      = DateTime.Now.AddYears(-18).AddMonths(3).AddDays(15),
                        Cars          = new List <Car> {
                            cars[0], cars[1]
                        }
                    };
                    userManager.Create(user, "Qq!123");
                    userManager.AddToRole(user.Id, UserRoles.Driver);
                }

                if (!context.Users.Any(n => n.UserName == UserRoles.Driver + "2"))
                {
                    var user = new Driver
                    {
                        UserName      = UserRoles.Driver + "2",
                        FirstName     = "Елена",
                        LastName      = "Попова",
                        Patronymic    = "Лукьяновн",
                        RegistredDate = DateTime.Now,
                        DateBorn      = DateTime.Now.AddYears(-19).AddMonths(3).AddDays(7),
                        Cars          = new List <Car> {
                            cars[2], cars[3], cars[4]
                        }
                    };
                    userManager.Create(user, "Qq!123");
                    userManager.AddToRole(user.Id, UserRoles.Driver);
                }

                if (!context.Users.Any(n => n.UserName == UserRoles.Driver + "3"))
                {
                    var user = new Driver
                    {
                        UserName      = UserRoles.Driver + "3",
                        FirstName     = "Авдей",
                        LastName      = "Тарасов",
                        Patronymic    = "Авдеевич",
                        RegistredDate = DateTime.Now,
                        DateBorn      = DateTime.Now.AddYears(-21).AddMonths(11).AddDays(2),
                        Cars          = new List <Car> {
                            cars[4]
                        }
                    };
                    userManager.Create(user, "Qq!123");
                    userManager.AddToRole(user.Id, UserRoles.Driver);
                }

                context.SaveChanges();
            }

            if (!context.Routes.Any())
            {
                context.Routes.AddRange(new List <Route>
                {
                    new Route
                    {
                        Departure   = "Пункт А",
                        Destination = "Пункт Б"
                    },
                    new Route
                    {
                        Departure   = "Пункт А",
                        Destination = "Пункт С"
                    },
                    new Route
                    {
                        Departure   = "Пункт А",
                        Destination = "Пункт Д"
                    },
                    new Route
                    {
                        Departure   = "Пункт А",
                        Destination = "Пункт И"
                    },
                    new Route
                    {
                        Departure   = "Пункт А",
                        Destination = "Пункт Ф"
                    },
                    new Route
                    {
                        Departure   = "Пункт А",
                        Destination = "Пункт Т"
                    },
                    new Route
                    {
                        Departure   = "Пункт А",
                        Destination = "Пункт К"
                    },
                    new Route
                    {
                        Departure   = "Пункт Б",
                        Destination = "Пункт А"
                    },
                    new Route
                    {
                        Departure   = "Пункт С",
                        Destination = "Пункт А"
                    },
                    new Route
                    {
                        Departure   = "Пункт Д",
                        Destination = "Пункт А"
                    },
                    new Route
                    {
                        Departure   = "Пункт И",
                        Destination = "Пункт А"
                    },
                    new Route
                    {
                        Departure   = "Пункт Ф",
                        Destination = "Пункт А"
                    },
                    new Route
                    {
                        Departure   = "Пункт Т",
                        Destination = "Пункт А"
                    },
                    new Route
                    {
                        Departure   = "Пункт К",
                        Destination = "Пункт А"
                    },
                    new Route
                    {
                        Departure   = "Пункт Ф",
                        Destination = "Пункт З"
                    },
                    new Route
                    {
                        Departure   = "Пункт Ф",
                        Destination = "Пункт Т"
                    },
                    new Route
                    {
                        Departure   = "Пункт Т",
                        Destination = "Пункт З"
                    },
                    new Route
                    {
                        Departure   = "Пункт К",
                        Destination = "Пункт Ф"
                    },
                    new Route
                    {
                        Departure   = "Пункт Ф",
                        Destination = "Пункт К"
                    }
                });

                context.SaveChanges();

                var routes         = context.Routes.ToList();
                var dispatcher     = context.Dispatchers.FirstOrDefault();
                var drivers        = context.Drivers.ToList();
                var routeCars      = context.Cars.ToList();
                var currentDepDate = DateTime.Now;
                var currentDesDate = DateTime.Now.AddHours(4);
                if (dispatcher != null && drivers.Count > 2 && routeCars.Count >= 4)
                {
                    context.Schedule.AddRange(new List <ScheduleItem>
                    {
                        new ScheduleItem
                        {
                            RouteId         = routes[0].Id,
                            Number          = 1000,
                            DepartureDate   = currentDepDate,
                            DestinationDate = currentDesDate,
                            Seats           = routeCars[0].Seats,
                            CarId           = routeCars[0].Id,
                            DispatcherId    = dispatcher.Id,
                            Cost            = 100,
                            Drivers         = new List <Driver> {
                                drivers.First(x => x.Cars.Any(c => c.Id == routeCars[0].Id))
                            }
                        },
                        new ScheduleItem
                        {
                            RouteId         = routes[0].Id,
                            Number          = 1000,
                            DepartureDate   = currentDepDate.AddDays(1),
                            DestinationDate = currentDesDate.AddDays(1),
                            Seats           = routeCars[0].Seats,
                            CarId           = routeCars[0].Id,
                            DispatcherId    = dispatcher.Id,
                            Cost            = 100,
                            Drivers         = new List <Driver> {
                                drivers.First(x => x.Cars.Any(c => c.Id == routeCars[0].Id))
                            }
                        },
                        new ScheduleItem
                        {
                            RouteId         = routes[7].Id,
                            Number          = 1001,
                            DepartureDate   = currentDepDate.AddMinutes(30),
                            DestinationDate = currentDesDate.AddMinutes(30),
                            Seats           = routeCars[0].Seats,
                            CarId           = routeCars[0].Id,
                            DispatcherId    = dispatcher.Id,
                            Cost            = 100,
                            Drivers         = new List <Driver> {
                                drivers.First(x => x.Cars.Any(c => c.Id == routeCars[0].Id))
                            }
                        },
                        new ScheduleItem
                        {
                            RouteId         = routes[7].Id,
                            Number          = 1001,
                            DepartureDate   = currentDepDate.AddDays(1),
                            DestinationDate = currentDesDate.AddDays(1),
                            Seats           = routeCars[0].Seats,
                            CarId           = routeCars[0].Id,
                            DispatcherId    = dispatcher.Id,
                            Cost            = 100,
                            Drivers         = new List <Driver> {
                                drivers.First(x => x.Cars.Any(c => c.Id == routeCars[0].Id))
                            }
                        },
                        new ScheduleItem
                        {
                            RouteId         = routes[1].Id,
                            Number          = 1002,
                            DepartureDate   = currentDepDate.AddHours(2),
                            DestinationDate = currentDesDate.AddHours(3),
                            Seats           = routeCars[1].Seats,
                            CarId           = routeCars[1].Id,
                            DispatcherId    = dispatcher.Id,
                            Cost            = 90,
                            Drivers         = new List <Driver> {
                                drivers.First(x => x.Cars.Any(c => c.Id == routeCars[2].Id))
                            }
                        },
                        new ScheduleItem
                        {
                            RouteId         = routes[8].Id,
                            Number          = 1003,
                            DepartureDate   = currentDepDate.AddHours(-3),
                            DestinationDate = currentDesDate.AddHours(-3),
                            Seats           = routeCars[1].Seats,
                            CarId           = routeCars[1].Id,
                            DispatcherId    = dispatcher.Id,
                            Cost            = 95,
                            Drivers         = new List <Driver> {
                                drivers.First(x => x.Cars.Any(c => c.Id == routeCars[2].Id))
                            }
                        },
                        new ScheduleItem
                        {
                            RouteId         = routes[3].Id,
                            Number          = 1005,
                            DepartureDate   = currentDepDate,
                            DestinationDate = currentDesDate,
                            Seats           = routeCars[2].Seats,
                            CarId           = routeCars[2].Id,
                            DispatcherId    = dispatcher.Id,
                            Cost            = 100,
                            Drivers         = new List <Driver> {
                                drivers.First(x => x.Cars.Any(c => c.Id == routeCars[4].Id))
                            }
                        },
                        new ScheduleItem
                        {
                            RouteId         = routes[4].Id,
                            Number          = 1004,
                            DepartureDate   = currentDepDate.AddDays(-1),
                            DestinationDate = currentDesDate.AddDays(-1),
                            Seats           = routeCars[2].Seats,
                            CarId           = routeCars[2].Id,
                            DispatcherId    = dispatcher.Id,
                            Cost            = 100,
                            Drivers         = new List <Driver> {
                                drivers.First(x => x.Cars.Any(c => c.Id == routeCars[4].Id))
                            }
                        }
                    });
                }

                context.SaveChanges();
            }

            #endregion
        }
示例#35
0
        protected override void Seed(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" }
            //    );
            //

            #region Required
            //
            // required
            //

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


            var roleNames = new[] { RoleName.teacher, RoleName.student };
            foreach (var roleName in roleNames)
            {
                if (context.Roles.Any(r => r.Name == roleName))
                {
                    continue;
                }

                var role = new IdentityRole {
                    Name = roleName
                };
                var result = roleManager.Create(role);
                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors));
                }
            }

            var activityTypeNames = new string[, ] {
                { ActivityTypeName.exercise, ActivityTypeName.exerciseShortName },
                { ActivityTypeName.elearning, ActivityTypeName.elearningShortName },
                { ActivityTypeName.lecture, ActivityTypeName.lectureShortName }
            };
            var activityTypes = new ActivityType[activityTypeNames.GetUpperBound(0) + 1];

            for (int i = 0; i < activityTypes.Length; i++)
            {
                activityTypes[i] = new ActivityType {
                    Name = activityTypeNames[i, 0], ShortName = activityTypeNames[i, 1]
                };
            }

            context.ActivityTypes.AddOrUpdate(
                t => t.Name,
                activityTypes
                );
            context.SaveChanges();

            //
            // required
            //

            #endregion

            #region example data

            var courseCode = "ND17";
            var startDate  = new DateTime(2017, 08, 28);


            var courses = new Course[]
            {
                new Course {
                    CourseCode  = courseCode, Name = ".NET systemutveckling",
                    Description = "",
                    StartDate   = startDate, EndDate = startDate.AddMonths(4)
                },

                new Course {
                    CourseCode  = "113544-1", Name = "Certifierad programerare",
                    Description = "Utbildingen leder till at bli Certifierad programmerare. Programmeringsutbildningen gör att deltagare ska kunna upprätta program- och databasstrukturer samt programmera, implementera och underhålla system inom affärssystem, säljstödssystem, statistiksystem, bokningssystem, mm. Den studerande skall även inneha förutsättningarna för att kunna certifiera sig till MCSD: Microsoft Certified Solutions Developer.",
                    StartDate   = new DateTime(2017, 07, 31), EndDate = new DateTime(2017, 09, 29)
                },

                new Course {
                    CourseCode  = "DNV17", Name = "Systemutvecklare.NET",
                    Description = "",
                    StartDate   = new DateTime(2017, 12, 18), EndDate = new DateTime(2018, 03, 14)
                },

                new Course {
                    CourseCode  = "DNVT18", Name = "Systemutvecklare.NET",
                    Description = "",
                    StartDate   = new DateTime(2018, 02, 05), EndDate = new DateTime(2018, 05, 02)
                },

                new Course {
                    CourseCode  = "JHT17", Name = "Systemutvecklare Java",
                    Description = "",
                    StartDate   = new DateTime(2017, 09, 04), EndDate = new DateTime(2018, 01, 12)
                },

                new Course {
                    CourseCode  = "113544-2", Name = "Certifierad programerare",
                    Description = "",
                    StartDate   = new DateTime(2017, 08, 28), EndDate = new DateTime(2017, 10, 27)
                },

                new Course {
                    CourseCode  = "109522-1", Name = "IT-tekniker SharePoint/Dynamics",
                    Description = "",
                    StartDate   = new DateTime(2017, 12, 18), EndDate = new DateTime(2018, 03, 14)
                },

                new Course {
                    CourseCode  = "109522-2", Name = "IT-tekniker SharePoint/Dynamics",
                    Description = "",
                    StartDate   = new DateTime(2018, 01, 22), EndDate = new DateTime(2018, 04, 17)
                },
            };
            context.Courses.AddOrUpdate(
                c => c.CourseCode,
                courses
                );

            context.SaveChanges();

            var courseId = context.Courses.Where(c => c.CourseCode == courseCode).FirstOrDefault().Id;
            var modules  = new CourseModule[]
            {
                new CourseModule {
                    Name    = "C#", StartDate = startDate.AddDays(0),
                    EndDate = startDate.AddDays(29), CourseId = courseId
                },
                new CourseModule {
                    Name    = "Testning", StartDate = startDate.AddDays(22),
                    EndDate = startDate.AddDays(68), CourseId = courseId
                },
                new CourseModule {
                    Name    = "Webb", StartDate = startDate.AddDays(30),
                    EndDate = startDate.AddDays(53), CourseId = courseId
                },
                new CourseModule {
                    Name    = "MVC", StartDate = startDate.AddDays(45),
                    EndDate = startDate.AddDays(62), CourseId = courseId
                },
                new CourseModule {
                    Name    = "Databas", StartDate = startDate.AddDays(63),
                    EndDate = startDate.AddDays(73), CourseId = courseId
                },
                new CourseModule {
                    Name    = "App.Utv.", StartDate = startDate.AddDays(74),
                    EndDate = startDate.AddDays(82), CourseId = courseId
                },
                new CourseModule {
                    Name    = "MVC fördj", StartDate = startDate.AddDays(81),
                    EndDate = startDate.AddDays(111), CourseId = courseId
                }
            };
            context.Modules.AddOrUpdate(
                c => new { c.Name, c.StartDate },
                modules
                );

            context.SaveChanges();

            var elearningTypeId = context.ActivityTypes.Where(t => t.Name == ActivityTypeName.elearning).FirstOrDefault().Id;
            var exerciseTypeId  = context.ActivityTypes.Where(t => t.Name == ActivityTypeName.exercise).FirstOrDefault().Id;
            var lectureTypeId   = context.ActivityTypes.Where(t => t.Name == ActivityTypeName.lecture).FirstOrDefault().Id;

            var cSharpName = modules[0].Name;
            var cSharpDate = modules[0].StartDate;
            var cSharpId   = context.Modules.Where(m => m.Name == cSharpName && m.StartDate == cSharpDate).FirstOrDefault().Id;

            var testName = modules[1].Name;
            var testDate = modules[1].StartDate;
            var testId   = context.Modules.Where(m => m.Name == testName && m.StartDate == testDate).FirstOrDefault().Id;

            var webbName = modules[2].Name;
            var webbDate = modules[2].StartDate;
            var webbId   = context.Modules.Where(m => m.Name == webbName && m.StartDate == webbDate).FirstOrDefault().Id;

            var mvcName = modules[3].Name;
            var mvcDate = modules[3].StartDate;
            var mvcId   = context.Modules.Where(m => m.Name == mvcName && m.StartDate == mvcDate).FirstOrDefault().Id;

            var dbName = modules[4].Name;
            var dbDate = modules[4].StartDate;
            var dbId   = context.Modules.Where(m => m.Name == dbName && m.StartDate == dbDate).FirstOrDefault().Id;

            var appName = modules[5].Name;
            var appDate = modules[5].StartDate;
            var appId   = context.Modules.Where(m => m.Name == appName && m.StartDate == appDate).FirstOrDefault().Id;

            var mvcAdvName = modules[6].Name;
            var mvcAdvDate = modules[6].StartDate;
            var mvcAdvId   = context.Modules.Where(m => m.Name == mvcAdvName && m.StartDate == mvcAdvDate).FirstOrDefault().Id;

            var activities = new ModuleActivity[]
            {
                new ModuleActivity {
                    Name           = "Intro", Description = "",
                    StartDate      = startDate.AddDays(0), EndDate = startDate.AddDays(0),
                    ActivityTypeId = lectureTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Kapitel 1.1, 1.2", Description = "C# Fundamentals with Visual Studio 2015 med Scott Allen",
                    StartDate      = startDate.AddDays(0), EndDate = startDate.AddDays(0),
                    ActivityTypeId = elearningTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Kapitel 1.3", Description = "C# Fundamentals with Visual Studio 2015 med Scott Allen",
                    StartDate      = startDate.AddDays(1), EndDate = startDate.AddDays(1),
                    ActivityTypeId = elearningTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Kapitel 1.4 + 1.5", Description = "C# Fundamentals with Visual Studio 2015 med Scott Allen",
                    StartDate      = startDate.AddDays(1), EndDate = startDate.AddDays(1),
                    ActivityTypeId = elearningTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "C# Intro", Description = "Adrian",
                    StartDate      = startDate.AddDays(2), EndDate = startDate.AddDays(2),
                    ActivityTypeId = lectureTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Övning 2", Description = "Flow Control",
                    StartDate      = startDate.AddDays(3), EndDate = startDate.AddDays(3),
                    ActivityTypeId = exerciseTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "C# Grund", Description = "Adrian",
                    StartDate      = startDate.AddDays(4), EndDate = startDate.AddDays(4),
                    ActivityTypeId = lectureTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Kapitel 1.6 + 1.7", Description = "C# Fundamentals with Visual Studio 2015 med Scott Allen",
                    StartDate      = startDate.AddDays(7), EndDate = startDate.AddDays(7),
                    ActivityTypeId = elearningTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Kapitel 1.8", Description = "C# Fundamentals with Visual Studio 2015 med Scott Allen",
                    StartDate      = startDate.AddDays(7), EndDate = startDate.AddDays(7),
                    ActivityTypeId = elearningTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Kapitel 1.7 + 1.8", Description = "C# Fundamentals with Visual Studio 2015 med Scott Allen",
                    StartDate      = startDate.AddDays(8), EndDate = startDate.AddDays(8),
                    ActivityTypeId = elearningTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Övning 2", Description = "Flow Control",
                    StartDate      = startDate.AddDays(8), EndDate = startDate.AddDays(8),
                    ActivityTypeId = exerciseTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Repition", Description = "",
                    StartDate      = startDate.AddDays(8), EndDate = startDate.AddDays(8),
                    ActivityTypeId = exerciseTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "OOP", Description = "Adrian",
                    StartDate      = startDate.AddDays(9), EndDate = startDate.AddDays(9),
                    ActivityTypeId = lectureTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Övning 3", Description = " Inkapsling, arv och polymorfism Nytt utkast",
                    StartDate      = startDate.AddDays(10), EndDate = startDate.AddDays(10),
                    ActivityTypeId = exerciseTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "OOP 2", Description = "Adrian",
                    StartDate      = startDate.AddDays(11), EndDate = startDate.AddDays(11),
                    ActivityTypeId = lectureTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Övning 3", Description = " Inkapsling, arv och polymorfism Nytt utkast",
                    StartDate      = startDate.AddDays(14), EndDate = startDate.AddDays(14),
                    ActivityTypeId = exerciseTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Kapitel 2.1 - 2.4", Description = "",
                    StartDate      = startDate.AddDays(15), EndDate = startDate.AddDays(15),
                    ActivityTypeId = elearningTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Övning 4", Description = "",
                    StartDate      = startDate.AddDays(15), EndDate = startDate.AddDays(15),
                    ActivityTypeId = exerciseTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Generics", Description = "Adrian",
                    StartDate      = startDate.AddDays(21), EndDate = startDate.AddDays(21),
                    ActivityTypeId = lectureTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "LINQ", Description = "Adrian",
                    StartDate      = startDate.AddDays(21), EndDate = startDate.AddDays(21),
                    ActivityTypeId = lectureTypeId,
                    CourseModuleId = cSharpId
                },

                new ModuleActivity {
                    Name           = "Unit Test", Description = "C# Best Practices: Improving on the Basics med Deborah Kurata",
                    StartDate      = startDate.AddDays(22), EndDate = startDate.AddDays(22),
                    ActivityTypeId = elearningTypeId,
                    CourseModuleId = testId
                },

                new ModuleActivity {
                    Name           = "Sprint review 3", Description = "Slutprojekt",
                    StartDate      = startDate.AddDays(107), EndDate = startDate.AddDays(107),
                    ActivityTypeId = exerciseTypeId,
                    CourseModuleId = mvcAdvId
                },

                new ModuleActivity {
                    Name           = "Projekt slutfas", Description = "Slutprojekt",
                    StartDate      = startDate.AddDays(108), EndDate = startDate.AddDays(108),
                    ActivityTypeId = exerciseTypeId,
                    CourseModuleId = mvcAdvId
                },

                new ModuleActivity {
                    Name           = "Slutredovisning", Description = "Slutprojekt",
                    StartDate      = startDate.AddDays(109), EndDate = startDate.AddDays(109),
                    ActivityTypeId = exerciseTypeId,
                    CourseModuleId = mvcAdvId
                },

                new ModuleActivity {
                    Name           = "Avslutning", Description = "",
                    StartDate      = startDate.AddDays(109), EndDate = startDate.AddDays(109),
                    ActivityTypeId = exerciseTypeId,
                    CourseModuleId = mvcAdvId
                },


                new ModuleActivity {
                    Name = "Generics", Description = "", StartDate = startDate.AddDays(16), EndDate = startDate.AddDays(16), ActivityTypeId = lectureTypeId, CourseModuleId = cSharpId
                },
                new ModuleActivity {
                    Name = "Kapitel 2.5 – 2.6", Description = "", StartDate = startDate.AddDays(17), EndDate = startDate.AddDays(17), ActivityTypeId = elearningTypeId, CourseModuleId = cSharpId
                },
                new ModuleActivity {
                    Name = "Övning 4", Description = "", StartDate = startDate.AddDays(17), EndDate = startDate.AddDays(17), ActivityTypeId = exerciseTypeId, CourseModuleId = cSharpId
                },
                new ModuleActivity {
                    Name = "Kapitel 2.7 – 2.9", Description = "", StartDate = startDate.AddDays(18), EndDate = startDate.AddDays(18), ActivityTypeId = elearningTypeId, CourseModuleId = cSharpId
                },
                new ModuleActivity {
                    Name = "Övning 4", Description = "", StartDate = startDate.AddDays(18), EndDate = startDate.AddDays(18), ActivityTypeId = exerciseTypeId, CourseModuleId = cSharpId
                },
                new ModuleActivity {
                    Name = "Ariktektur", Description = "", StartDate = startDate.AddDays(23), EndDate = startDate.AddDays(23), ActivityTypeId = lectureTypeId, CourseModuleId = cSharpId
                },
                new ModuleActivity {
                    Name = "Test", Description = "", StartDate = startDate.AddDays(23), EndDate = startDate.AddDays(23), ActivityTypeId = lectureTypeId, CourseModuleId = cSharpId
                },
                new ModuleActivity {
                    Name = "Övning Garage 1.0", Description = "", StartDate = startDate.AddDays(24), EndDate = startDate.AddDays(25), ActivityTypeId = exerciseTypeId, CourseModuleId = cSharpId
                },
                new ModuleActivity {
                    Name = "Övning Garage 1.0", Description = "", StartDate = startDate.AddDays(28), EndDate = startDate.AddDays(29), ActivityTypeId = exerciseTypeId, CourseModuleId = cSharpId
                },
                new ModuleActivity {
                    Name = "Redovisning", Description = "", StartDate = startDate.AddDays(29), EndDate = startDate.AddDays(29), ActivityTypeId = exerciseTypeId, CourseModuleId = cSharpId
                },
                new ModuleActivity {
                    Name = "E-L: 3 + 4.1-4.3", Description = "", StartDate = startDate.AddDays(30), EndDate = startDate.AddDays(30), ActivityTypeId = elearningTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "Övning HTML", Description = "", StartDate = startDate.AddDays(30), EndDate = startDate.AddDays(30), ActivityTypeId = exerciseTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "E-L: 4.4-4.5", Description = "", StartDate = startDate.AddDays(31), EndDate = startDate.AddDays(31), ActivityTypeId = elearningTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "Övning CSS", Description = "", StartDate = startDate.AddDays(31), EndDate = startDate.AddDays(31), ActivityTypeId = exerciseTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "Html/Css", Description = "", StartDate = startDate.AddDays(32), EndDate = startDate.AddDays(32), ActivityTypeId = lectureTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "JavaScript CodeSchool", Description = "", StartDate = startDate.AddDays(35), EndDate = startDate.AddDays(35), ActivityTypeId = elearningTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "E-L: 5.1 – 5.3", Description = "", StartDate = startDate.AddDays(36), EndDate = startDate.AddDays(36), ActivityTypeId = elearningTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "E-L: 5.3 – 5.5", Description = "", StartDate = startDate.AddDays(36), EndDate = startDate.AddDays(36), ActivityTypeId = elearningTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "JS", Description = "", StartDate = startDate.AddDays(37), EndDate = startDate.AddDays(37), ActivityTypeId = lectureTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "Övning JS", Description = "", StartDate = startDate.AddDays(37), EndDate = startDate.AddDays(37), ActivityTypeId = lectureTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "Övning JS", Description = "", StartDate = startDate.AddDays(38), EndDate = startDate.AddDays(38), ActivityTypeId = elearningTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "Kapitel 6 Bootstrap", Description = "", StartDate = startDate.AddDays(39), EndDate = startDate.AddDays(39), ActivityTypeId = elearningTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "Övning Bootstrap", Description = "", StartDate = startDate.AddDays(42), EndDate = startDate.AddDays(43), ActivityTypeId = exerciseTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "ASP.NET MVC", Description = "", StartDate = startDate.AddDays(44), EndDate = startDate.AddDays(44), ActivityTypeId = lectureTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "Kapitel 7.1 – 7.3", Description = "", StartDate = startDate.AddDays(45), EndDate = startDate.AddDays(45), ActivityTypeId = elearningTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "MVC", Description = "", StartDate = startDate.AddDays(46), EndDate = startDate.AddDays(46), ActivityTypeId = lectureTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "Kapitel 7.4 ", Description = "", StartDate = startDate.AddDays(49), EndDate = startDate.AddDays(49), ActivityTypeId = elearningTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "Kapitel 7.5 + Övn MVC ", Description = "", StartDate = startDate.AddDays(49), EndDate = startDate.AddDays(49), ActivityTypeId = elearningTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "E-L Repetition + Övn ", Description = "", StartDate = startDate.AddDays(50), EndDate = startDate.AddDays(50), ActivityTypeId = elearningTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "Kapitel 7.6 + Övn ", Description = "", StartDate = startDate.AddDays(50), EndDate = startDate.AddDays(50), ActivityTypeId = elearningTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "Git ", Description = "", StartDate = startDate.AddDays(51), EndDate = startDate.AddDays(51), ActivityTypeId = lectureTypeId, CourseModuleId = webbId
                },
                new ModuleActivity {
                    Name = "E-L Repetition + Övn ", Description = "", StartDate = startDate.AddDays(52), EndDate = startDate.AddDays(52), ActivityTypeId = elearningTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "7.6 + Övn ", Description = "", StartDate = startDate.AddDays(52), EndDate = startDate.AddDays(52), ActivityTypeId = elearningTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "ViewModel ", Description = "", StartDate = startDate.AddDays(53), EndDate = startDate.AddDays(53), ActivityTypeId = lectureTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "PartialView ", Description = "", StartDate = startDate.AddDays(53), EndDate = startDate.AddDays(53), ActivityTypeId = lectureTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "Övning Garage 2.0 ", Description = "", StartDate = startDate.AddDays(56), EndDate = startDate.AddDays(59), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "Redovisning ", Description = "", StartDate = startDate.AddDays(59), EndDate = startDate.AddDays(59), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcId
                },
                new ModuleActivity {
                    Name = "Datamodellering ", Description = "", StartDate = startDate.AddDays(60), EndDate = startDate.AddDays(60), ActivityTypeId = lectureTypeId, CourseModuleId = dbId
                },
                new ModuleActivity {
                    Name = "Övning 13 ", Description = "", StartDate = startDate.AddDays(60), EndDate = startDate.AddDays(60), ActivityTypeId = exerciseTypeId, CourseModuleId = dbId
                },
                new ModuleActivity {
                    Name = "EntityFramework ", Description = "", StartDate = startDate.AddDays(63), EndDate = startDate.AddDays(63), ActivityTypeId = lectureTypeId, CourseModuleId = dbId
                },
                new ModuleActivity {
                    Name = "SQLBolt.com ", Description = "", StartDate = startDate.AddDays(64), EndDate = startDate.AddDays(64), ActivityTypeId = elearningTypeId, CourseModuleId = dbId
                },
                new ModuleActivity {
                    Name = "Test MVC ", Description = "", StartDate = startDate.AddDays(65), EndDate = startDate.AddDays(65), ActivityTypeId = lectureTypeId, CourseModuleId = testId
                },
                new ModuleActivity {
                    Name = "Continuous intergration", Description = "", StartDate = startDate.AddDays(65), EndDate = startDate.AddDays(65), ActivityTypeId = lectureTypeId, CourseModuleId = testId
                },
                new ModuleActivity {
                    Name = "Garage 2.5 ", Description = "", StartDate = startDate.AddDays(66), EndDate = startDate.AddDays(67), ActivityTypeId = exerciseTypeId, CourseModuleId = dbId
                },
                new ModuleActivity {
                    Name = "Garage 2.5 ", Description = "", StartDate = startDate.AddDays(70), EndDate = startDate.AddDays(71), ActivityTypeId = exerciseTypeId, CourseModuleId = cSharpId
                },
                new ModuleActivity {
                    Name = "Kapitel 10", Description = "", StartDate = startDate.AddDays(71), EndDate = startDate.AddDays(71), ActivityTypeId = elearningTypeId, CourseModuleId = appId
                },
                new ModuleActivity {
                    Name = "Övn UX ", Description = "", StartDate = startDate.AddDays(71), EndDate = startDate.AddDays(71), ActivityTypeId = exerciseTypeId, CourseModuleId = appId
                },
                new ModuleActivity {
                    Name = "UX ", Description = "", StartDate = startDate.AddDays(72), EndDate = startDate.AddDays(72), ActivityTypeId = lectureTypeId, CourseModuleId = appId
                },
                new ModuleActivity {
                    Name = "Övning 16 ", Description = "", StartDate = startDate.AddDays(72), EndDate = startDate.AddDays(72), ActivityTypeId = exerciseTypeId, CourseModuleId = appId
                },
                new ModuleActivity {
                    Name = "Jquery CodeSchool ", Description = "", StartDate = startDate.AddDays(73), EndDate = startDate.AddDays(73), ActivityTypeId = elearningTypeId, CourseModuleId = appId
                },
                new ModuleActivity {
                    Name = "Jquery/Ajax ", Description = "", StartDate = startDate.AddDays(74), EndDate = startDate.AddDays(74), ActivityTypeId = lectureTypeId, CourseModuleId = appId
                },
                new ModuleActivity {
                    Name = "Identity ", Description = "", StartDate = startDate.AddDays(77), EndDate = startDate.AddDays(77), ActivityTypeId = lectureTypeId, CourseModuleId = appId
                },
                new ModuleActivity {
                    Name = "Kapitel 12 MVC ", Description = "", StartDate = startDate.AddDays(78), EndDate = startDate.AddDays(78), ActivityTypeId = elearningTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Övning 17 ", Description = "", StartDate = startDate.AddDays(78), EndDate = startDate.AddDays(78), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Client vs. Server ", Description = "", StartDate = startDate.AddDays(79), EndDate = startDate.AddDays(79), ActivityTypeId = lectureTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Kapitel 12 MVC ", Description = "", StartDate = startDate.AddDays(80), EndDate = startDate.AddDays(80), ActivityTypeId = elearningTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Övning 17 ", Description = "", StartDate = startDate.AddDays(80), EndDate = startDate.AddDays(80), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "SCRUM ", Description = "", StartDate = startDate.AddDays(81), EndDate = startDate.AddDays(81), ActivityTypeId = lectureTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Projektplanering ", Description = "", StartDate = startDate.AddDays(84), EndDate = startDate.AddDays(85), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Projektstart ", Description = "", StartDate = startDate.AddDays(86), EndDate = startDate.AddDays(86), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Planering sprint 1 ", Description = "", StartDate = startDate.AddDays(86), EndDate = startDate.AddDays(86), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Projekt sprint 1", Description = "", StartDate = startDate.AddDays(87), EndDate = startDate.AddDays(88), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Projekt sprint 1", Description = "", StartDate = startDate.AddDays(91), EndDate = startDate.AddDays(92), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Sprint review 1", Description = "", StartDate = startDate.AddDays(93), EndDate = startDate.AddDays(93), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Planering sprint 2 ", Description = "", StartDate = startDate.AddDays(93), EndDate = startDate.AddDays(93), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Projekt sprint 2", Description = "", StartDate = startDate.AddDays(94), EndDate = startDate.AddDays(95), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Projekt sprint 2", Description = "", StartDate = startDate.AddDays(98), EndDate = startDate.AddDays(99), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Sprint review 2", Description = "", StartDate = startDate.AddDays(100), EndDate = startDate.AddDays(100), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Planering sprint 3", Description = "", StartDate = startDate.AddDays(100), EndDate = startDate.AddDays(100), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Projekt sprint 3", Description = "", StartDate = startDate.AddDays(101), EndDate = startDate.AddDays(102), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
                new ModuleActivity {
                    Name = "Projekt sprint 3", Description = "", StartDate = startDate.AddDays(105), EndDate = startDate.AddDays(106), ActivityTypeId = exerciseTypeId, CourseModuleId = mvcAdvId
                },
            };

            context.Activities.AddOrUpdate(
                a => new { a.Name, a.CourseModuleId, a.StartDate, a.EndDate, a.Description },
                activities
                );
            context.SaveChanges();


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

            var users = new List <string[]>();
            users.Add(new[] { "*****@*****.**", "Learny", "Tomas Svensson", RoleName.teacher });
            users.Add(new[] { "*****@*****.**", "Learny", "Klas Klättermus", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Abas Ali Rahmanian Aberouie", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Afram Kako", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Archana Chikmagalur Lakshminarasimha", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Christian Trochez Östnaes", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Christopher Wolf", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Daniel Saar Odhammer", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Egidio Palmo Ricchiuti", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Gunnar Rydberg", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Hans Guldager", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "James Allen", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "John Alkas Yousef", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Juha Kuusjärvi", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Lars Börlin", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Linus Alpsten", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Nils Lindstedt", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Ola Bjelving", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Petra Lindell", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Rolf Lundqvist", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Sattar Alvandpour", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Tensaeberhan Mengist Yoseph", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Thomas Palestig", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Tomas Lanquist", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Vijayalakshmi Goduguluri", RoleName.student });
            users.Add(new[] { "*****@*****.**", "Learny", "Zareen Pathan", RoleName.student });

            foreach (var user in users)
            {
                var userUserName = user[0];
                var userEmail    = user[0];
                var userPassword = user[1];
                var userName     = user[2];
                var userRole     = user[3];

                if (context.Users.Any(u => u.UserName == userUserName))
                {
                    continue;
                }

                var newUser = new ApplicationUser {
                    UserName = userUserName, Email = userEmail, Name = userName
                };
                if (userRole == RoleName.student)
                {
                    newUser.CourseId = courseId;
                }

                var result = userManager.Create(newUser, userPassword);
                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors));
                }

                //Add role
                var existingUser = userManager.FindByName(userUserName);
                if (!userManager.IsInRole(existingUser.Id, userRole))
                {
                    userManager.AddToRole(existingUser.Id, userRole);
                }
            }

            #endregion
        }
示例#36
0
        public static void Seed(MedSimDbContext context)
        {
#if !DEBUG
            throw new NotImplementedException("this should not be being used in a production environment - security changes required");
#endif
            try
            {
                if (!context.Roles.Any())
                {
                    //not in production
                    //context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction,
                    //    "alter database [" + context.Database.Connection.Database + "] set single_user with rollback immediate");
                    //
                    var roleStore   = new RoleStore <AspNetRole, Guid, AspNetUserRole>(context);
                    var roleManager = new RoleManager <AspNetRole, Guid>(roleStore);
                    var role        = new AspNetRole
                    {
                        Id   = Guid.NewGuid(),
                        Name = RoleConstants.Admin
                    };
                    roleManager.Create(role);
                }

                if (!context.Users.Any())
                {
                    var userStore   = new CustomUserStore(context);
                    var userManager = new ApplicationUserManager(userStore);

                    var user = new AspNetUser
                    {
                        Email    = "*****@*****.**",
                        UserName = "******"
                    };
                    var result = userManager.Create(user, password: "******");
                    if (result.Succeeded)
                    {
                        userManager.AddToRole(user.Id, RoleConstants.Admin);
                    }
                    else
                    {
                        throw new DbSeedException(result.Errors);
                    }
                }
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                                    .SelectMany(x => x.ValidationErrors)
                                    .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
        }
示例#37
0
        protected override void Seed(WARG.Models.ApplicationDbContext context)
        {
            var store   = new RoleStore <IdentityRole>(context);
            var manager = new RoleManager <IdentityRole>(store);

            if (!context.Roles.Any(r => r.Name == "Administracion"))
            {
                var role = new IdentityRole {
                    Name = "Administracion"
                };
                manager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name == "Cobranzas"))
            {
                var role = new IdentityRole {
                    Name = "Cobranzas"
                };
                manager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name == "Comercial"))
            {
                var role = new IdentityRole {
                    Name = "Comercial"
                };
                manager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name == "Contabilidad"))
            {
                var role = new IdentityRole {
                    Name = "Contabilidad"
                };
                manager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name == "Compras"))
            {
                var role = new IdentityRole {
                    Name = "Compras"
                };
                manager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name == "Registros"))
            {
                var role = new IdentityRole {
                    Name = "Registros"
                };
                manager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name == "Sistemas"))
            {
                var role = new IdentityRole {
                    Name = "Sistemas"
                };
                manager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name == "PostVenta"))
            {
                var role = new IdentityRole {
                    Name = "PostVenta"
                };
                manager.Create(role);
            }
        }
示例#38
0
        //public IHttpActionResult GetClientWithAspNetUserId(string clientId)
        //{
        //    try
        //    {
        //        using (MaxMasterDbEntities db = new MaxMasterDbEntities())
        //        {
        //            var client = db.Clients.Where(x => x.AspNetUserId == clientId).Select(x => new { value = x.AspNetUserId, label = x.ShortName }).FirstOrDefault();
        //            return Content(HttpStatusCode.OK, new { client });
        //        }
        //    }
        //    catch(Exception ex)
        //    {
        //        return Content(HttpStatusCode.InternalServerError, "An error occured, please try again later");
        //    }
        //}

        public async Task <IHttpActionResult> AddClientWithPwd()
        {
            try
            {
                UserManager <ApplicationUser> userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form            = HttpContext.Current.Request.Form;
                    var clientLocations = JsonConvert.DeserializeObject <List <ClientLocationModel> >(form.Get("ClientLocations"));
                    var email           = form.Get("Email");
                    var password        = form.Get("password");
                    var userName        = form.Get("userName");

                    var user1 = userManager.FindByEmail(email);
                    if (user1 != null)
                    {
                        return(Content(HttpStatusCode.InternalServerError, "User with email " + email + " already exists"));
                    }

                    var exsistingUser = await _userManager.FindByNameAsync(userName);

                    if (exsistingUser != null)
                    {
                        return(Content(HttpStatusCode.InternalServerError, "User with user name " + userName + " already exists"));
                    }

                    Client client = new Client();

                    client.OrgId        = Convert.ToInt32(form.Get("Organisation"));
                    client.Name         = form.Get("Name");
                    client.ShortName    = form.Get("ShortName");
                    client.Email        = email;
                    client.PrimaryPhone = form.Get("PrimaryPhone");

                    for (int i = 0; i < clientLocations.Count; i++)
                    {
                        ClientLocation clientloc = new ClientLocation();
                        clientloc.AddressLine1     = clientLocations[i].AddressLine1;
                        clientloc.AddressLine2     = clientLocations[i].AddressLine2;
                        clientloc.Landmark         = clientLocations[i].Landmark;
                        clientloc.Country_Id       = clientLocations[i].Country;
                        clientloc.State_Id         = clientLocations[i].State;
                        clientloc.City_Id          = clientLocations[i].City;
                        clientloc.ZIP              = clientLocations[i].zip;
                        clientloc.TimeZone_Id      = clientLocations[i].TimeZone;
                        clientloc.IsInvoiceAddress = clientLocations[i].IsInvoice;
                        clientloc.Client_Id        = client.Id;

                        client.ClientLocations.Add(clientloc);
                    }

                    ApplicationUser user = new ApplicationUser()
                    {
                        UserName = userName, Email = email
                    };

                    _userManager.UserValidator = new UserValidator <ApplicationUser>(_userManager)
                    {
                        AllowOnlyAlphanumericUserNames = false,
                        RequireUniqueEmail             = true
                    };
                    IdentityResult result = _userManager.Create(user, password);

                    if (!result.Succeeded)
                    {
                        return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
                    }

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

                    _userManager.AddToRole(user.Id, "Client");

                    string to      = email;
                    string subject = "Welcome to Max Trans Systems";
                    string body    = "Hi,Welcome to Max Trans Systems. Following are the credentials for your account" +
                                     Environment.NewLine + "Username : "******"Password : "******"*****@*****.**";

                    var sendMail = new EmailController().SendEmail(from, "Max", email, subject, body);

                    client.AspNetUserId = user.Id;
                    client.Active       = true;
                    client.LastUpdated  = DateTime.Now;
                    client.UpdatedBy    = User.Identity.GetUserId();
                    client.ClientType   = "Direct Client";

                    db.Clients.Add(client);
                    db.SaveChanges();
                }

                return(Ok());
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occoured, please try again!"));
            }
        }
示例#39
0
        protected override void Seed(BugTracker.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" }
            //    );
            //
            //   context.Roles.Add(new IdentityRole { Name = "Admin" });
            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 == "Project Manager"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "Project Manager"
                };

                manager.Create(role);
            }


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

                manager.Create(role);
            }


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

                manager.Create(role);
            }

            // Create a new application user object (AspNetUsers entry)
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Satya",
                    LastName    = "Nayak",
                    DisplayName = "SN",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "SatyaAvtar",
                    LastName    = "NNNN",
                    DisplayName = "Avtar",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Blink",
                    LastName    = "Flash",
                    DisplayName = "Blink",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Jerry",
                    LastName    = "Seinfeld",
                    DisplayName = "JEeerryy",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }


            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Fat",
                    LastName    = "Newman",
                    DisplayName = "New",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }


            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Cosmo",
                    LastName    = "Kramer",
                    DisplayName = "Cosmos",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }


            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Elane",
                    LastName    = "Benese",
                    DisplayName = "EB",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }

            var projects = new List <Project> {
                new Project {
                    Name = "The Big Lebowski"
                },
                new Project {
                    Name = "Peterkin"
                },
                new Project {
                    Name = "Ferris"
                },
                new Project {
                    Name = "Newman"
                },
                new Project {
                    Name = "Kramer"
                }
            };

            if (!context.Projects.Any(r => r.Name == "The Big Lebowski"))
            {
                projects.ForEach(p => context.Projects.Add(p));
                context.SaveChanges();
            }



            var userId = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userId, "Admin");
            userManager.AddToRole(userId, "Developer");


            // Commented out Used in Database First design to assign
            // local user btUser aspNetUserId to aspnetUserId (nvarchar(50))
            //// Create BtUsers entry to match the AspNetUsers entry
            //var bt = new BugTrackerEntities();
            //if(!(bt.BTUsers.Any(u => u.AspNetUserId == userId)))
            //{
            //    var btUser = new BTUser();
            //    btUser.AspNetUserId = userId;
            //    btUser.FirstName = "Satya";
            //    btUser.LastName = "Nayak";
            //    bt.BTUsers.Add(btUser);
            //    bt.SaveChanges();
            //}

            var project  = context.Projects.Single(p => p.Name == "The Big Lebowski").Id;
            var project2 = context.Projects.Single(p => p.Name == "Peterkin").Id;
            var project3 = context.Projects.Single(p => p.Name == "Ferris").Id;
            var project4 = context.Projects.Single(p => p.Name == "Newman").Id;
            var project5 = context.Projects.Single(p => p.Name == "Kramer").Id;


            var ticketType1 = "Bug";
            var ticketType2 = "Feature Request";
            var ticketType3 = "Improvement";


            var ticketStatus1 = "In progress";
            var ticketStatus2 = "Not Assigned";
            var ticketStatus3 = "Closed";

            var ticketPriority1 = "Low";
            var ticketPriority2 = "Medium";
            var ticketPriority3 = "High";


            var tickets = new List <Ticket>
            {
                new Ticket
                {
                    Title            = "Search is broken",
                    Description      = "The search never returns results",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = project,
                    TicketType       = ticketType1,
                    TicketStatus     = ticketStatus1,
                    TicketPriority   = ticketPriority1,
                    OwnerUserId      = userId,
                    AssignedToUserId = userId
                },

                new Ticket {
                    Title            = "Can't attach a file to a ticket",
                    Description      = "I get an error undefined everytinme",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = project2,
                    TicketType       = ticketType2,
                    TicketStatus     = ticketStatus3,
                    TicketPriority   = ticketPriority1,
                    OwnerUserId      = userId,
                    AssignedToUserId = userId
                },
                new Ticket {
                    Title            = "Can't reassign a ticket",
                    Description      = "The drop down of users doesn't populate",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = project3,
                    TicketType       = ticketType3,
                    TicketStatus     = ticketStatus1,
                    TicketPriority   = ticketPriority2,
                    OwnerUserId      = userId,
                    AssignedToUserId = userId
                },
                new Ticket {
                    Title            = "Can't change status of a ticket",
                    Description      = "Error every time",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = project4,
                    TicketType       = ticketType2,
                    TicketStatus     = ticketStatus2,
                    TicketPriority   = ticketPriority2,
                    OwnerUserId      = userId,
                    AssignedToUserId = userId
                },
                new Ticket {
                    Title            = "Can't create a new project",
                    Description      = "Validation error",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = project5,
                    TicketType       = ticketType1,
                    TicketStatus     = ticketStatus1,
                    TicketPriority   = ticketPriority1,
                    OwnerUserId      = userId,
                    AssignedToUserId = userId
                },
                new Ticket {
                    Title            = "Can't assign users to a ticket",
                    Description      = "Drop down list doesn't populate",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = project5,
                    TicketType       = ticketType3,
                    TicketStatus     = ticketStatus1,
                    TicketPriority   = ticketPriority2,
                    OwnerUserId      = userId,
                    AssignedToUserId = userId
                },
                new Ticket {
                    Title            = "Sorting of rows not working",
                    Description      = "When you click on a row nothing happens",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = project4,
                    TicketType       = ticketType2,
                    TicketStatus     = ticketStatus3,
                    TicketPriority   = ticketPriority2,
                    OwnerUserId      = userId,
                    AssignedToUserId = userId
                },
                new Ticket {
                    Title            = "Create new ticket",
                    Description      = "Need a textarea for description",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = project3,
                    TicketType       = ticketType2,
                    TicketStatus     = ticketStatus3,
                    TicketPriority   = ticketPriority3,
                    OwnerUserId      = userId,
                    AssignedToUserId = userId
                },
                new Ticket {
                    Title            = "Timestamps are editable",
                    Description      = "Really? How convenient",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = project2,
                    TicketType       = ticketType1,
                    TicketStatus     = ticketStatus3,
                    TicketPriority   = ticketPriority1,
                    OwnerUserId      = userId,
                    AssignedToUserId = userId
                },
                new Ticket {
                    Title            = "Save after editing broken",
                    Description      = "More validation errors",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = project,
                    TicketType       = ticketType2,
                    TicketStatus     = ticketStatus1,
                    TicketPriority   = ticketPriority1,
                    OwnerUserId      = userId,
                    AssignedToUserId = userId
                }
            };

            if (!context.Tickets.Any(r => r.ProjectId == project))
            {
                tickets.ForEach(t => context.Tickets.Add(t));
                context.SaveChanges();
            }
        }
示例#40
0
        public static ApplicationRoleManager Create(IdentityFactoryOptions <ApplicationRoleManager> options, IOwinContext context)
        {
            var roleStore = new RoleStore <IdentityRole>(context.Get <ApplicationDbContext>());

            return(new ApplicationRoleManager(roleStore));
        }
示例#41
0
 public ApplicationRoleManager(RoleStore <ApplicationRole> store)
     : base(store)
 {
 }
示例#42
0
        protected override void Seed(IdentityDataContext context)
        {
            //rolleri

            if (!context.Roles.Any(i => i.Name == "admin"))
            {
                var store = new RoleStore <ApplicationRole>(context);

                var manage = new RoleManager <ApplicationRole>(store);

                var role = new ApplicationRole()
                {
                    Name = "admin", Description = "admin rolü"
                };

                manage.Create(role);
            }
            if (!context.Roles.Any(i => i.Name == "user"))
            {
                var store = new RoleStore <ApplicationRole>(context);

                var manage = new RoleManager <ApplicationRole>(store);

                var role = new ApplicationRole()
                {
                    Name = "user", Description = "user rolü"
                };

                manage.Create(role);
            }
            if (!context.Users.Any(i => i.Name == "berkakkavak"))
            {
                var store = new UserStore <ApplicationUser>(context);

                var manager = new UserManager <ApplicationUser>(store);

                var user = new ApplicationUser()
                {
                    Name = "berk", Surname = "akkavak", UserName = "******", Email = "*****@*****.**"
                };

                manager.Create(user, "1234567");
                manager.AddToRole(user.Id, "admin");
                manager.AddToRole(user.Id, "user");
            }
            if (!context.Users.Any(i => i.Name == "gamzeakkavak"))
            {
                var store = new UserStore <ApplicationUser>(context);

                var manager = new UserManager <ApplicationUser>(store);

                var user = new ApplicationUser()
                {
                    Name = "gamze", Surname = "akkavak", UserName = "******", Email = "*****@*****.**"
                };

                manager.Create(user, "1234567");
                manager.AddToRole(user.Id, "user");
            }


            //user
            base.Seed(context);
        }
示例#43
0
        protected override void Seed(LearningSystemContext context)
        {
            if (!context.Roles.Any(role => role.Name == "Student"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole("Student");
                manager.Create(role);
            }

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

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

            if (!context.Roles.Any(role => role.Name == "BlogAuthor"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole("BlogAuthor");
                manager.Create(role);
            }
            context.Courses.AddOrUpdate(course => course.Name, new Course[]
            {
                new Course()
                {
                    Name        = "Programming basics - March 2016",
                    Description = "Description",
                    StartDate   = new DateTime(2016, 03, 23),
                    EndDate     = new DateTime(2016, 05, 23)
                },
                new Course()
                {
                    Name        = "Software technologies",
                    Description = "Description",
                    StartDate   = new DateTime(2017, 03, 23),
                    EndDate     = new DateTime(2017, 05, 23)
                },
                new Course()
                {
                    Name        = "Arduino controllers",
                    Description = "Description",
                    StartDate   = new DateTime(2016, 02, 14),
                    EndDate     = new DateTime(2016, 03, 20)
                },
                new Course()
                {
                    Name        = "Cake making",
                    Description = "Description",
                    StartDate   = new DateTime(2016, 01, 01),
                    EndDate     = new DateTime(2016, 01, 23)
                },
                new Course()
                {
                    Name        = "Cockies making",
                    Description = "Description",
                    StartDate   = new DateTime(2016, 05, 19),
                    EndDate     = new DateTime(2016, 06, 01)
                }
            });
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email,
                    Email    = model.Email,
                    School   = model.School,
                    Country  = model.Country,
                    State    = model.State,
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var roleStore   = new RoleStore <IdentityRole>(new ApplicationDbContext());
                    var RoleManager = new RoleManager <IdentityRole>(roleStore);
                    await RoleManager.CreateAsync(new IdentityRole("Admin"));

                    await RoleManager.CreateAsync(new IdentityRole("Teacher"));

                    await RoleManager.CreateAsync(new IdentityRole("Student"));

                    if (model.RoleId == 1)
                    {
                        await UserManager.AddToRoleAsync(user.Id, "Admin");

                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

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

                        return(RedirectToAction("Admin", "Home"));
                    }

                    if (model.RoleId == 2)
                    {
                        await UserManager.AddToRoleAsync(user.Id, "Teacher");

                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

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

                        return(RedirectToAction("Teacher", "Home"));
                    }

                    if (model.RoleId == 3)
                    {
                        await UserManager.AddToRoleAsync(user.Id, "Student");

                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

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

                        return(RedirectToAction("Student", "Home"));
                    }
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#45
0
        protected override void Seed(BluePumpkinn.DAL.Context context)
        {
            if (!context.Roles.Any())
            {
                var roleStore   = new RoleStore <IdentityRole>(context);
                var roleManager = new RoleManager <IdentityRole>(roleStore);

                var role1 = new IdentityRole
                {
                    Name = "Administrator"
                };
                roleManager.CreateAsync(role1).Wait();

                var role2 = new IdentityRole
                {
                    Name = "Employee"
                };
                roleManager.CreateAsync(role2).Wait();
            }



            if (!context.Users.Any())
            {
                var userStore   = new UserStore <ApplicationUser>(context);
                var userManager = new ApplicationUserManager(userStore);

                System.IO.FileStream file1 = new System.IO.FileStream(@"C:\Users\toth\Desktop\zamestnaci_jednotna_velkost\jenn-hudson.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] data1 = new byte[file1.Length];
                file1.Read(data1, 0, data1.Length);
                file1.Close();

                System.IO.FileStream file2 = new System.IO.FileStream(@"C:\Users\toth\Desktop\zamestnaci_jednotna_velkost\lewis-c-morel.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] data2 = new byte[file2.Length];
                file2.Read(data2, 0, data2.Length);
                file2.Close();

                System.IO.FileStream file3 = new System.IO.FileStream(@"C:\Users\toth\Desktop\zamestnaci_jednotna_velkost\desirae-young.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] data3 = new byte[file3.Length];
                file3.Read(data3, 0, data3.Length);
                file3.Close();

                System.IO.FileStream file4 = new System.IO.FileStream(@"C:\Users\toth\Desktop\zamestnaci_jednotna_velkost\john-g-winn.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] data4 = new byte[file4.Length];
                file4.Read(data4, 0, data4.Length);
                file4.Close();

                System.IO.FileStream file5 = new System.IO.FileStream(@"C:\Users\toth\Desktop\zamestnaci_jednotna_velkost\elisabeth-c-cooper.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] data5 = new byte[file5.Length];
                file5.Read(data5, 0, data5.Length);
                file5.Close();

                System.IO.FileStream file6 = new System.IO.FileStream(@"C:\Users\toth\Desktop\zamestnaci_jednotna_velkost\christine-j-maynard.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] data6 = new byte[file6.Length];
                file6.Read(data6, 0, data6.Length);
                file6.Close();

                System.IO.FileStream file7 = new System.IO.FileStream(@"C:\Users\toth\Desktop\zamestnaci_jednotna_velkost\james-p-galvan.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] data7 = new byte[file7.Length];
                file7.Read(data7, 0, data7.Length);
                file7.Close();

                System.IO.FileStream file8 = new System.IO.FileStream(@"C:\Users\toth\Desktop\zamestnaci_jednotna_velkost\debra-c-titus.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] data8 = new byte[file8.Length];
                file8.Read(data8, 0, data8.Length);
                file8.Close();

                System.IO.FileStream file9 = new System.IO.FileStream(@"C:\Users\toth\Desktop\zamestnaci_jednotna_velkost\giovanni-j-peng.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] data9 = new byte[file9.Length];
                file9.Read(data9, 0, data9.Length);
                file9.Close();

                System.IO.FileStream file10 = new System.IO.FileStream(@"C:\Users\toth\Desktop\zamestnaci_jednotna_velkost\henrich-fuller.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] data10 = new byte[file10.Length];
                file10.Read(data10, 0, data10.Length);
                file10.Close();

                System.IO.FileStream file11 = new System.IO.FileStream(@"C:\Users\toth\Desktop\zamestnaci_jednotna_velkost\michael-d-stewart.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] data11 = new byte[file11.Length];
                file11.Read(data11, 0, data11.Length);
                file11.Close();

                var admin = new ApplicationUser
                {
                    Email                = "*****@*****.**",
                    Firstname            = "Jane",
                    Surname              = "Hudson",
                    UserName             = "******",
                    EmailConfirmed       = true,
                    BirthDate            = DateTime.Parse("1970-12-23").Date,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = false,
                    LockoutEnabled       = true,
                    Photo                = data1
                };
                userManager.CreateAsync(admin, "Password@123").Wait();
                userManager.AddToRolesAsync(admin.Id, "Administrator").Wait();

                var user1 = new ApplicationUser
                {
                    Email                = "*****@*****.**",
                    Firstname            = "Lewis C.",
                    Surname              = "Morrel",
                    UserName             = "******",
                    EmailConfirmed       = true,
                    BirthDate            = DateTime.Parse("1985-12-15").Date,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = false,
                    LockoutEnabled       = true,
                    Photo                = data2
                };
                userManager.CreateAsync(user1, "Password@123").Wait();
                userManager.AddToRolesAsync(user1.Id, "Employee").Wait();

                var user2 = new ApplicationUser
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    Firstname            = "Desirae",
                    Surname              = "Young",
                    EmailConfirmed       = true,
                    BirthDate            = DateTime.Parse("1990-07-09").Date,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = false,
                    LockoutEnabled       = true,
                    Photo                = data3
                };
                userManager.CreateAsync(user2, "Password@123").Wait();
                userManager.AddToRolesAsync(user2.Id, "Employee").Wait();

                var user3 = new ApplicationUser
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    Firstname            = "John G.",
                    Surname              = "Winn",
                    EmailConfirmed       = true,
                    BirthDate            = DateTime.Parse("1982-02-27").Date,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = false,
                    LockoutEnabled       = true,
                    Photo                = data4
                };
                userManager.CreateAsync(user3, "Password@123").Wait();
                userManager.AddToRolesAsync(user3.Id, "Employee").Wait();

                var user4 = new ApplicationUser
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    Firstname            = "Elisabeth C.",
                    Surname              = "Cooper",
                    EmailConfirmed       = true,
                    BirthDate            = DateTime.Parse("1984-01-24").Date,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = false,
                    LockoutEnabled       = true,
                    Photo                = data5
                };
                userManager.CreateAsync(user4, "Password@123").Wait();
                userManager.AddToRolesAsync(user4.Id, "Employee").Wait();

                var user5 = new ApplicationUser
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    Firstname            = "Christin J.",
                    Surname              = "Maynard",
                    EmailConfirmed       = true,
                    BirthDate            = DateTime.Parse("1978-09-09").Date,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = false,
                    LockoutEnabled       = true,
                    Photo                = data6
                };
                userManager.CreateAsync(user5, "Password@123").Wait();
                userManager.AddToRolesAsync(user5.Id, "Employee").Wait();

                var user6 = new ApplicationUser
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    Firstname            = "James P.",
                    Surname              = "Galvan",
                    EmailConfirmed       = true,
                    BirthDate            = DateTime.Parse("1990-12-06").Date,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = false,
                    LockoutEnabled       = true,
                    Photo                = data7
                };
                userManager.CreateAsync(user6, "Password@123").Wait();
                userManager.AddToRolesAsync(user6.Id, "Employee").Wait();

                var user7 = new ApplicationUser
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    Firstname            = "Debra C.",
                    Surname              = "Titus",
                    EmailConfirmed       = true,
                    BirthDate            = DateTime.Parse("1983-08-22").Date,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = false,
                    LockoutEnabled       = true,
                    Photo                = data8
                };
                userManager.CreateAsync(user7, "Password@123").Wait();
                userManager.AddToRolesAsync(user7.Id, "Employee").Wait();

                var user8 = new ApplicationUser
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    Firstname            = "Giovanni J.",
                    Surname              = "Peng",
                    EmailConfirmed       = true,
                    BirthDate            = DateTime.Parse("1990-12-10").Date,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = false,
                    LockoutEnabled       = true,
                    Photo                = data9
                };
                userManager.CreateAsync(user8, "Password@123").Wait();
                userManager.AddToRolesAsync(user8.Id, "Employee").Wait();

                var user9 = new ApplicationUser
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    Firstname            = "Henrich",
                    Surname              = "Fuller",
                    EmailConfirmed       = true,
                    BirthDate            = DateTime.Parse("1975-09-16").Date,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = false,
                    LockoutEnabled       = true,
                    Photo                = data10
                };
                userManager.CreateAsync(user9, "Password@123").Wait();
                userManager.AddToRolesAsync(user9.Id, "Employee").Wait();

                var user10 = new ApplicationUser
                {
                    Email                = "*****@*****.**",
                    UserName             = "******",
                    Firstname            = "Michael D.",
                    Surname              = "Stewart",
                    EmailConfirmed       = true,
                    BirthDate            = DateTime.Parse("1999-09-01").Date,
                    TwoFactorEnabled     = false,
                    PhoneNumberConfirmed = false,
                    LockoutEnabled       = true,
                    Photo                = data11
                };
                userManager.CreateAsync(user10, "Password@123").Wait();
                userManager.AddToRolesAsync(user10.Id, "Employee").Wait();
            }

            //update-database -ConfigurationTypeName BluePumpkinn.Migrations.AnotherDbContext.Configuration
            if (!context.Event.Any())
            {
                var events = new List <Event>
                {
                    new Event
                    {
                        Name          = "Charity Group",
                        EventDate     = DateTime.Parse("2015-12-15").Date,
                        EventLocation = "London",
                        Description   = "Commission invites charities, trustees and their advisers to attend its Annual Public Meeting on 15 December 2015. The meeting will be chaired by William Shawcross, chairman of the Charity Commission, who will also open the meeting. Attendees will then hear from the regulator’s new Chief Executive, Paula Sussex, on the Commission’s work over the last year and her plans for the coming months.The meeting will also include a lecture from the renowned historian and author Dr Frank Prochaska on ‘The State of Charity’. Dr Prochaska, a former lecturer in British history at Yale, will also invite attendees to comment and discuss the topic. The event is to be held at Church House in Westminster BC from 4pm to 6pm and will be followed by a drinks reception. The meeting is free to attend. To book a place please email publicmeetings@@charitycommission.com"
                    },


                    new Event
                    {
                        Name        = "Chess Tournament",
                        Description = "Love to play chess already? Want to learn how? Want to meet new people? Join us! We welcome members"
                    },

                    new Event
                    {
                        Name        = "Christmas Raffle",
                        Description = "A Christmas raffle offers a fund-raising option with a festive twist. A raffle with a holiday theme"
                    },


                    new Event
                    {
                        Name          = "Employee of the Month",
                        EventDate     = DateTime.Parse("2015-12-30").Date,
                        EventLocation = "London",
                        Description   = "The UAB Employee of the Month Program seeks to recognize and reward those staff members whose"
                    },

                    new Event
                    {
                        Name          = "Footbal",
                        EventDate     = DateTime.Parse("2015-12-06").Date,
                        EventLocation = "Wien",
                        Description   = "With more than 3,000 members we are the largest flag football group in the world.  We are a co-ed group of flag football fanatics. Our league is 100% FREE.  No fees or donations required!  We welcome novice and experienced adult players of all ages.  Our motto is safety first, then sportsmanship, fun, exercise, and competition.  Come make new friends, have fun, and get great exercise at the beach. This meetup page is dedicated to our \"competitive league.\"  However, our group   also offers FREE weekly \"pick-up games\" EVERY Saturday and Sunday at 11 AM 52 weeks per year. Click on the link just below to join our \"sister\" group if you want to play FREE \"pick up\" flag football."
                    },

                    new Event
                    {
                        Name          = "Company Vision Meeting",
                        EventDate     = DateTime.Parse("2016-01-08").Date,
                        EventLocation = "Edinbrugh",
                        Description   = "We are delighted to invite you to this year’s Visionary Conference, co-hosted by Visionary and VISION 2020 UK in Edinburgh. This year’s theme is ‘Leading for Change – Delivering the Future Together’ which is reflected throughout the 16 workshops on offer to delegates over the two-day programme.  The workshops will cover a range of topics including children, fundraising, rehabilitation and research. The conference is designed to provide networking and learning opportunities for local societies, national charities and other professions. We hope all delegates can share and take away learnings from the two days to improve the quality of service provided to people with sight loss across theThis is the sixth annual Visionary Conference and this year has been designed to provide more benefits to delegates, including extended information sharing and some new highlights. Please find attached, the programme for this year’s conference which is subject to change."
                    }
                };
                context.Event.AddRange(events);
                context.SaveChanges();
            }


            //if (!context.EventParticipant.Any())
            //{
            //    var participant = new EventParticipant{
            //        ApplicationUserID=context.Users.Select(a=>a.Id==;
            //    }
            //}
        }
示例#46
0
        internal FakeIdentityContextFactory(string databaseName)
        {
            if (string.IsNullOrEmpty(databaseName))
            {
                throw new ArgumentException($"{nameof(databaseName)} is Null or Empty.", nameof(databaseName));
            }

            IServiceCollection services = new ServiceCollection();

            services.AddTransient <IConfiguration>((sp) => new ConfigurationBuilder()
                                                   .AddInMemoryCollection(new Dictionary <string, string>
            {
                { "databaseName", databaseName }
            }).Build());
            services.AddDbContext <FakeIdentityContext>();
            services.AddIdentity <ApplicationUser, ApplicationRole>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 3;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <FakeIdentityContext>()
            .AddDefaultTokenProviders();

            HttpRequest         request         = new DefaultHttpContext().Request;
            HttpContextAccessor contextAccessor = new HttpContextAccessor {
                HttpContext = request.HttpContext
            };

            services.AddSingleton <IHttpContextAccessor>(contextAccessor);

            IServiceProvider serviceProvider = services.BuildServiceProvider();

            contextAccessor.HttpContext.RequestServices = serviceProvider;
            ParkingDBContext context = serviceProvider.GetRequiredService <FakeIdentityContext>();

            UserStore <ApplicationUser, ApplicationRole, ParkingDBContext, string> userStore = new UserStore <ApplicationUser, ApplicationRole, ParkingDBContext, string>(context);
            IOptions <IdentityOptions>               serviceIOptions           = serviceProvider.GetRequiredService <IOptions <IdentityOptions> >();
            UserManager <ApplicationUser>            serviceUserManager        = serviceProvider.GetRequiredService <UserManager <ApplicationUser> >();
            ILogger <UserManager <ApplicationUser> > serviceILoggerUserManager = serviceProvider.GetRequiredService <ILogger <UserManager <ApplicationUser> > >();

            RoleStore <ApplicationRole, ParkingDBContext, string> roleStore    = new RoleStore <ApplicationRole, ParkingDBContext, string>(context);
            RoleManager <ApplicationRole>            serviceRoleManager        = serviceProvider.GetRequiredService <RoleManager <ApplicationRole> >();
            ILogger <RoleManager <ApplicationRole> > serviceILoggerRoleManager = serviceProvider.GetRequiredService <ILogger <RoleManager <ApplicationRole> > >();

            IHttpContextAccessor                       serviceIHttpContextAccessor          = serviceProvider.GetRequiredService <IHttpContextAccessor>();
            SignInManager <ApplicationUser>            serviceSignInManager                 = serviceProvider.GetRequiredService <SignInManager <ApplicationUser> >();
            ILogger <SignInManager <ApplicationUser> > serviceILoggerSignInManager          = serviceProvider.GetRequiredService <ILogger <SignInManager <ApplicationUser> > >();
            IAuthenticationSchemeProvider              serviceIAuthenticationSchemeProvider = serviceProvider.GetRequiredService <IAuthenticationSchemeProvider>();

            UserManager = new UserManager <ApplicationUser>(
                userStore,
                serviceIOptions,
                serviceUserManager.PasswordHasher,
                serviceUserManager.UserValidators,
                serviceUserManager.PasswordValidators,
                serviceUserManager.KeyNormalizer,
                serviceUserManager.ErrorDescriber,
                serviceProvider,
                serviceILoggerUserManager
                );

            RoleManager = new RoleManager <ApplicationRole>(
                roleStore,
                serviceRoleManager.RoleValidators,
                serviceRoleManager.KeyNormalizer,
                serviceRoleManager.ErrorDescriber,
                serviceILoggerRoleManager
                );

            SignInManager = new SignInManager <ApplicationUser>(
                UserManager,
                serviceIHttpContextAccessor,
                serviceSignInManager.ClaimsFactory,
                serviceIOptions,
                serviceILoggerSignInManager,
                serviceIAuthenticationSchemeProvider
                );
        }
 public AppRoleManager(RoleStore <AppRole> store) : base(store)
 {
 }
        protected override void Seed(ApplicationDbContext db)
        {
            //db.Users.Add(new User { userId = "jfk", ADA = false });
            //db.Users.Add(new User { userId = "nixon", ADA = false });

            RoleStore <IdentityRole>    roleStore = new RoleStore <IdentityRole>(db);
            UserStore <ApplicationUser> userStore = new UserStore <ApplicationUser>(db);

            RoleManager <IdentityRole>    rm = new RoleManager <IdentityRole>(roleStore);
            UserManager <ApplicationUser> um = new UserManager <ApplicationUser>(userStore);

            IdentityResult ir;

            ApplicationUser nobody = createUser("*****@*****.**");
            ApplicationUser jfk    = createUser("*****@*****.**");
            ApplicationUser nixon  = createUser("*****@*****.**");

            ir = um.Create(nobody, "nobody1234");
            //nobody = um.FindByName(nobody.UserName);
            ir = um.Create(jfk, "jfk1234");
            //jfk = um.FindByName(jfk.UserName);
            ir = um.Create(nixon, "nixon1234");
            //nixon = um.FindByName(nixon.UserName);

            rm.Create(new IdentityRole("User"));
            if (!um.IsInRole(nobody.Id, "User"))
            {
                um.AddToRole(nobody.Id, "User");
            }
            if (!um.IsInRole(jfk.Id, "User"))
            {
                um.AddToRole(jfk.Id, "User");
            }
            if (!um.IsInRole(nixon.Id, "User"))
            {
                um.AddToRole(nixon.Id, "User");
            }

            rm.Create(new IdentityRole("Admin"));
            if (!um.IsInRole(nixon.Id, "Admin"))
            {
                um.AddToRole(nixon.Id, "Admin");
            }

            rm.Create(new IdentityRole("Approver"));
            if (!um.IsInRole(jfk.Id, "Approver"))
            {
                um.AddToRole(jfk.Id, "Approver");
            }

            db.Tags.Add(new Tag {
                Name = "portrait"
            });
            db.Tags.Add(new Tag {
                Name = "architecture"
            });
            db.SaveChanges();

            db.Images.Add(new Image
            {
                Caption     = "Ingrid Bergman",
                Description = "Actor from Casablanca.",
                Date        = new DateTime(1946, 12, 14),
                UserID      = jfk.Id,
                TagID       = 1,
                Approved    = true
            });
            db.SaveChanges();

            base.Seed(db);
        }
 public RolesApiController(WebStoreDb db)
 {
     _RoleStore = new RoleStore <Role>(db);
 }
示例#50
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FindBy"/> class.
        /// </summary>
        public GetAllAsync()
        {
            // Create a service provider to be shared by all test methods
            var serviceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider();

            // Create options telling the context to use an
            // InMemory database and the service provider.
            var builder = new DbContextOptionsBuilder <TemplateDbContext>();

            builder.UseInMemoryDatabase().UseInternalServiceProvider(serviceProvider);
            this.contextOptions = builder.Options;

            // seed in constructor.
            using (var context = new TemplateDbContext(this.contextOptions))
            {
                string password  = "******";
                var    roleStore = new RoleStore <IdentityRole>(context);

                var user = new ApplicationUser
                {
                    Name               = "User for test purposes",
                    UserName           = "******",
                    NormalizedUserName = "******",
                    Email              = "*****@*****.**",
                    NormalizedEmail    = "*****@*****.**",
                    EmailConfirmed     = true,
                    LockoutEnabled     = false,
                    SecurityStamp      = Guid.NewGuid().ToString()
                };

                var userTester = new ApplicationUser
                {
                    Name               = "User for test purposes",
                    UserName           = "******",
                    NormalizedUserName = "******",
                    Email              = "*****@*****.**",
                    NormalizedEmail    = "*****@*****.**",
                    EmailConfirmed     = true,
                    LockoutEnabled     = false,
                    SecurityStamp      = Guid.NewGuid().ToString()
                };

                if (!context.Roles.Any(r => r.Name == "User"))
                {
                    roleStore.CreateAsync(new IdentityRole {
                        Name = "User", NormalizedName = "User"
                    });
                }

                if (!context.Users.Any(u => u.UserName == user.UserName))
                {
                    var hasher = new PasswordHasher <ApplicationUser>();
                    var hashed = hasher.HashPassword(user, password);
                    user.PasswordHash       = hashed;
                    userTester.PasswordHash = hashed;
                    var userStore = new UserStore <ApplicationUser>(context);
                    userStore.CreateAsync(user);
                    userStore.CreateAsync(userTester);
                    userStore.AddToRoleAsync(user, "User");
                    userStore.AddToRoleAsync(userTester, "User");
                }

                context.SaveChangesAsync();
            }
        }
示例#51
0
        public static ApplicationRoleManager Create(IdentityFactoryOptions <ApplicationRoleManager> options, IOwinContext context)
        {
            var roleStore = new RoleStore(context.Get <BrgyMgmtEntities>());

            return(new ApplicationRoleManager(roleStore));
        }
示例#52
0
        protected override void Seed(ApplicationDbContext context)
        {
            #region Roles
            if (!context.LMSRoles.Any(r => r.Name == RoleConstants.Admin))
            {
                var store       = new RoleStore <Role>(context);
                var roleManager = new RoleManager <Role>(store);

                roleManager.Create(new Role(RoleConstants.Admin));
            }

            if (!context.LMSRoles.Any(r => r.Name == RoleConstants.Teacher))
            {
                var store       = new RoleStore <Role>(context);
                var roleManager = new RoleManager <Role>(store);

                roleManager.Create(new Role(RoleConstants.Teacher));
            }

            if (!context.LMSRoles.Any(r => r.Name == RoleConstants.Student))
            {
                var store       = new RoleStore <Role>(context);
                var roleManager = new RoleManager <Role>(store);

                roleManager.Create(new Role(RoleConstants.Student));
            }
            #endregion

            #region Subjects
            Subject subject = new Subject {
                Name = "French"
            };
            #endregion

            #region Courses
            Course course = new Course {
                Subject = subject
            };
            #endregion

            #region Users
            if (!context.LMSUsers.Any(u => u.UserName == "Admin"))
            {
                var store       = new UserStore <User>(context);
                var userManager = new UserManager <User>(store);
                var newuser     = new User
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    BirthDate = DateTime.Now.ToString("yyyy/MM/dd"),
                    FirstName = "Admin",
                    LastName  = "Histrator"
                };

                userManager.Create(newuser, "Admin-Password1");
                userManager.AddToRole(newuser.Id, RoleConstants.Admin);
            }

            Random rd = new Random();

            List <string> phoneNumbers = new List <string>();

            if (!context.LMSUsers.Any(u => u.UserName == "Liam"))
            {
                string phoneNumber = GeneratePhoneNumber(rd);

                var store       = new UserStore <User>(context);
                var userManager = new UserManager <User>(store);
                var newuser     = new User
                {
                    UserName             = "******",
                    Email                = "*****@*****.**",
                    FirstName            = "Liam",
                    LastName             = "B",
                    BirthDate            = DateTime.Now.ToString("yyyy/MM/dd"),
                    PhoneNumber          = phoneNumber,
                    PhoneNumberConfirmed = true
                };

                phoneNumbers.Add(phoneNumber);

                userManager.Create(newuser, "Teacher-Password1");
                userManager.AddToRole(newuser.Id, RoleConstants.Teacher);
            }

            if (!context.LMSUsers.Any(u => u.UserName == "Student1"))
            {
                var store       = new UserStore <User>(context);
                var userManager = new UserManager <User>(store);

                for (int noStudent = 1; noStudent <= 20; noStudent += 1)
                {
                    int      year      = rd.Next(1990, 2010);
                    int      month     = rd.Next(1, 13);
                    DateTime birthDate = new DateTime(year, month, rd.Next(1, DateTime.DaysInMonth(year, month) + 1));

                    string phoneNumber = string.Empty;

                    do
                    {
                        phoneNumber = GeneratePhoneNumber(rd);
                    }while (phoneNumbers.Contains(phoneNumber));

                    var newuser = new User
                    {
                        UserName             = "******" + noStudent.ToString(),
                        Email                = "s" + noStudent.ToString() + "@mail.nu",
                        FirstName            = "Student",
                        LastName             = new string((char)((int)'A' + noStudent - 1), 5),
                        BirthDate            = birthDate.ToString("yyyy/MM/dd"),
                        PhoneNumber          = phoneNumber,
                        PhoneNumberConfirmed = true
                    };

                    phoneNumbers.Add(phoneNumber);

                    userManager.Create(newuser, "Student-Password1");
                    userManager.AddToRole(newuser.Id, RoleConstants.Student);
                }

                for (int noTeacher = 1; noTeacher <= 10; noTeacher += 1)
                {
                    int      year      = rd.Next(1960, 2001);
                    int      month     = rd.Next(1, 13);
                    DateTime birthDate = new DateTime(year, month, rd.Next(1, DateTime.DaysInMonth(year, month) + 1));

                    string phoneNumber = string.Empty;

                    do
                    {
                        phoneNumber = GeneratePhoneNumber(rd);
                    }while (phoneNumbers.Contains(phoneNumber));

                    var newuser = new User
                    {
                        UserName             = "******" + noTeacher.ToString(),
                        Email                = "t" + noTeacher.ToString() + "@mail.nu",
                        FirstName            = "Teacher",
                        LastName             = new string((char)((int)'A' + noTeacher - 1), 5),
                        BirthDate            = birthDate.ToString("yyyy/MM/dd"),
                        PhoneNumber          = phoneNumber,
                        PhoneNumberConfirmed = true
                    };

                    phoneNumbers.Add(phoneNumber);

                    userManager.Create(newuser, "Teacher-Password1");
                    userManager.AddToRole(newuser.Id, RoleConstants.Teacher);
                }
            }

            User user = context.LMSUsers.FirstOrDefault(u => u.Email == "*****@*****.**");
            course.Teacher = user;
            user.Courses   = new List <Course> {
                course
            };

            context.Users.AddOrUpdate(u => u.Id, user);
            #endregion

            #region Classrooms
            context.Classrooms.AddOrUpdate(
                c => c.ID,
                new Classroom
            {
                ID                = 1,
                Name              = "A001",
                Location          = "Building A, ground floor, first on the right",
                Remarks           = "Lecture hall",
                AmountStudentsMax = 354
            },
                new Classroom
            {
                ID                = 2,
                Name              = "A002",
                Location          = "Building A, ground floor, first on the left",
                Remarks           = "Chemistry classroom",
                AmountStudentsMax = 18
            },
                new Classroom
            {
                ID                = 3,
                Name              = "A003",
                Location          = "Building A, ground floor, second on the right",
                AmountStudentsMax = 32
            },
                new Classroom
            {
                ID                = 4,
                Name              = "A004",
                Location          = "Building A, ground floor, second on the left",
                AmountStudentsMax = 28
            },
                new Classroom
            {
                ID                = 5,
                Name              = "A011",
                Location          = "Building A, first floor, first on the right",
                Remarks           = "Computer classroom",
                AmountStudentsMax = 22
            },
                new Classroom
            {
                ID                = 6,
                Name              = "A012",
                Location          = "Building A, first floor, first on the left",
                Remarks           = "Computer classroom",
                AmountStudentsMax = 12
            },
                new Classroom
            {
                ID                = 7,
                Name              = "A013",
                Location          = "Building A, first floor, second on the right",
                Remarks           = "Computer classroom",
                AmountStudentsMax = 18
            },
                new Classroom
            {
                ID                = 8,
                Name              = "A014",
                Location          = "Building A, first floor, second on the left",
                AmountStudentsMax = 35
            },
                new Classroom
            {
                ID                = 9,
                Name              = "A021",
                Location          = "Building A, second floor, first on the right",
                AmountStudentsMax = 48
            },
                new Classroom
            {
                ID                = 10,
                Name              = "A022",
                Location          = "Building A, second floor, first on the left",
                Remarks           = "Physics classroom",
                AmountStudentsMax = 16
            },
                new Classroom
            {
                ID                = 11,
                Name              = "A023",
                Location          = "Building A, second floor, second on the right",
                AmountStudentsMax = 12
            },
                new Classroom
            {
                ID                = 12,
                Name              = "A024",
                Location          = "Building A, second floor, second on the left",
                AmountStudentsMax = 12
            },
                new Classroom
            {
                ID                = 13,
                Name              = "B001",
                Location          = "Building B, ground floor, first on the right",
                Remarks           = "Lecture hall",
                AmountStudentsMax = 358
            },
                new Classroom
            {
                ID                = 14,
                Name              = "B002",
                Location          = "Building B, ground floor, first on the left",
                Remarks           = "Lecture hall",
                AmountStudentsMax = 215
            },
                new Classroom
            {
                ID                = 15,
                Name              = "B003",
                Location          = "Building B, ground floor, second on the right",
                AmountStudentsMax = 12
            },
                new Classroom
            {
                ID                = 16,
                Name              = "B004",
                Location          = "Building B, ground floor, second on the left",
                AmountStudentsMax = 12
            },
                new Classroom
            {
                ID                = 17,
                Name              = "B011",
                Location          = "Building B, first floor, first on the right",
                AmountStudentsMax = 12
            },
                new Classroom
            {
                ID                = 18,
                Name              = "B012",
                Location          = "Building B, first floor, first on the left",
                AmountStudentsMax = 12
            },
                new Classroom
            {
                ID                = 19,
                Name              = "B013",
                Location          = "Building B, first floor, second on the right",
                AmountStudentsMax = 12
            },
                new Classroom
            {
                ID                = 20,
                Name              = "B014",
                Location          = "Building B, first floor, second on the left",
                AmountStudentsMax = 12
            },
                new Classroom
            {
                ID                = 21,
                Name              = "B021",
                Location          = "Building B, second floor, first on the right",
                AmountStudentsMax = 12
            },
                new Classroom
            {
                ID                = 22,
                Name              = "B022",
                Location          = "Building B, second floor, first on the left",
                AmountStudentsMax = 12
            },
                new Classroom
            {
                ID                = 23,
                Name              = "B023",
                Location          = "Building B, second floor, second on the right",
                AmountStudentsMax = 12
            },
                new Classroom
            {
                ID                = 24,
                Name              = "B024",
                Location          = "Building B, second floor, second on the left",
                AmountStudentsMax = 12
            }
                );
            #endregion
        }
        private async Task CreateIdentityUsers(ApplicationDbContext context)
        {
            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new UserManager <ApplicationUser>(userStore);
            var roleStore   = new RoleStore <IdentityRole>();
            var roleManager = new RoleManager <IdentityRole>(roleStore);

            if (!roleManager.RoleExists(Roles.ADMIN))
            {
                var role = new IdentityRole();
                role.Name = Roles.ADMIN;
                roleManager.Create(role);
            }
            if (!roleManager.RoleExists(Roles.MANAGER))
            {
                var role = new IdentityRole();
                role.Name = Roles.MANAGER;
                roleManager.Create(role);
            }
            if (!roleManager.RoleExists(Roles.SITE_ENGINEER))
            {
                var role = new IdentityRole();
                role.Name = Roles.SITE_ENGINEER;
                roleManager.Create(role);
            }
            if (!roleManager.RoleExists(Roles.ACCOUNTANT))
            {
                var role = new IdentityRole();
                role.Name = Roles.ACCOUNTANT;
                roleManager.Create(role);
            }

            var manager1 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultManager1 = await userManager.CreateAsync(manager1, "123456");

            if (resultManager1.Succeeded)
            {
                userManager.AddToRole(manager1.Id, Roles.MANAGER);
            }
            var managerYamin = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultManagerYamin = await userManager.CreateAsync(managerYamin, "123456");

            if (resultManagerYamin.Succeeded)
            {
                userManager.AddToRole(managerYamin.Id, Roles.MANAGER);
            }
            var manager2 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultManager2 = await userManager.CreateAsync(manager2, "123456");

            if (resultManager2.Succeeded)
            {
                userManager.AddToRole(manager2.Id, Roles.MANAGER);
            }
            var manager3 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultManager3 = await userManager.CreateAsync(manager3, "123456");

            if (resultManager3.Succeeded)
            {
                userManager.AddToRole(manager3.Id, Roles.MANAGER);
            }
            var manager4 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultManager4 = await userManager.CreateAsync(manager4, "123456");

            if (resultManager4.Succeeded)
            {
                userManager.AddToRole(manager4.Id, Roles.MANAGER);
            }
            var manager5 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultManager5 = await userManager.CreateAsync(manager5, "123456");

            if (resultManager5.Succeeded)
            {
                userManager.AddToRole(manager5.Id, Roles.MANAGER);
            }
            var manager6 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultManager6 = await userManager.CreateAsync(manager6, "123456");

            if (resultManager6.Succeeded)
            {
                userManager.AddToRole(manager6.Id, Roles.MANAGER);
            }
            var accountant = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultAccountant = await userManager.CreateAsync(accountant, "123456");

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

            if (resultSiteEngineer1.Succeeded)
            {
                userManager.AddToRole(siteEngineer1.Id, Roles.SITE_ENGINEER);
            }
            var siteEngineerYamin = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultSiteEngineerYamin = await userManager.CreateAsync(siteEngineerYamin, "123456");

            if (resultSiteEngineerYamin.Succeeded)
            {
                userManager.AddToRole(siteEngineerYamin.Id, Roles.SITE_ENGINEER);
            }
            var siteEngineer2 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultSiteEngineer2 = await userManager.CreateAsync(siteEngineer2, "123456");

            if (resultSiteEngineer2.Succeeded)
            {
                userManager.AddToRole(siteEngineer2.Id, Roles.SITE_ENGINEER);
            }
            var siteEngineer3 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer3 = await userManager.CreateAsync(siteEngineer3, "123456");

            if (resultsiteEngineer3.Succeeded)
            {
                userManager.AddToRole(siteEngineer3.Id, Roles.SITE_ENGINEER);
            }
            var siteEngineer4 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer4 = await userManager.CreateAsync(siteEngineer4, "123456");

            if (resultsiteEngineer4.Succeeded)
            {
                userManager.AddToRole(siteEngineer4.Id, Roles.SITE_ENGINEER);
            }
            var siteEngineer5 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer5 = await userManager.CreateAsync(siteEngineer5, "123456");

            if (resultsiteEngineer5.Succeeded)
            {
                userManager.AddToRole(siteEngineer5.Id, Roles.SITE_ENGINEER);
            }
            var siteEngineer6 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer6 = await userManager.CreateAsync(siteEngineer6, "123456");

            if (resultsiteEngineer6.Succeeded)
            {
                userManager.AddToRole(siteEngineer6.Id, Roles.SITE_ENGINEER);
            }
            var siteEngineer7 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer7 = await userManager.CreateAsync(siteEngineer7, "123456");

            if (resultsiteEngineer7.Succeeded)
            {
                userManager.AddToRole(siteEngineer7.Id, Roles.SITE_ENGINEER);
            }
            var siteEngineer8 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer8 = await userManager.CreateAsync(siteEngineer8, "123456");

            if (resultsiteEngineer8.Succeeded)
            {
                userManager.AddToRole(siteEngineer8.Id, Roles.SITE_ENGINEER);
            }
            var siteEngineer9 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer9 = await userManager.CreateAsync(siteEngineer9, "123456");

            if (resultsiteEngineer9.Succeeded)
            {
                userManager.AddToRole(siteEngineer9.Id, Roles.SITE_ENGINEER);
            }
            var siteEngineer10 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer10 = await userManager.CreateAsync(siteEngineer10, "123456");

            if (resultsiteEngineer10.Succeeded)
            {
                userManager.AddToRole(siteEngineer10.Id, Roles.SITE_ENGINEER);
            }
            var siteEngineer11 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer11 = await userManager.CreateAsync(siteEngineer11, "123456");

            if (resultsiteEngineer11.Succeeded)
            {
                userManager.AddToRole(siteEngineer11.Id, Roles.SITE_ENGINEER);
            }
            var siteEngineer12 = new ApplicationUser()
            {
                UserName = "******", Email = "*****@*****.**"
            };
            IdentityResult resultsiteEngineer12 = await userManager.CreateAsync(siteEngineer12, "123456");

            if (resultsiteEngineer12.Succeeded)
            {
                userManager.AddToRole(siteEngineer12.Id, Roles.SITE_ENGINEER);
            }
        }
示例#54
0
        protected override void Seed(TrainerWebApi.DAL.TrainerContext context)
        {
            if (System.Diagnostics.Debugger.IsAttached == false)
            {
                System.Diagnostics.Debugger.Launch();
            }

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

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

            roleManager.Create(new IdentityRole("admin"));
            roleManager.Create(new IdentityRole("athlete"));
            roleManager.Create(new IdentityRole("trainer"));

            var admin = new User
            {
                Id            = "1",
                UserName      = "******",
                FirstName     = "Admin",
                LastName      = "Admin",
                Email         = "[email protected]",
                PasswordHash  = new PasswordHasher().HashPassword("admin"),
                SecurityStamp = Guid.NewGuid().ToString()
            };

            var test_athlete = new User
            {
                Id            = "2",
                UserName      = "******",
                FirstName     = "Testathlete",
                LastName      = "Testathlete",
                Email         = "*****@*****.**",
                PasswordHash  = new PasswordHasher().HashPassword("testathlete"),
                SecurityStamp = Guid.NewGuid().ToString()
            };

            var test_trainer = new User
            {
                Id            = "3",
                UserName      = "******",
                FirstName     = "Testtrainer",
                LastName      = "TestTrainer",
                Email         = "*****@*****.**",
                PasswordHash  = new PasswordHasher().HashPassword("testtrainer"),
                SecurityStamp = Guid.NewGuid().ToString()
            };

            context.Users.AddOrUpdate(admin);
            context.Users.AddOrUpdate(test_athlete);
            context.Users.AddOrUpdate(test_trainer);

            context.Muscles.AddOrUpdate(
                m => m.Name,
                new Muscle {
                Id = 1, Name = "Bicep"
            },
                new Muscle {
                Id = 2, Name = "Tricep"
            },
                new Muscle {
                Id = 3, Name = "Forearm"
            },
                new Muscle {
                Id = 4, Name = "Minor Chest"
            },
                new Muscle {
                Id = 5, Name = "Major Chest"
            },
                new Muscle {
                Id = 6, Name = "Back"
            },
                new Muscle {
                Id = 7, Name = "Trapezoid"
            },
                new Muscle {
                Id = 8, Name = "Hamstrings"
            },
                new Muscle {
                Id = 9, Name = "ABS"
            },
                new Muscle {
                Id = 10, Name = "Legs"
            }
                );

            context.SaveChanges();

            var bicepCurlMuscles   = context.Muscles.Where(m => m.Id == 1 || m.Id == 3).ToList();
            var benchPressMuscles  = context.Muscles.Where(m => m.Id == 4 || m.Id == 5 || m.Id == 2).ToList();
            var rowsMuscles        = context.Muscles.Where(m => m.Id == 1 || m.Id == 6 || m.Id == 7 || m.Id == 3).ToList();
            var frontSquatsMuscles = context.Muscles.Where(m => m.Id == 10 || m.Id == 9 || m.Id == 7 || m.Id == 8).ToList();
            var backSquatsMuscles  = context.Muscles.Where(m => m.Id == 10 || m.Id == 9 || m.Id == 7 || m.Id == 8).ToList();

            context.ExerciseCards.AddOrUpdate(
                e => e.Name,
                new ExerciseCard {
                Name = "Bicep Curl", Description = "Curl the biceps", MusclesInvolved = bicepCurlMuscles
            },
                new ExerciseCard {
                Name = "Bench Press", Description = "Curl the biceps", MusclesInvolved = benchPressMuscles
            },
                new ExerciseCard {
                Name = "Rows", Description = "Curl the biceps", MusclesInvolved = rowsMuscles
            },
                new ExerciseCard {
                Name = "Front Squats", Description = "Curl the biceps", MusclesInvolved = frontSquatsMuscles
            },
                new ExerciseCard {
                Name = "Back Squats", Description = "Curl the biceps", MusclesInvolved = backSquatsMuscles
            },
                new ExerciseCard {
                Name = "Deadlift", Description = "Curl the biceps"
            },
                new ExerciseCard {
                Name = "Hip Thrusts", Description = "Curl the biceps"
            }
                );

            context.SaveChanges();

            context.Trainings.AddOrUpdate(
                t => t.Name,
                new Training
            {
                Name      = "test_training_1",
                Exercises = new List <ExercisePlan>
                {
                    new ExercisePlan
                    {
                        Name = "Bicep Curl",
                        Sets = new List <ExerciseSet>()
                        {
                            new ExerciseSet {
                                Reps = 10, Weight = 10
                            },
                            new ExerciseSet {
                                Reps = 8, Weight = 12
                            },
                            new ExerciseSet {
                                Reps = 7, Weight = 14
                            },
                            new ExerciseSet {
                                Reps = 6, Weight = 16
                            },
                            new ExerciseSet {
                                Reps = 4, Weight = 18
                            },
                        }
                    },
                    new ExercisePlan
                    {
                        Name = "Bench Press",
                        Sets = new List <ExerciseSet>()
                        {
                            new ExerciseSet {
                                Reps = 10, Weight = 50
                            },
                            new ExerciseSet {
                                Reps = 8, Weight = 55
                            },
                            new ExerciseSet {
                                Reps = 7, Weight = 60
                            },
                            new ExerciseSet {
                                Reps = 6, Weight = 65
                            },
                            new ExerciseSet {
                                Reps = 4, Weight = 70
                            },
                        }
                    },
                    new ExercisePlan
                    {
                        Name = "Rows",
                        Sets = new List <ExerciseSet>()
                        {
                            new ExerciseSet {
                                Reps = 10, Weight = 30
                            },
                            new ExerciseSet {
                                Reps = 8, Weight = 35
                            },
                            new ExerciseSet {
                                Reps = 7, Weight = 40
                            },
                            new ExerciseSet {
                                Reps = 6, Weight = 45
                            },
                            new ExerciseSet {
                                Reps = 4, Weight = 50
                            },
                        }
                    },
                    new ExercisePlan
                    {
                        Name = "Deadlift",
                        Sets = new List <ExerciseSet>()
                        {
                            new ExerciseSet {
                                Reps = 8, Weight = 110
                            },
                            new ExerciseSet {
                                Reps = 6, Weight = 115
                            },
                            new ExerciseSet {
                                Reps = 5, Weight = 120
                            },
                            new ExerciseSet {
                                Reps = 4, Weight = 125
                            },
                            new ExerciseSet {
                                Reps = 3, Weight = 130
                            },
                        }
                    },
                }
            }
                );

            var tr      = context.Trainings.FirstOrDefault(t => t.Name == "test_training_1");
            var testAth = context.Users.FirstOrDefault(u => u.UserName == "testathlete");

            tr.User = testAth;

            context.Trainings.AddOrUpdate(
                t => t.Name,
                new Training
            {
                Name      = "test_training_2",
                User      = testAth,
                Exercises = new List <ExercisePlan>
                {
                    new ExercisePlan
                    {
                        Name = "Rows",
                        Sets = new List <ExerciseSet>()
                        {
                            new ExerciseSet {
                                Reps = 10, Weight = 70
                            },
                            new ExerciseSet {
                                Reps = 8, Weight = 75
                            },
                            new ExerciseSet {
                                Reps = 7, Weight = 80
                            },
                        }
                    },
                    new ExercisePlan
                    {
                        Name = "Deadlift",
                        Sets = new List <ExerciseSet>()
                        {
                            new ExerciseSet {
                                Reps = 18, Weight = 60
                            },
                            new ExerciseSet {
                                Reps = 16, Weight = 65
                            },
                            new ExerciseSet {
                                Reps = 15, Weight = 70
                            },
                            new ExerciseSet {
                                Reps = 14, Weight = 75
                            },
                            new ExerciseSet {
                                Reps = 13, Weight = 80
                            },
                        }
                    },
                }
            }
                );

            context.Reports.AddOrUpdate(
                r => r.Id,
                new Report
            {
                DateTime = DateTime.Parse("30-01-2017"),
                Training = context.Trainings.FirstOrDefault(t => t.Name == "test_training_1")
            },
                new Report
            {
                DateTime = DateTime.Parse("05-02-2017"),
                Training = context.Trainings.FirstOrDefault(t => t.Name == "test_training_1")
            },
                new Report
            {
                DateTime = DateTime.Parse("10-02-2017"),
                Training = context.Trainings.FirstOrDefault(t => t.Name == "test_training_1")
            },
                new Report
            {
                DateTime = DateTime.Parse("15-02-2017"),
                Training = context.Trainings.FirstOrDefault(t => t.Name == "test_training_1")
            },
                new Report
            {
                DateTime = DateTime.Parse("20-02-2017"),
                Training = context.Trainings.FirstOrDefault(t => t.Name == "test_training_1")
            }
                );

            try
            {
                context.SaveChanges();

                userManager.AddToRole("1", "admin");
                userManager.AddToRole("2", "athlete");
                userManager.AddToRole("3", "trainer");

                context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                var a = "a";
            }

            //  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" }
            //    );
            //
        }
        static Startup()
        {
            PublicClientId = "self";

            UserManagerFactory = () =>
            {
                var context = new IdentityDbContext();
                System.Data.Entity.Database.SetInitializer<IdentityDbContext>(new IdentityDbInitializer());

                var userStore = new UserStore<IdentityUser>(context);
                userStore.DisposeContext = true;

                return new UserManager<IdentityUser>(userStore);
            };

            RoleManagerFactory = () =>
            {
                var context = new IdentityDbContext();
                System.Data.Entity.Database.SetInitializer<IdentityDbContext>(new IdentityDbInitializer());

                var roleStore = new RoleStore<IdentityRole>(context);

                return new RoleManager<IdentityRole>(roleStore);
            };

            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = true
            };
        }