コード例 #1
0
    /// <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");
        }
    }
コード例 #2
0
        public void SeedData(EmployerEmployeeHuntDbContext context)
        {
            var userStore = new UserStore<User>(context);
            var userManager = new UserManager<User>(userStore);

            var adminUser = new User
            {
                UserName = AdministratorUserName,
                Email = AdministratorUserName
            };

            var headhunterUser = new User
            {
                UserName = HeadhunterUserName,
                Email = HeadhunterUserName
            };

            var developerUser = new User
            {
                UserName = DeveloperUserName,
                Email = DeveloperUserName
            };

            var employerUser = new User
            {
                UserName = EmployerUserName,
                Email = EmployerUserName
            };

            userManager.Create(adminUser, AdministratorPassword);
            userManager.Create(headhunterUser, HeadhunterPassword);
            userManager.Create(developerUser, DeveloperPassword);
            userManager.Create(employerUser, EmployerPassword);

            userManager.AddToRole(adminUser.Id, GlobalConstants.AdministratorRoleName);
            userManager.AddToRole(headhunterUser.Id, GlobalConstants.HeadhunterRoleName);
            userManager.AddToRole(developerUser.Id, GlobalConstants.UserRoleName);
            userManager.AddToRole(employerUser.Id, GlobalConstants.UserRoleName);

            for (int i = 0; i < 60; i++)
            {
                var currentUser = new User
                {
                    Email = string.Format("user_{0}@somemail.com", i + 1),
                    UserName = string.Format("user_{0}", i + 1)
                };

                userManager.Create(currentUser, currentUser.Email);

                if (i % 2 == 0)
                {
                    userManager.AddToRole(currentUser.Id, GlobalConstants.HeadhunterRoleName);
                }
                else
                {
                    userManager.AddToRole(currentUser.Id, GlobalConstants.UserRoleName);
                }
            }
        }
コード例 #3
0
ファイル: DbConfig.cs プロジェクト: uaandrei/d4232ffg
        private static void SetupRolesAndUsers(DbContext context)
        {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            // add roles
            if (!roleManager.RoleExists(Role.Guest.ToString()))
                roleManager.Create(new IdentityRole(Role.Guest.ToString()));
            if (!roleManager.RoleExists(Role.Supplier.ToString()))
                roleManager.Create(new IdentityRole(Role.Supplier.ToString()));
            if (!roleManager.RoleExists(Role.Deactivated.ToString()))
                roleManager.Create(new IdentityRole(Role.Deactivated.ToString()));
            if (!roleManager.RoleExists(Role.User.ToString()))
                roleManager.Create(new IdentityRole(Role.User.ToString()));
            var adminRole = roleManager.FindByName(Role.Admin.ToString());
            if (adminRole == null)
            {
                adminRole = new IdentityRole(Role.Admin.ToString());
                roleManager.Create(adminRole);
            }
            #if DEBUG
            //add admin user
            var admin = userManager.Find(Admin_User, Admin_Pass);
            if (admin == null)
            {
                admin = new ApplicationUser
                {
                    UserName = Admin_User,
                    Email = Admin_Mail,
                    EmailConfirmed = true
                };
                var result = userManager.Create(admin, Admin_Pass);
                // TODO: verify returned IdentityResult
                userManager.AddToRole(admin.Id, Role.Admin.ToString());
                result = userManager.SetLockoutEnabled(admin.Id, false);
            }

            var rolesForUser = userManager.GetRoles(admin.Id);
            if (!rolesForUser.Contains(adminRole.Name))
            {
                var result = userManager.AddToRole(admin.Id, adminRole.Name);
            }

            //add normal user
            if (userManager.Find("*****@*****.**", "1q2w3e4r") == null)
            {
                var user = new ApplicationUser
                {
                    UserName = "******",
                    Email = "*****@*****.**",
                    EmailConfirmed = true
                };
                userManager.Create(user, "1q2w3e4r");
                // TODO: verify returned IdentityResult
                userManager.AddToRole(user.Id, Role.User.ToString());
            }
            #endif
        }
コード例 #4
0
        public static void Seed(ApplicationDbContext context)
        {
            UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(context);
            UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);

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

            if (!roleManager.RoleExists("Admin"))
                roleManager.Create(new Role { Name = "Admin" });

            if (!roleManager.RoleExists("User"))
                roleManager.Create(new Role { Name = "User" });

            IdentityResult result = null;

            ApplicationUser user1 = userManager.FindByName("*****@*****.**");

            if (user1 == null)
            {
                user1 = new ApplicationUser { Email = "*****@*****.**", UserName = "******" };
            }

            result = userManager.Create(user1, "asdfasdf");
            if (!result.Succeeded)
            {
                string error = result.Errors.FirstOrDefault();
                throw new Exception(error);
            }

            userManager.AddToRole(user1.Id, "Admin");
            user1 = userManager.FindByName("*****@*****.**");

            ApplicationUser user2 = userManager.FindByName("*****@*****.**");

            if (user2 == null)
            {
                user2 = new ApplicationUser { Email = "*****@*****.**", UserName = "******" };
            }

            result = userManager.Create(user2, "asdfasfd");
            if (!result.Succeeded)
            {
                string error = result.Errors.FirstOrDefault();
                throw new Exception(error);
            }

            userManager.AddToRole(user2.Id, "User");
            user2 = userManager.FindByName("*****@*****.**");
        }
コード例 #5
0
ファイル: UserController.cs プロジェクト: raberana/Readpublic
        public HttpResponseMessage AddUser(UserSignUpViewModel userParam)
        {
            UserManager userManager = new UserManager();
            HistoryManager historyManager = new HistoryManager();
            try
            {
                var user = new User();
                user.UserName = userParam.UserName;
                user.Password = userParam.Password;
                user.Email = userParam.Email;
                user.FirstName = userParam.FirstName;
                user.MiddleName = userParam.MiddleName;
                user.LastName = userParam.LastName;

                userManager.Create(user);
                var dbUser = userManager.FindUserEmail(user.Email);
                historyManager.AddHistory(new History(dbUser)
                {
                    Activity = Activities.Joined,
                    Description = Helper.GenerateActivityDescription(dbUser, Activities.Joined)
                });
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
                return response;
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
            }
        }
コード例 #6
0
 private void CreateAndLoginUser()
 {
     if (!IsValid)
     {
         return;
     }
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = userName.Text };
     IdentityResult result = manager.Create(user);
     if (result.Succeeded)
     {
         var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
         if (loginInfo == null)
         {
             Response.Redirect("~/Account/Login");
             return;
         }
         result = manager.AddLogin(user.Id, loginInfo.Login);
         if (result.Succeeded)
         {
             IdentityHelper.SignIn(manager, user, isPersistent: false);
             IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
             return;
         }
     }
     AddErrors(result);
 }
        public ActionResult Doctors_Create([DataSourceRequest]DataSourceRequest request, DoctorGridViewModel doctor)
        {
            if (this.ModelState.IsValid)
            {
                //TODO:Create service for users
                var context = new MyMedicalGuideDbContext();
                var userManager = new UserManager<User>(new UserStore<User>(context));
                var userDoctor = new User()
                {
                    Email = doctor.Email,
                    FirstName = doctor.FirstName,
                    LastName = doctor.LastName,
                    PhoneNumber = doctor.PhoneNumber,
                    UserName = doctor.Username
                };
                var hospitalId = this.TempData["hospitalId"];
                userManager.Create(userDoctor, doctor.Password);
                var DoctorDb = new MyMedicalGuide.Data.Models.Doctor() { User = userDoctor, HospitalId = (int)hospitalId, DepartmentId = doctor.DepartmentId, CreatedOn = DateTime.Now };
                context.Doctors.Add(DoctorDb);

                userManager.AddToRole(userDoctor.Id, "Doctor");

            }

            return this.Json(new[] { doctor }.ToDataSourceResult(request, this.ModelState));
        }
コード例 #8
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                var user = new IdentityUser() { UserName = txtUsername.Text };
                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    Response.Redirect("/user/index.aspx");

                }
                else
                {
                    lblStatus.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception d)
            {
                Response.Redirect("/error.aspx");
            }
        }
コード例 #9
0
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                var user = new IdentityUser() { UserName = txtUsername.Text };

                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    //lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
                    //lblStatus.CssClass = "label label-success";
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    Response.Redirect("admin/main-menu.aspx");
                }
                else
                {
                    lblStatus.Text = result.Errors.FirstOrDefault();
                    lblStatus.CssClass = "label label-danger";
                }
            }
            catch (Exception q)
            {
                Response.Redirect("/error.aspx");
            }
        }
コード例 #10
0
ファイル: SeedServices.cs プロジェクト: rswetnam/GoodBoating
        public static ApplicationUser CreateUser(UserManager<ApplicationUser> userManager, string email, string firstName, string lastName,
           string password, bool lockOutEnabled)
        {
            var user = userManager.FindByName(email);

            if (user == null)
            {
                user = new ApplicationUser
                {
                    UserName = email,
                    Email = email,
                    FirstName = firstName,
                    LastName = lastName,
                    EmailConfirmed = true
                };
                try
                {
                    userManager.Create(user, password);
                }
                catch (Exception ex)
                {
                    Log4NetHelper.Log("Error creating Admin User", LogLevel.ERROR, "AspNetUser", 1, "none", ex);
                }
                userManager.SetLockoutEnabled(user.Id, lockOutEnabled);
            }
            return user;
        }
コード例 #11
0
 public void GetUserClaimSyncTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("u1");
     var result = manager.Create(user);
     UnitTestHelper.IsSuccess(result);
     Assert.NotNull(user);
     var claims = new[]
     {
         new Claim("c1", "v1"),
         new Claim("c2", "v2"),
         new Claim("c3", "v3")
     };
     foreach (Claim c in claims)
     {
         UnitTestHelper.IsSuccess(manager.AddClaim(user.Id, c));
     }
     var userClaims = new List<Claim>(manager.GetClaims(user.Id));
     Assert.Equal(3, userClaims.Count);
     foreach (Claim c in claims)
     {
         Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value));
     }
 }
コード例 #12
0
        public static void Initialize(MacheteContext DB)
        {
            IdentityResult ir;

            var rm = new RoleManager<IdentityRole>
               (new RoleStore<IdentityRole>(DB));
            ir = rm.Create(new IdentityRole("Administrator"));
            ir = rm.Create(new IdentityRole("Manager"));
            ir = rm.Create(new IdentityRole("Check-in"));
            ir = rm.Create(new IdentityRole("PhoneDesk"));
            ir = rm.Create(new IdentityRole("Teacher"));
            ir = rm.Create(new IdentityRole("User"));
            ir = rm.Create(new IdentityRole("Hirer")); // This role is used exclusively for the online hiring interface

            var um = new UserManager<ApplicationUser>(
                new UserStore<ApplicationUser>(DB));
            var user = new ApplicationUser()
            {
                UserName = "******",
                IsApproved = true,
                Email = "*****@*****.**"
            };

            ir = um.Create(user, "ChangeMe");
            ir = um.AddToRole(user.Id, "Administrator"); //Default Administrator, edit to change
            ir = um.AddToRole(user.Id, "Teacher"); //Required to make tests work
            DB.Commit();
        }
コード例 #13
0
        protected void RadGridUserList_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            var editableitem = ((GridEditableItem)e.Item);
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            ///
            var useStore = new UserStore<AppUser>(new ApplicationDbContext());
            var manager = new UserManager<AppUser>(useStore);

            string LogInUserName=(editableitem.FindControl("RtxtLoginID") as RadTextBox).Text.Trim();

            var user = new AppUser { UserName = LogInUserName, FName = (editableitem.FindControl("RtxtFirstName") as RadTextBox).Text, LName = (editableitem.FindControl("RtxtLastName") as RadTextBox).Text };
            IdentityResult result = manager.Create(user, (editableitem.FindControl("RtxtPassword") as RadTextBox).Text);

            if (result.Succeeded)
            {
                //Get The Current Created UserInfo
                AppUser CreatedUser = manager.FindByName(LogInUserName);

                var RoleAddResult = manager.AddToRole(CreatedUser.Id.Trim(), (editableitem.FindControl("RDDListRole") as RadDropDownList).SelectedItem.Text.Trim());

                lblMessage.Text = string.Format("User {0} is creted successfully", user.UserName);
            }

            else
            {

                lblMessage.Text = result.Errors.FirstOrDefault();
                e.Canceled = true;
            }
        }
コード例 #14
0
        protected void RegisterButton_Click(object sender, EventArgs e)
        {
            //crete new userStore and userManager objects
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            var user = new IdentityUser()
            {
                UserName = UserNameTextBox.Text,
                PhoneNumber = PhoneNumberTextBox.Text,
                Email = EmailTextBox.Text
            };
            //create new user in the dbb and store the resukt
            IdentityResult result = userManager.Create(user, PasswordTextBox.Text);
            //check if succesfully registered
            if (result.Succeeded)
            {
                //authenticate and login new user
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);//store info in session

                //sign in
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);

                //redirect to main menu
                Response.Redirect("~/Secured/TodoList.aspx");

            }
            else
            {
                //display error in the AlertFlash div
                StatusLabel.Text = result.Errors.FirstOrDefault();
                AlertFlash.Visible = true;
            }
        }
コード例 #15
0
ファイル: RoleActions.cs プロジェクト: SCCapstone/ZVerse
        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");
            }
        }
コード例 #16
0
        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");
            }
        }
コード例 #17
0
ファイル: Register.aspx.cs プロジェクト: masterhou/webgl2012
 protected void CreateUser_Click(object sender, EventArgs e)
 {
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = UserName.Text };
     IdentityResult result = manager.Create(user, Password.Text);
     if (result.Succeeded)
     {
         ApplicationUser newUser = manager.Find(UserName.Text, Password.Text);
         var sa = new StoredAccount();
         sa.CreateNewAccount(newUser.Id,Email.Text);
         var returnUrl = Request.QueryString["ReturnUrl"];
         IdentityHelper.SignIn(manager, user, isPersistent: false);
         if (returnUrl == null)
         {
             IdentityHelper.RedirectToReturnUrl("~/Game/User-Home.aspx", Response);
         }
         else
         {
             IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
         }
     }
     else
     {
         ErrorMessage.Text = result.Errors.FirstOrDefault();
     }
 }
コード例 #18
0
ファイル: ImportUsers.cs プロジェクト: deyantodorov/Healthy
        private void CreateUser(ApplicationDbContext context, string userName, string userEmail, string userPass, string userRole)
        {
            if (context.Users.Any())
            {
                return;
            }

            var store = new UserStore<User>(context);
            var manager = new UserManager<User>(store)
            {
                PasswordValidator = new PasswordValidator
                {
                    RequiredLength = WebConstants.MinUserPasswordLength,
                    RequireNonLetterOrDigit = false,
                    RequireDigit = false,
                    RequireLowercase = false,
                    RequireUppercase = false,
                }
            };

            var user = new User
            {
                UserName = userName,
                Email = userEmail
            };

            manager.Create(user, userPass);
            manager.AddToRole(user.Id, userRole);
        }
コード例 #19
0
ファイル: Helper.cs プロジェクト: yschermer/PC4U
        public static void CreateUserByRole(RoleEnum role, ApplicationUser user, string password, ApplicationDbContext db)
        {
            user.Id = Guid.NewGuid().ToString();

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

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    manager.Create(user, password);
                    db.SaveChanges();

                    manager.AddToRole(user.Id, Enum.GetName(typeof(RoleEnum), (int)role));
                    db.SaveChanges();

                    dbContextTransaction.Commit();
                }
                catch (Exception)
                {
                    dbContextTransaction.Rollback();
                }
            }
        }
コード例 #20
0
ファイル: Global.asax.cs プロジェクト: dmitriy1024/GreenHouse
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

            using (var context = new ApplicationDbContext())
            {
                if (context.Roles.Where(a => String.Compare(a.Name, "admin", true) == 0).Count() == 0)
                {
                    context.Roles.Add(new IdentityRole("admin"));
                    context.SaveChanges();
                }

                var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                var user = new ApplicationUser() { UserName = "******", Email = "*****@*****.**" };
                var createResult = um.Create(user, "Aa123!");
                if(createResult.Succeeded)
                {
                    var roleresult = um.AddToRole(user.Id, "admin");
                }
            }
        }
コード例 #21
0
        public static void ClassInitialize(TestContext testContext)
        {
            // Since users are not cleaned up by transactions, we create the users we need for the test once.
            using (var context = new EventContext())
            {
                var userManager = new UserManager<AppUser>(new UserStore<AppUser>(context));
                AppUser user1 = new AppUser() { UserName = "******" };
                userManager.Create(user1, "TestPassword");

                AppUser user2 = new AppUser() { UserName = "******" };
                userManager.Create(user2, "TestPassword");

                AppUser user3 = new AppUser() { UserName = "******" };
                userManager.Create(user3, "TestPassword");
            }
        }
コード例 #22
0
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        var userMgr = new UserManager();

        var employee = new Employee()
        {
            UserName = UserName.Text,
            FirstName = FirstName.Text,
            LastName = LastName.Text,
            PhoneNumber = PhoneNumber.Text,
            Email = Email.Text,
            Department = (Grievance.GrievanceTypes)Convert.ToInt32(Department.SelectedValue)
        };
        IdentityResult IdUserResult = userMgr.Create(employee, Password.Text);

        if (IdUserResult.Succeeded)
        {
            if (!userMgr.IsInRole(employee.Id, "Employee")) // Only users of type "Employee" can be created from the "Register Employee" page.
            {
                IdUserResult = userMgr.AddToRole(employee.Id, "Employee");
            }
            SuccessMessage.Text = "Employee created successfully";
            SuccessMessage.Visible = true;
            ErrorMessage.Visible = false;

           UserName.Text =  FirstName.Text = LastName.Text = PhoneNumber.Text = Email.Text = Password.Text = ConfirmPassword.Text = string.Empty;
        }
        else
        {
            ErrorMessage.Text = IdUserResult.Errors.FirstOrDefault();
            ErrorMessage.Visible = true;
            SuccessMessage.Visible = false;
        }
        
    }
コード例 #23
0
ファイル: register.aspx.cs プロジェクト: irichardi/assign2
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            // Default UserStore constructor uses the default connection string named: DefaultConnectionEF
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);

            var user = new IdentityUser() { UserName = txtUName.Text };
            user.Email = txtEmail.Text;
            user.PhoneNumber = txtPhone.Text;
            IdentityResult result = manager.Create(user, txtPass.Text);

            if (result.Succeeded)
            {
                lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                Response.Redirect("/admin/main.aspx");

            }
            else
            {
                lblStatus.Text = result.Errors.FirstOrDefault();
            }
        }
コード例 #24
0
        public ActionResult Register(User user)
        {
            string temp = user.Password;
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);

            var user2 = new IdentityUser() { UserName = user.Username };
            IdentityResult result = manager.Create(user2, user.Password);

            if (result.Succeeded)
            {
                TempData["message"] = "Identity user create worked";

                //var temp2 =  this.ControllerContext.HttpContext;
                var authenticationManager = HttpContext.GetOwinContext().Authentication;
                //var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user2, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                //Response.Redirect("~/Login.aspx");
                //return View("Login");

                if (User.Identity.IsAuthenticated)
                {
                    TempData["message"] += "/n   User.Identity.IsAuthenticate working";
                }

                return View("Index");
            }
            else
            {
                TempData["message"] = "Failed: " + result.Errors.FirstOrDefault();
            }
            return View("Index");
        }
コード例 #25
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            // Default UserStore constructor uses the default connection string named: DefaultConnection
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);
            //IdentityResult IdUserResult;

            var user = new IdentityUser() { UserName = UserName.Text };
            IdentityResult result = manager.Create(user, Password.Text);

            if (result.Succeeded)
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);

               // IdUserResult = manager.AddToRole(manager.FindByName(user.UserName).Id, "member");

                Session["uPass"] = Password.Text;
                Response.Redirect("~/WebForm2.aspx");
                // StatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName);
            }
            else
            {
                StatusMessage.Text = result.Errors.FirstOrDefault();
            }
        }
コード例 #26
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            var manager = new UserManager();
            var user = new ApplicationUser() { UserName = UserName.Text };
            IdentityResult result = manager.Create(user, Password.Text);
            if (result.Succeeded)
            {

                result = manager.AddToRole(user.Id, "Student");

                var std = new Student();
                std.FirstName = FirstName.Text;
                std.LastName = lastName.Text;
                std.UserId = user.Id;
                std.BirthDate = DateTime.Now;

                CourseContext cc = new CourseContext();
                cc.Students.Add(std);
                cc.SaveChanges();

                IdentityHelper.SignIn(manager, user, isPersistent: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);

            }
            else
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
コード例 #27
0
ファイル: Default.aspx.cs プロジェクト: ramyothman/RBM
 private void CreateAndLoginUser(string username, string email)
 {
     Session["dummy"] = "dummy";
     if (!IsValid)
     {
         return;
     }
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = username, Email = email, Id = Guid.NewGuid().ToString() };
     var userM = (from y in manager.Users where y.UserName == username select y).FirstOrDefault();
     if(userM == null)
     {
         IdentityResult result = manager.Create(user);
         if (result.Succeeded)
         {
             IdentityHelper.SignIn(manager, user, isPersistent: false);
             IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
             return;
         }
         AddErrors(result);
     }
     else
     {
         IdentityHelper.SignIn(manager, userM, isPersistent: false);
         IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
         return;
     }
 }
コード例 #28
0
ファイル: IdentityModels.cs プロジェクト: GudjonGeir/SubHub
 public bool CreateUser(ApplicationUser user, string password)
 {
     var um = new UserManager<ApplicationUser>(
         new UserStore<ApplicationUser>(new SubHubContext()));
     var idResult = um.Create(user, password);
     return idResult.Succeeded;
 }
コード例 #29
0
ファイル: DataSeeder.cs プロジェクト: Vyara/SciHub
        internal static void SeedAdmin(SciHubDbContext context)
        {
            const string adminUserName = "******";
            const string adminPassword = "******";

            if (context.Users.Any(u => u.UserName == adminUserName))
            {
                return;
            }

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

            var admin = new User
            {
                UserName = adminUserName,
                Email = "*****@*****.**",
                FirstName = "Admin",
                LastName = "Adminos",
                Avatar = UserDefaultPictureConstants.Female,
                Gender = Gender.Female,
                About = "I am the Decider!"
            };

            userManager.Create(admin, adminPassword);
            userManager.AddToRole(admin.Id, UserRoleConstants.Admin);
            userManager.AddToRole(admin.Id, UserRoleConstants.Default);

            context.SaveChanges();
        }
コード例 #30
0
ファイル: DataSeeder.cs プロジェクト: AdrianApostolov/GiftBox
        internal static void SeedAdmin(GiftBoxDbContext context)
        {
            const string AdminEmail = "*****@*****.**";
            const string AdminPassword = "******";

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

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

            var admin = new User
            {
                FirstName = "Adrian",
                UserRole = "Admin",
                LastName = "Apostolov",
                Email = AdminEmail,
                UserName = "******",
                PhoneNumber = "0889972697",
                ImageUrl = GlobalConstants.DefaultUserPicture,
            };

            userManager.Create(admin, AdminPassword);
            userManager.AddToRole(admin.Id, GlobalConstants.AdminRole);
            userManager.AddToRole(admin.Id, GlobalConstants.UserRole);
            userManager.AddToRole(admin.Id, GlobalConstants.HomeAdministrator);

            context.SaveChanges();
        }
コード例 #31
0
        protected override void Seed(LojaVirtual.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

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

                manager.Create(role);
            }

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

                manager.Create(role);
            }

            var PasswordHash = new PasswordHasher();

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser
                {
                    UserName     = "******",
                    Name         = "Admin",
                    Telephone    = "51 92375412",
                    Email        = "*****@*****.**",
                    PasswordHash = PasswordHash.HashPassword("s2b")
                };

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

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser
                {
                    UserName     = "******",
                    Name         = "Hugo",
                    Telephone    = "51 92432432",
                    Email        = "*****@*****.**",
                    PasswordHash = PasswordHash.HashPassword("s2b")
                };

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

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser
                {
                    UserName     = "******",
                    Name         = "Ze",
                    Telephone    = "51 87655412",
                    Email        = "*****@*****.**",
                    PasswordHash = PasswordHash.HashPassword("s2b")
                };


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

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser
                {
                    UserName     = "******",
                    Name         = "Luis",
                    Telephone    = "51 32334412",
                    Email        = "*****@*****.**",
                    PasswordHash = PasswordHash.HashPassword("s2b")
                };

                manager.Create(user);
                manager.AddToRole(user.Id, "User");
            }
        }
コード例 #32
0
        protected override void Seed(RecipeBuilder_Version_1.DAL.RecipeBuilder2Context context)
        {
            /*if (System.Diagnostics.Debugger.IsAttached == false)
             *  System.Diagnostics.Debugger.Launch();*/
            var forums = new List <Forum>()
            {
                new Forum {
                    Categories = new List <Category>(), ForumName = "Main"
                }
            };

            forums.ForEach(s => context.Fora.AddOrUpdate(p => p.ForumName, s));

            InitializeIdentityForEF(context);
            var userManager = new UserManager <Member>(
                new UserStore <Member>(context));

            var members = new List <Member>
            {
                new Member {
                    Email = "*****@*****.**", UserName = "******", FirstName = "Sam", LastName = "Ple", Password = "******", NickName = "ABCMouse", DateJoined = DateTime.Parse("2016-01-25"), MemberID = 1, Messages = new List <Message>()
                },
                new Member {
                    Email = "*****@*****.**", UserName = "******", FirstName = "Exam", LastName = "Ple", Password = "******", NickName = "BCDMouse", DateJoined = DateTime.Parse("2015-05-02"), MemberID = 2, Messages = new List <Message>()
                },
                new Member {
                    Email = "*****@*****.**", UserName = "******", FirstName = "Lonnie", LastName = "Teter", Password = "******", NickName = "ChefCode", DateJoined = DateTime.Parse("2014-12-06"), MemberID = 3, Messages = new List <Message>()
                },
                new Member {
                    Email = "*****@*****.**", UserName = "******", FirstName = "Parker", LastName = "Davis", Password = "******", NickName = "ChefCodejr", DateJoined = DateTime.Parse("2014-06-12"), MemberID = 4, Messages = new List <Message>()
                },
                new Member {
                    Email = "*****@*****.**", UserName = "******", FirstName = "Stephani", LastName = "Day", Password = "******", NickName = "MrsChefCode", DateJoined = DateTime.Parse("2013-11-11"), MemberID = 5, Messages = new List <Message>()
                }
            };

            //Now I save each member by logging them in and out to hash their password using OWIN -LONNIE
            members.ForEach(s => context.Users.AddOrUpdate(p => p.Email, s));
            foreach (var member in members)
            {
                var user = context.Users.SingleOrDefault(u => u.Email == member.Email);
                if (user == null)
                {
                    var result = userManager.Create(member, member.Password);
                    if (result.Succeeded)
                    {
                        InitializeAuthenticationApplyAppCookie(userManager, member);
                    }
                }
            }
            members.ForEach(s => context.Users.AddOrUpdate(p => p.Email, s));
            context.SaveChanges();

            var topics = new List <Topic>
            {
                new Topic {
                    Description = "All things food", Messages = new List <Message>()
                },
                new Topic {
                    Description = "Everything under the sun and beyond", Messages = new List <Message>()
                },
                new Topic {
                    Description = "Things don't add up", Messages = new List <Message>()
                },
                new Topic {
                    Description = "Post college life", Messages = new List <Message>()
                },
                new Topic {
                    Description = "Before they were professionals", Messages = new List <Message>()
                }
            };

            topics.ForEach(s => context.Topics.AddOrUpdate(p => p.Description, s));
            context.SaveChanges();

            var categories = new List <Category>()
            {
                new Category {
                    ForumID = forums[0].ForumID, Messages = new List <Message>(), Title = "The Future", Description = "Fast-forward to the past, we're going back to the future. "
                },
                new Category {
                    ForumID = forums[0].ForumID, Messages = new List <Message>(), Title = "Sustainability", Description = "Re-cycle, Re-use, Re-plenish and Re-plant, and make a profit as a by-product. "
                },
                new Category {
                    ForumID = forums[0].ForumID, Messages = new List <Message>(), Title = "Restaurants", Description = "We love to talk about local restaurants. "
                }
            };

            categories.ForEach(s => context.Categories.AddOrUpdate(p => p.Title, s));
            context.SaveChanges();

            var messages = new List <Message>
            {
                new Message {
                    MemberID = members.Single(s => s.Email == "*****@*****.**").MemberID,
                    TopicID  = topics[0].TopicID, Subject = "I Love Food", Body = "How long you got...", Date = DateTime.Parse("2005-09-01"), Comments = new List <Comment>(), CategoryID = categories[0].CategoryID
                },

                new Message {
                    MemberID = members.Single(s => s.Email == "*****@*****.**").MemberID,
                    TopicID  = topics[0].TopicID, Subject = "RE:I Love Food", Body = "I Got awhile...", Date = DateTime.Parse("2005-09-02"), CategoryID = categories[0].CategoryID
                },

                new Message {
                    MemberID = members.Single(s => s.Email == "*****@*****.**").MemberID,
                    TopicID  = topics[0].TopicID, Subject = "RE:I Love Food", Body = "I Got awhile too...", Date = DateTime.Parse("2005-09-03"), Comments = new List <Comment>(), CategoryID = categories[0].CategoryID
                },

                new Message {
                    MemberID = members.Single(s => s.Email == "*****@*****.**").MemberID,
                    TopicID  = topics[1].TopicID, Subject = "I Hate Food", Body = "No How long you got...", Date = DateTime.Parse("2005-09-04"), CategoryID = categories[0].CategoryID
                },

                new Message {
                    MemberID = members.Single(s => s.Email == "*****@*****.**").MemberID,
                    TopicID  = topics[1].TopicID, Subject = "RE:I Hate Food", Body = "Save it buddy...", Date = DateTime.Parse("2005-09-05"), CategoryID = categories[0].CategoryID
                },

                new Message {
                    MemberID = members.Single(s => s.Email == "*****@*****.**").MemberID,
                    TopicID  = topics[2].TopicID, Subject = "I Love Science", Body = "Hey How long you got...", Date = DateTime.Parse("2005-09-06"), CategoryID = categories[0].CategoryID
                },

                new Message {
                    MemberID = members.Single(s => s.Email == "*****@*****.**").MemberID,
                    TopicID  = topics[3].TopicID, Subject = "I Love Math", Body = "How long do I got..?", Date = DateTime.Parse("2005-09-07"), CategoryID = categories[0].CategoryID
                },

                new Message {
                    MemberID = members.Single(s => s.Email == "*****@*****.**").MemberID,
                    TopicID  = topics[4].TopicID, Subject = "I Love My Career", Body = "I'll tell you how long I got....", Date = DateTime.Parse("2005-09-08"), CategoryID = categories[0].CategoryID
                },

                new Message {
                    MemberID = members.Single(s => s.Email == "*****@*****.**").MemberID,
                    TopicID  = topics[4].TopicID, Subject = "I Loved College", Body = "You Do that...", Date = DateTime.Parse("2005-09-09"), CategoryID = categories[0].CategoryID
                },

                new Message {
                    MemberID = members.Single(s => s.Email == "*****@*****.**").MemberID,
                    TopicID  = topics[4].TopicID, Subject = "I Love Science", Body = "I will you just watch..", Date = DateTime.Parse("2005-09-10"), CategoryID = categories[0].CategoryID
                }
            };

            messages.ForEach(s => context.Messages.AddOrUpdate(p => p.Body, s));

            context.SaveChanges();

            var comments = new List <Comment>()
            {
                new Comment {
                    MessageID = messages[0].MessageID, MemberID = members[2].MemberID, Date = DateTime.Parse("2005-10-01"), Body = "All Day :)"
                },
                new Comment {
                    MessageID = messages[0].MessageID, MemberID = members[2].MemberID, Date = DateTime.Parse("2005-10-02"), Body = "HellO??"
                },
                new Comment {
                    MessageID = messages[0].MessageID, MemberID = members[0].MemberID, Date = DateTime.Parse("2005-10-03"), Body = "Sorry I'm Back"
                },
                new Comment {
                    MessageID = messages[2].MessageID, MemberID = members[1].MemberID, Date = DateTime.Parse("2005-11-01"), Body = "What's up?"
                },
                new Comment {
                    MessageID = messages[0].MessageID, MemberID = members[0].MemberID, Date = DateTime.Parse("2005-11-02"), Body = "Comment on my own post"
                }
            };

            comments.ForEach(s => context.Comments.AddOrUpdate(p => p.Body, s));
            context.SaveChanges();

            AddOrUpdate_Comment_Into_Message(context, comments[0].Body, messages[0].Body);
            AddOrUpdate_Comment_Into_Message(context, comments[1].Body, messages[0].Body);
            AddOrUpdate_Comment_Into_Message(context, comments[2].Body, messages[0].Body);
            AddOrUpdate_Comment_Into_Message(context, comments[3].Body, messages[2].Body);
            AddOrUpdate_Comment_Into_Message(context, comments[4].Body, messages[0].Body);



            /* AddOrUpdate_Message_Into_Category(context, messages[0], categories[0].Title);
             * AddOrUpdate_Message_Into_Category(context, messages[1], categories[1].Title);
             * AddOrUpdate_Message_Into_Category(context, messages[2], categories[2].Title);
             * AddOrUpdate_Message_Into_Category(context, messages[3], categories[1].Title);
             * AddOrUpdate_Message_Into_Category(context, messages[4], categories[1].Title);
             * AddOrUpdate_Message_Into_Category(context, messages[5], categories[1].Title);
             * AddOrUpdate_Message_Into_Category(context, messages[6], categories[1].Title);
             * AddOrUpdate_Message_Into_Category(context, messages[7], categories[1].Title);
             * AddOrUpdate_Message_Into_Category(context, messages[8], categories[1].Title);
             * AddOrUpdate_Message_Into_Category(context, messages[9], categories[1].Title);*/

            context.SaveChanges();

            AddOrUpdate_Category_Into_Forum(context, categories[0].Title, forums[0].ForumName);
            AddOrUpdate_Category_Into_Forum(context, categories[1].Title, forums[0].ForumName);
            AddOrUpdate_Category_Into_Forum(context, categories[2].Title, forums[0].ForumName);

            context.SaveChanges();


            var unitOfMeasures = new List <UnitOfMeasure>()
            {
                new UnitOfMeasure {
                    Unit = "Pound", UnitQuantity = 1m
                },
                new UnitOfMeasure {
                    Unit = "Ounce", UnitQuantity = 1m
                },
                new UnitOfMeasure {
                    Unit = "Gallon", UnitQuantity = 1m
                },
                new UnitOfMeasure {
                    Unit = "Half-Gallon", UnitQuantity = 1m
                },
                new UnitOfMeasure {
                    Unit = "Quart", UnitQuantity = 1m
                },
                new UnitOfMeasure {
                    Unit = "Pint", UnitQuantity = 1m
                },
                new UnitOfMeasure {
                    Unit = "Cup", UnitQuantity = 1m
                },
                new UnitOfMeasure {
                    Unit = "Fluid-Ounce", UnitQuantity = 1m
                },
                new UnitOfMeasure {
                    Unit = "Each", UnitQuantity = 1m
                },
                new UnitOfMeasure {
                    Unit = "Table-Spoon", UnitQuantity = 1m
                },
                new UnitOfMeasure {
                    Unit = "Tea-Spoon", UnitQuantity = 1m
                }
            };

            unitOfMeasures.ForEach(s => context.UnitOfMeasures.AddOrUpdate(p => p.Unit, s));
            context.SaveChanges();

            var foodItems = new List <FoodItem>()
            {
                new FoodItem {
                    FoodName = "Apple", IndividualAsPurchasedWeight = 0.5m, PotentiallyHazardous = false, Specification = "Fresh", YieldPercentage = 1
                },
                new FoodItem {
                    FoodName = "Orange", IndividualAsPurchasedWeight = 0.5m, PotentiallyHazardous = false, Specification = "Fresh", YieldPercentage = 1
                },
                new FoodItem {
                    FoodName = "Lemon", IndividualAsPurchasedWeight = 0.5m, PotentiallyHazardous = false, Specification = "Fresh", YieldPercentage = 1
                },
                new FoodItem {
                    FoodName = "Tomato", IndividualAsPurchasedWeight = 0.5m, PotentiallyHazardous = false, Specification = "Fresh", YieldPercentage = 1
                },
                new FoodItem {
                    FoodName = "Lettuce", IndividualAsPurchasedWeight = 1m, PotentiallyHazardous = false, Specification = "Head of", YieldPercentage = 1
                },
                new FoodItem {
                    FoodName = "Bacon", IndividualAsPurchasedWeight = 4m, PotentiallyHazardous = true, Specification = "Cured", YieldPercentage = 1
                }
            };

            foodItems.ForEach(s => context.FoodItems.AddOrUpdate(p => p.FoodName, s));
            context.SaveChanges();

            var asPurchasedItems = new List <AsPurchasedItem>()
            {
                new AsPurchasedItem {
                    AsPurchasedName = "fooditem1", FoodItem = foodItems[0], AsPurchasedUnitQuantity = 50, UnitOfMeasure = unitOfMeasures[0], FoodItemQuantity = 1
                },
                new AsPurchasedItem {
                    AsPurchasedName = "fooditem2", FoodItem = foodItems[1], AsPurchasedUnitQuantity = 50, UnitOfMeasure = unitOfMeasures[0], FoodItemQuantity = 1
                },
                new AsPurchasedItem {
                    AsPurchasedName = "fooditem3", FoodItem = foodItems[2], AsPurchasedUnitQuantity = 50, UnitOfMeasure = unitOfMeasures[0], FoodItemQuantity = 1
                },
                new AsPurchasedItem {
                    AsPurchasedName = "fooditem4", FoodItem = foodItems[3], AsPurchasedUnitQuantity = 50, UnitOfMeasure = unitOfMeasures[0], FoodItemQuantity = 1
                },
                new AsPurchasedItem {
                    AsPurchasedName = "fooditem5", FoodItem = foodItems[4], AsPurchasedUnitQuantity = 50, UnitOfMeasure = unitOfMeasures[0], FoodItemQuantity = 1
                },
                new AsPurchasedItem {
                    AsPurchasedName = "fooditem6", FoodItem = foodItems[5], AsPurchasedUnitQuantity = 50, UnitOfMeasure = unitOfMeasures[0], FoodItemQuantity = 1
                }
            };

            asPurchasedItems.ForEach(s => context.AsPurchasedItems.AddOrUpdate(p => p.AsPurchasedName, s));
            context.SaveChanges();

            var packages = new List <Package>()
            {
                new Package {
                    AsPurchasedItem = asPurchasedItems[0], PackageCost = 100, VendorCode = "XYZ123", QRCode = "abc123"
                },
                new Package {
                    AsPurchasedItem = asPurchasedItems[1], PackageCost = 100, VendorCode = "XYZ123", QRCode = "abc124"
                },
                new Package {
                    AsPurchasedItem = asPurchasedItems[2], PackageCost = 100, VendorCode = "XYZ123", QRCode = "abc125"
                },
                new Package {
                    AsPurchasedItem = asPurchasedItems[3], PackageCost = 100, VendorCode = "XYZ123", QRCode = "abc126"
                },
                new Package {
                    AsPurchasedItem = asPurchasedItems[4], PackageCost = 100, VendorCode = "XYZ123", QRCode = "abc127"
                },
                new Package {
                    AsPurchasedItem = asPurchasedItems[5], PackageCost = 100, VendorCode = "XYZ123", QRCode = "abc128"
                },
            };

            packages.ForEach(s => context.Packages.AddOrUpdate(p => p.QRCode, s));
            context.SaveChanges();

/******************************************* Schema Extention ******************************************************************************************************************************************/
            var foods = new List <Food>()
            {
                new Food {
                    FoodName = "Apple", IndividualAsPurchasedWeight = 0.5m, PotentiallyHazardous = false, Specification = "Fresh", YieldPercentage = 1
                },
                new Food {
                    FoodName = "Orange", IndividualAsPurchasedWeight = 0.5m, PotentiallyHazardous = false, Specification = "Fresh", YieldPercentage = 1
                },
                new Food {
                    FoodName = "Lemon", IndividualAsPurchasedWeight = 0.5m, PotentiallyHazardous = false, Specification = "Fresh", YieldPercentage = 1
                },
                new Food {
                    FoodName = "Tomato", IndividualAsPurchasedWeight = 0.5m, PotentiallyHazardous = false, Specification = "Fresh", YieldPercentage = 1
                },
                new Food {
                    FoodName = "Lettuce", IndividualAsPurchasedWeight = 1m, PotentiallyHazardous = false, Specification = "Head of", YieldPercentage = 1
                },
                new Food {
                    FoodName = "Bacon", IndividualAsPurchasedWeight = 4m, PotentiallyHazardous = true, Specification = "Cured", YieldPercentage = 1
                }
            };

            foods.ForEach(s => context.Foods.AddOrUpdate(p => p.FoodName, s));
            context.SaveChanges();

            var recipes = new List <Recipe>()
            {
                new Recipe {
                    MenuItemQuantity = 1, RecipeCost = 3.00m, RecipeName = "BLT", Ingredients = new List <Ingredient>()
                },
                new Recipe {
                    MenuItemQuantity = 1, RecipeCost = 1.50m, RecipeName = "Citrus Salad", Ingredients = new List <Ingredient>()
                }
            };

            recipes.ForEach(s => context.Recipes.AddOrUpdate(p => p.RecipeName, s));
            context.SaveChanges();

            var ingredients = new List <Ingredient>()
            {
                new Ingredient {
                    Food = foods[5], UnitOfMeasure = unitOfMeasures[0], UnitQuantity = 0.5m, IngredientName = "Crispy Bacon", Preparation = "Render", Recipes = new List <Recipe>()
                },
                new Ingredient {
                    Food = foods[4], UnitOfMeasure = unitOfMeasures[0], UnitQuantity = 0.5m, IngredientName = "Sliced Tomato", Preparation = "Slice", Recipes = new List <Recipe>()
                },
                new Ingredient {
                    Food = foods[3], UnitOfMeasure = unitOfMeasures[0], UnitQuantity = 0.5m, IngredientName = "Crisp Lettuce", Preparation = "Shred", Recipes = new List <Recipe>()
                },
                new Ingredient {
                    Food = foods[2], UnitOfMeasure = unitOfMeasures[1], UnitQuantity = 12.5m, IngredientName = "Fresh Lemon", Preparation = "Cut in half & Squeeze", Recipes = new List <Recipe>()
                },
                new Ingredient {
                    Food = foods[1], UnitOfMeasure = unitOfMeasures[1], UnitQuantity = 10.5m, IngredientName = "Fresh Orange", Preparation = "Peel & Slice", Recipes = new List <Recipe>()
                },
                new Ingredient {
                    Food = foods[0], UnitOfMeasure = unitOfMeasures[1], UnitQuantity = 10.5m, IngredientName = "Fresh Apple", Preparation = "Peel & Slice", Recipes = new List <Recipe>()
                }
            };

            ingredients.ForEach(s => context.Ingredients.AddOrUpdate(p => p.IngredientName, s));
            context.SaveChanges();


            //var recipes = new List<Recipe>
            //{
            //    new Recipe { MenuItemQuantity = 1, RecipeCost = 3.00m, RecipeName = "BLT", Ingredients = new List<Ingredient>()
            //      DepartmentID = departments.Single( s => s.Name == "Engineering").DepartmentID,
            //      Instructors = new List<Instructor>()
            //    },
            //}

            AddOrUpdateIngredient(context, "BLT", "Crispy Bacon");
            AddOrUpdateIngredient(context, "BLT", "Sliced Tomato");
            AddOrUpdateIngredient(context, "BLT", "Crisp Lettuce");
            AddOrUpdateIngredient(context, "Citrus Salad", "Fresh Lemon");
            AddOrUpdateIngredient(context, "Citrus Salad", "Fresh Orange");
            AddOrUpdateIngredient(context, "Citrus Salad", "Fresh Apple");

            var menuItems = new List <MenuItem>()
            {
                new MenuItem {
                    MenuItemName = "BLT", RecipeID = recipes.Single(s => s.RecipeName == "BLT").RecipeID
                },
                new MenuItem {
                    MenuItemName = "Citrus Salad", RecipeID = recipes.Single(s => s.RecipeName == "Citrus Salad").RecipeID
                }
            };

            menuItems.ForEach(s => context.MenuItems.AddOrUpdate(p => p.MenuItemName, s));
            context.SaveChanges();

            var menuMeals = new List <MenuMeal>()
            {
                new MenuMeal {
                    MenuMealName = "BLT & Citrus Salad"
                }
            };

            menuMeals.ForEach(s => context.MenuMeals.AddOrUpdate(p => p.MenuMealName, s));
            context.SaveChanges();

            AddOrUpdate_MenuMeal_With_MenuItem(context, "BLT & Citrus Salad", "BLT");
            AddOrUpdate_MenuMeal_With_MenuItem(context, "BLT & Citrus Salad", "Citrus Salad");

            var menus = new List <Menu>()
            {
                new Menu()
                {
                    MenuName = "Dinner", MenuDesigner = "Lonnie", DateCreated = DateTime.Now
                }
            };

            menus.ForEach(s => context.Menus.AddOrUpdate(p => p.MenuName, s));
            context.SaveChanges();

            AddOrUpdate_MENU_With_MenuItem(context, "Dinner", "BLT");
            AddOrUpdate_MENU_With_MenuItem(context, "Dinner", "Citrus Salad");
            AddOrUpdate_MENU_With_MENUMEAL(context, "Dinner", "BLT & Citrus Salad");
        }
コード例 #33
0
ファイル: NomSeed.cs プロジェクト: iiTarun/iiCode
        protected override void Seed(NomEntities context)
        {
            GetBidUpImdicator().ForEach(c => context.BidUpIndicators.Add(c));
            GetCapacityTypeIndicator().ForEach(c => context.metadataCapacityTypeIndicator.Add(c));
            GetCycle().ForEach(c => context.metadataCycle.Add(c));
            GetExportDeclaration().ForEach(c => context.metadataExportDeclaration.Add(c));
            // GetFileStatus().ForEach(c => context.metadataFileStatu.Add(c));
            GetQuantityTypeIndicator().ForEach(c => context.metadataQuantityTypeIndicator.Add(c));
            GetRequestType().ForEach(c => context.metadataRequestType.Add(c));
            var contractList = ContractSeed.GetContract(); //.ForEach(c => context.Contract.Add(c));

            EmailTemplateSeed.GetEmailSeed().ForEach(c => context.EmailTemplates.Add(c));
            FileStatusSeed.GetFileStatus().ForEach(c => context.metadataFileStatu.Add(c));
            MetadataDataSetSeed.GetDataSet().ForEach(c => context.metadataDataset.Add(c));
            PipelineEncKeyInfoSeed.GetPipelineEncKeyInfo().ForEach(c => context.metadataPipelineEncKeyInfo.Add(c));
            SettingSeed.GetSettingData().ForEach(c => context.Setting.Add(c));
            metadataErrorCodeSeed.GetErrorCode().ForEach(c => context.metadataErrorCode.Add(c));

            GetSendingStatus().ForEach(c => context.SendingStages.Add(c));
            GetReceivingStages().ForEach(c => context.ReceivingStages.Add(c));
            var locationList = LocationsSeed.GetLocations();

            #region Identity Seed
            // add roles
            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);
            }
            //add users
            if (!(context.ShipperCompany.Any(u => u.DUNS == "837565548")))
            {
                var shipperCompany = new ShipperCompany
                {
                    Name           = "Shell",
                    DUNS           = "837565548",
                    IsActive       = true,
                    CreatedBy      = "",
                    CreatedDate    = DateTime.Now,
                    ModifiedBy     = "",
                    ModifiedDate   = DateTime.Now,
                    SubscriptionID = 0,
                    ShipperAddress = ""
                };
                context.ShipperCompany.Add(shipperCompany);
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser
                    {
                        UserName             = "******",
                        PhoneNumber          = "0797697898",
                        EmailConfirmed       = true,
                        Email                = "*****@*****.**",
                        PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "Monday02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper
                    {
                        UserId           = userToInsert.Id,
                        FirstName        = "Tiffany P",
                        LastName         = "On",
                        ShipperCompanyID = shipperCompany.ID,
                        IsActive         = true,
                        CreatedBy        = "",
                        CreatedDate      = DateTime.Now,
                        ModifiedBy       = "",
                        ModifiedDate     = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "Tuesday02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Rebecca J", LastName = "Newson", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "Wednesday02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Terry A", LastName = "Mcmillin", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "Thursday02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Amanda", LastName = "Boettcher", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "Friday02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Jason J", LastName = "Babin", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "Saturday02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Deepthi", LastName = "Bollu", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "Sunday02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Carly M", LastName = "Billington", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "Jan02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Jayme C", LastName = "D'Agnolo", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "Feb02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Brandon", LastName = "Johnson", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "March02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Tami L", LastName = "Covington", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "April02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Danielle", LastName = "Foster", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "May02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Christen", LastName = "Schaffer", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "June02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "John", LastName = "Powell", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "July02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Leslie", LastName = "May", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "August02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Justin", LastName = "Babb", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
            }
            if (!(context.ShipperCompany.Any(u => u.DUNS == "078711334")))
            {
                var shipperCompany = new ShipperCompany
                {
                    Name           = "Enercross",
                    DUNS           = "078711334",
                    IsActive       = true,
                    CreatedBy      = "",
                    CreatedDate    = DateTime.Now,
                    ModifiedBy     = "",
                    ModifiedDate   = DateTime.Now,
                    SubscriptionID = 0,
                    ShipperAddress = ""
                };
                context.ShipperCompany.Add(shipperCompany);
                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0797697898", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "Monday02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Gagan", LastName = "Deep", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }

                if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
                {
                    var userStore    = new UserStore <ApplicationUser>(context);
                    var userManager  = new UserManager <ApplicationUser>(userStore);
                    var userToInsert = new ApplicationUser {
                        UserName = "******", PhoneNumber = "0000000000", EmailConfirmed = true, Email = "*****@*****.**", PhoneNumberConfirmed = true,
                    };
                    userManager.Create(userToInsert, "Monday02__");
                    userManager.AddToRole(userToInsert.Id, "Admin");

                    var shipper = new Shipper {
                        UserId = userToInsert.Id, FirstName = "Gagan", LastName = "Deep", ShipperCompanyID = shipperCompany.ID, IsActive = true, CreatedBy = "", CreatedDate = DateTime.Now, ModifiedBy = "", ModifiedDate = DateTime.Now
                    };
                    context.Shipper.Add(shipper);
                }
            }
            #endregion

            #region Add Pipeline
            try
            {
                var pipelineList            = PipelineSeed.GetPipelines();
                var transactionTypeList     = TransactionTypesSeed.GetTransactionTypes();
                var tspList                 = TransportationServiceProviderSeed.GetTransportationServiceProvider();
                var pipelineTranTypeMapList = PipelineTransactionTypeMapSeed.GetPipelineTransactionTypeMap();
                var tpwList                 = TradingPartnerWorksheetSeed.GetTradingPartnerWorksheet();
                var counterPartyList        = CounterPartySeed.GetCounterParty();
                var pipeEncKeyInfoList      = PipelineEncKeyInfoSeed.GetPipelineEncKeyInfo();

                foreach (var tranType in transactionTypeList)
                {
                    var tt = new metadataTransactionType
                    {
                        Identifier = tranType.Identifier,
                        IsActive   = tranType.IsActive,
                        Name       = tranType.Name,
                        SequenceNo = tranType.SequenceNo
                    };
                    context.metadataTransactionType.Add(tt);
                    context.Commit();
                    var tranTypeMapOnPipeTTId = pipelineTranTypeMapList.Where(a => a.TransactionTypeID == tranType.ID).ToList();
                    foreach (var ttm in tranTypeMapOnPipeTTId)
                    {
                        var map = new Pipeline_TransactionType_Map
                        {
                            IsActive          = ttm.IsActive,
                            LastModifiedBy    = ttm.LastModifiedBy,
                            LastModifiedDate  = ttm.LastModifiedDate,
                            PathType          = ttm.PathType,
                            PipeDuns          = "",//pipe.DUNSNo,
                            PipelineID        = ttm.PipelineID,
                            TransactionTypeID = tt.ID,
                            CreatedBy         = "",
                            CreatedDate       = DateTime.Now
                        };
                        context.Pipeline_TransactionType_Map.Add(map);
                        context.Commit();
                    }
                }
                foreach (var tsp in tspList)
                {
                    var tspObj = new TransportationServiceProvider
                    {
                        CreatedBy    = tsp.CreatedBy,
                        CreatedDate  = tsp.CreatedDate,
                        DUNSNo       = tsp.DUNSNo,
                        IsActive     = tsp.IsActive,
                        ModifiedBy   = tsp.ModifiedBy,
                        ModifiedDate = tsp.ModifiedDate,
                        Name         = tsp.Name
                    };
                    context.TransportationServiceProvider.Add(tspObj);
                    context.Commit();
                    var tspPipeList = pipelineList.Where(a => a.TSPId == tsp.ID).ToList();
                    foreach (var pipe in tspPipeList)
                    {
                        var pipeObj = new Pipeline
                        {
                            IsActive     = pipe.IsActive,
                            ModelTypeID  = pipe.ModelTypeID,
                            ModifiedBy   = pipe.ModifiedBy,
                            ModifiedDate = pipe.ModifiedDate,
                            Name         = pipe.Name,
                            ToUseTSPDUNS = pipe.ToUseTSPDUNS,
                            TSPId        = tspObj.ID,
                            CreatedBy    = "",
                            CreatedDate  = DateTime.Now,
                            DUNSNo       = pipe.DUNSNo
                        };
                        context.Pipeline.Add(pipeObj);
                        context.Commit();

                        var pipeTpwList = tpwList.Where(a => a.PipelineID == pipe.ID).ToList();
                        foreach (var tpw in pipeTpwList)
                        {
                            var tpwObj = new TradingPartnerWorksheet
                            {
                                IsActive                = tpw.IsActive,
                                IsTest                  = tpw.IsTest,
                                KeyLive                 = tpw.KeyLive,
                                KeyTest                 = tpw.KeyTest,
                                ModifiedBy              = tpw.ModifiedBy,
                                ModifiedDate            = tpw.ModifiedDate,
                                Name                    = tpw.Name,
                                PasswordLive            = tpw.PasswordLive,
                                PasswordTest            = tpw.PasswordTest,
                                PipeDuns                = pipeObj.DUNSNo,
                                PipelineID              = pipeObj.ID,
                                ReceiveDataSeperator    = tpw.ReceiveDataSeperator,
                                ReceiveSegmentSeperator = tpw.ReceiveSegmentSeperator,
                                ReceiveSubSeperator     = tpw.ReceiveSubSeperator,
                                SendDataSeperator       = tpw.SendDataSeperator,
                                SendSegmentSeperator    = tpw.SendSegmentSeperator,
                                SendSubSeperator        = tpw.SendSubSeperator,
                                URLLive                 = tpw.URLLive,
                                URLTest                 = tpw.URLTest,
                                UsernameLive            = tpw.UsernameLive,
                                UsernameTest            = tpw.UsernameTest,
                                CreatedBy               = "",
                                CreatedDate             = DateTime.Now
                            };
                            context.TradingPartnerWorksheet.Add(tpwObj);
                        }
                        var conPipeList = contractList.Where(a => a.PipelineID == pipe.ID).ToList();
                        foreach (var conPipe in conPipeList)
                        {
                            var con = new Contract
                            {
                                IsActive       = conPipe.IsActive,
                                LocationFromID = conPipe.LocationFromID,
                                LocationToID   = conPipe.LocationToID,
                                MDQ            = conPipe.MDQ,
                                ModifiedBy     = conPipe.ModifiedBy,
                                ModifiedDate   = conPipe.ModifiedDate,
                                PipeDuns       = pipeObj.DUNSNo,
                                PipelineID     = pipeObj.ID,
                                ReceiptZone    = conPipe.ReceiptZone,
                                RequestNo      = conPipe.RequestNo,
                                RequestTypeID  = conPipe.RequestTypeID,
                                ShipperID      = 0,
                                ValidUpto      = conPipe.ValidUpto,
                                CreatedBy      = "",
                                DeliveryZone   = conPipe.DeliveryZone,
                                FuelPercentage = conPipe.FuelPercentage,
                                CreatedDate    = DateTime.Now
                            };
                            context.Contract.Add(con);
                        }
                        var locPipeList = locationList.Where(a => a.PipeDuns.Trim() == pipe.DUNSNo.Trim()).ToList();
                        foreach (var locPipe in locPipeList)
                        {
                            var loc = new Location
                            {
                                Identifier   = locPipe.Identifier,
                                IsActive     = locPipe.IsActive,
                                ModifiedBy   = locPipe.ModifiedBy,
                                ModifiedDate = locPipe.ModifiedDate,
                                Name         = locPipe.Name,
                                PipeDuns     = pipeObj.DUNSNo,
                                PipelineID   = pipeObj.ID,
                                PropCode     = locPipe.PropCode,
                                RDUsageID    = locPipe.RDUsageID,
                                CreatedBy    = locPipe.CreatedBy,
                                CreatedDate  = locPipe.CreatedDate
                            };
                            context.Location.Add(loc);
                        }
                        var ttmpList = context.Pipeline_TransactionType_Map.Where(a => a.PipelineID == pipe.ID).ToList();//pipelineTranTypeMapList.Where(a => a.PipelineID == pipe.ID).ToList();
                        foreach (var map in ttmpList)
                        {
                            map.PipelineID = pipeObj.ID;
                            map.PipeDuns   = pipeObj.DUNSNo;
                            context.Pipeline_TransactionType_Map.Attach(map);
                            var entry = context.Entry(map);
                            entry.Property(e => e.PipelineID).IsModified = true;
                            entry.Property(e => e.PipeDuns).IsModified   = true;
                            context.Commit();
                        }
                        var pipeEncKeyInfoPipeList = pipeEncKeyInfoList.Where(a => a.PipelineId == pipe.ID).ToList();
                        foreach (var peki in pipeEncKeyInfoPipeList)
                        {
                            peki.PipelineId = pipeObj.ID;
                            peki.PipeDuns   = pipeObj.DUNSNo;
                            context.metadataPipelineEncKeyInfo.Add(peki);
                        }
                    }
                }
                foreach (var cp in counterPartyList)
                {
                    context.CounterParty.Add(cp);
                }
            }
            catch (Exception ex)
            {
            }

            #endregion


            context.Commit();
        }
コード例 #34
0
        protected override void Seed(LSM.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" }
            //    );
            //

            // En massa komplicerad kod för att skapa nya användare och roller !!


            var courses = new List <Course>
            {
                new Course {
                    Name      = "Java", Description = "Coding Java",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01")
                },
                new Course {
                    Name      = "Python", Description = "Coding Pyhton",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01")
                },
                new Course {
                    Name      = "C#", Description = "Coding C#",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01")
                },
                new Course {
                    Name      = "Kurs med lång beskrivning", Description = "Proin tincidunt ullamcorper lectus, sit amet tempus neque maximus quis. Phasellus at lorem id nunc hendrerit congue quis eu odio. Praesent convallis vitae odio in posuere. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin blandit diam eu dignissim pharetra. In volutpat orci nec quam placerat, nec vehicula lacus vulputate. Nullam sagittis sollicitudin nisl, non blandit orci vestibulum at. Nullam leo est, finibus ut iaculis in, consectetur eu ligula. Integer nisi neque, tempus id orci ac, porttitor sodales nunc. Praesent pretium libero scelerisque, rhoncus purus in, consectetur risus. Praesent sollicitudin est nec lectus pretium, at bibendum purus volutpat. Quisque viverra imperdiet lacus, non volutpat metus porttitor eu. Praesent convallis neque odio, cursus pretium ipsum convallis eu. Vivamus ut metus id ante tristique fringilla id quis augue.Proin tincidunt ullamcorper lectus, sit amet tempus neque maximus quis. Phasellus at lorem id nunc hendrerit congue quis eu odio. Praesent convallis vitae odio in posuere. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin blandit diam eu dignissim pharetra. In volutpat orci nec quam placerat, nec vehicula lacus vulputate. Nullam sagittis sollicitudin nisl, non blandit orci vestibulum at. Nullam leo est, finibus ut iaculis in, consectetur eu ligula. Integer nisi neque, tempus id orci ac, porttitor sodales nunc. Praesent pretium libero scelerisque, rhoncus purus in, consectetur risus. Praesent sollicitudin est nec lectus pretium, at bibendum purus volutpat. Quisque viverra imperdiet lacus, non volutpat metus porttitor eu. Praesent convallis neque odio, cursus pretium ipsum convallis eu. Vivamus ut metus id ante tristique fringilla id quis augue.",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01")
                },
                new Course {
                    Name      = "Kurs med många moduler, studenter och aktiviter", Description = "Kurs med många moduler, studenter och aktiviter",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01")
                },
            };
            var date = DateTime.Now;

            for (int index = 0; index < 15; index++)
            {
                date.AddMonths(1);

                courses.Add(new Course
                {
                    Name        = "Kurs" + index,
                    Description = "Qwerty 123",
                    StartDate   = date,
                    StopDate    = date
                });
            }


            //Changed

            courses.ForEach(s => context.Courses.AddOrUpdate(p => p.Name, s));
            context.SaveChanges();

            var CourseMany   = context.Courses.Where(m => m.Name == "Kurs med många moduler, studenter och aktiviter").First();
            var CourseJava   = context.Courses.Where(m => m.Name == "Java").First();
            var CourseC      = context.Courses.Where(m => m.Name == "C#").First();
            var CoursePython = context.Courses.Where(m => m.Name == "Python").First();



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

            var roleNames = new[] { "Teacher", "Student" };       // A list of different roles...

            foreach (var roleName in roleNames)
            {
                if (context.Roles.Any(r => r.Name == roleName))
                {
                    continue;
                }

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

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

            var emails = new[] { "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**",
                                 "*****@*****.**", "*****@*****.**", "*****@*****.**" };
            var name = new[] { "Gandalf", "Galadriel", "Frodo", "Gimli",
                               "Knatte", "Fnatte", "Tjatte" };
            var lastname = new[] { "Gandalf", "Of the Forest", "Baggings", "Craftman",
                                   "Anka", "Anka", "Anka" };

            string emailname;

            for (int i = 0; i < emails.Length; i++)
            {
                emailname = emails[i]; //Must be set here not in the lamba expression
                if (context.Users.Any(u => u.UserName == emailname))
                {
                    continue;
                }

                // Create user, with username and pwd
                // Update with FirstName, LastName
                DateTime t1   = DateTime.Now;
                var      user = new ApplicationUser
                {
                    UserName  = emails[i],
                    Email     = emails[i],
                    FirstName = name[i],
                    LastName  = lastname[i],
                    CourseId  = CourseMany.Id
                };
                var result = userManager.Create(user, "Lsm123!");
                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors));
                }
            }


            //int kingnumber = 1;
            //foreach (var email in emails)
            //{


            //    kingnumber++;
            //    if (context.Users.Any(u => u.UserName == emails[i])) continue;

            //    // Create user, with username and pwd
            //    // Update with FirstName, LastName
            //    DateTime t1 = DateTime.Now;
            //    var user = new ApplicationUser
            //    {

            //        UserName = email,
            //        Email = email,
            //        FirstName = "Karl",
            //        LastName = kingnumber.ToString(),
            //        CourseId = CourseMany.Id
            //    };
            //    var result = userManager.Create(user, "Lsm123!");
            //    if (!result.Succeeded)
            //    {
            //        throw new Exception(string.Join("\n", result.Errors));
            //    }
            //}



            var u1 = userManager.FindByName("*****@*****.**");

            userManager.AddToRole(u1.Id, "Student");


            var u2 = userManager.FindByName("*****@*****.**");

            userManager.AddToRole(u2.Id, "Student");


            var u3 = userManager.FindByName("*****@*****.**");

            userManager.AddToRoles(u3.Id, "Student");


            var u4 = userManager.FindByName("*****@*****.**");

            userManager.AddToRoles(u4.Id, "Student");


            var u5 = userManager.FindByName("*****@*****.**");

            userManager.AddToRoles(u5.Id, "Student");


            var u6 = userManager.FindByName("*****@*****.**");

            userManager.AddToRoles(u6.Id, "Student");


            var u7 = userManager.FindByName("*****@*****.**");

            userManager.AddToRoles(u7.Id, "Student");
            //Skippat från alla rader u7.CourseId = 5;


            //var JavaDude = new ApplicationUser
            //{
            //    UserName = "******",
            //    Email = "*****@*****.**",
            //    FirstName = "Java",
            //    LastName = "Dude",
            //    CourseId = CourseC.Id
            //};
            //userManager.Create(JavaDude, "Lsm123!");
            //var u8 = userManager.FindByName("*****@*****.**");

            //userManager.AddToRoles(u8.Id, "Student");

            var Teacher = new ApplicationUser
            {
                UserName  = "******",
                Email     = "*****@*****.**",
                FirstName = "Lärare",
                LastName  = "Lärare",
                CourseId  = null
            };

            userManager.Create(Teacher, "Lsm123!");
            var u9 = userManager.FindByName("*****@*****.**");

            userManager.AddToRoles(u9.Id, "Teacher");

            //var PythonDude = new ApplicationUser
            //{
            //    UserName = "******",
            //    Email = "*****@*****.**",
            //    FirstName = "Python",
            //    LastName = "Dude",
            //    CourseId = CoursePython.Id
            //};
            //userManager.Create(JavaDude, "Lsm123!");
            //var u10 = userManager.FindByName("*****@*****.**");

            //var CDude = new ApplicationUser
            //{
            //    UserName = "******",
            //    Email = "*****@*****.**",
            //    FirstName = "C#",
            //    LastName = "Dude",
            //    CourseId = CourseC.Id
            //};
            //userManager.Create(CDude, "Lsm123!");
            //var u11 = userManager.FindByName("*****@*****.**");

            var modules = new List <Module>

            {
                new Module {
                    Name      = "Manga Aktivititer", Description = "First introduction",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01"), CourseId = CourseMany.Id
                },
                new Module {
                    Name      = "Part1", Description = "First introduction",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01"), CourseId = CourseJava.Id
                },
                new Module {
                    Name      = "Part2", Description = "Going uphill",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01"), CourseId = CourseJava.Id
                },
                new Module {
                    Name      = "Part3", Description = "Go downhill",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01"), CourseId = CourseC.Id
                },
                new Module {
                    Name      = "Part4", Description = "Go forward",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01"), CourseId = CourseC.Id
                },
                new Module {
                    Name      = "Part5", Description = "Run back",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01"), CourseId = CoursePython.Id
                },
                new Module {
                    Name      = "Part6", Description = "Start flying",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01"), CourseId = CoursePython.Id
                },
                new Module {
                    Name      = "Part7", Description = "Take a walk",
                    StartDate = DateTime.Parse("2010-09-01"), StopDate = DateTime.Parse("2010-09-01"), CourseId = CoursePython.Id
                }
            };


            var dateModule = DateTime.Now;

            for (int index = 0; index < 15; index++)
            {
                dateModule.AddMonths(1);

                modules.Add(new Module
                {
                    Name        = "Module" + index,
                    Description = "Qwerty 123",
                    StartDate   = date,
                    StopDate    = date,
                    CourseId    = CourseMany.Id
                });
            }



            modules.ForEach(s => context.Modules.AddOrUpdate(p => p.Name, s));
            context.SaveChanges();
            var ActivityMany = context.Modules.Where(m => m.Name == "Manga Aktivititer").First();



            var act = new List <Activity>
            {
                new Activity {
                    Name = "Act20", Description = "Try whiskey",
                    Day  = DateTime.Parse("2010-09-01"), Pass = Epass.FMEM, ModuleId = 1
                },
                new Activity {
                    Name = "Act21", Description = "Go home",
                    Day  = DateTime.Parse("2010-09-01"), Pass = Epass.FMEM, ModuleId = 2
                },
                new Activity {
                    Name = "Act22", Description = "Drink beer",
                    Day  = DateTime.Parse("2010-09-01"), Pass = Epass.FMEM, ModuleId = 3
                },
                new Activity {
                    Name = "Act23", Description = "Reading",
                    Day  = DateTime.Parse("2010-09-01"), Pass = Epass.FMEM, ModuleId = 3
                },
                new Activity {
                    Name = "Act24", Description = "Sleep",
                    Day  = DateTime.Parse("2010-09-01"), Pass = Epass.FMEM, ModuleId = 3
                }
            };

            for (int index = 0; index < 15; index++)
            {
                act.Add(new Activity
                {
                    Name        = "Module" + index,
                    Description = "Qwerty 123",
                    Day         = date,
                    Pass        = Epass.FMEM,
                    ModuleId    = ActivityMany.Id
                });
            }

            act.ForEach(s => context.Activitys.AddOrUpdate(p => p.Name, s));
            context.SaveChanges();


            //context.Courses.Find(p => p.Name == "Tjoho");
        }
コード例 #35
0
        protected override void Seed(ApplicationDbContext appDbContext)
        {
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(appDbContext));

            var user = new ApplicationUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                EmailConfirmed = true,
                SecurityStamp  = new Guid().ToString()
            };

            appDbContext.Packages.AddOrUpdate(p => p.Name,
                                              new Package {
                Name = "PACKAGE 1", PackageType = PackageType.Shares, Duration = 15, Price = 0, Return = 0
            },
                                              new Package {
                Name = "PACKAGE 2", PackageType = PackageType.Shares, Duration = 30, Price = 0, Return = 0
            },
                                              new Package {
                Name = "ROOKIE", PackageType = PackageType.Shares, Duration = 365, Price = 60, Return = 1500
            },
                                              new Package {
                Name = "ROOKIE+", PackageType = PackageType.Shares, Duration = 365, Price = 120, Return = 3000
            },
                                              new Package {
                Name = "BASIC", PackageType = PackageType.Shares, Duration = 365, Price = 220, Return = 5000
            },
                                              new Package {
                Name = "STARTER", PackageType = PackageType.Shares, Duration = 365, Price = 550, Return = 12000
            },
                                              new Package {
                Name = "EXECUTIVE", PackageType = PackageType.Shares, Duration = 365, Price = 1000, Return = 20000
            },
                                              new Package {
                Name = "EXECUTIVE+", PackageType = PackageType.Shares, Duration = 365, Price = 1500, Return = 25000
            },
                                              new Package {
                Name = "PREMIUM", PackageType = PackageType.Shares, Duration = 365, Price = 3000, Return = 50000
            },
                                              new Package {
                Name = "PROFESSIONAL", PackageType = PackageType.Shares, Duration = 365, Price = 5000, Return = 75000
            },
                                              new Package {
                Name = "ELITE", PackageType = PackageType.Shares, Duration = 365, Price = 10000, Return = 150000
            }
                                              );

            appDbContext.Roles.AddOrUpdate(r => r.Name,
                                           new IdentityRole {
                Name = "Admin"
            },
                                           new IdentityRole {
                Name = "Investor"
            }
                                           );

            appDbContext.SaveChanges();

            if (userManager.Create(user, "Koinfast@2018").Succeeded)
            {
                userManager.AddToRole(user.Id, "Admin");
            }
            base.Seed(appDbContext);
        }
コード例 #36
0
        protected override void Seed(SEPApp.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.AddOrUpdate(
            //    r => r.Name,
            //    new IdentityRole { Name = "Admin" },
            //    new IdentityRole { Name = "ProductionManager" },
            //    new IdentityRole { Name = "HRManager" },
            //    new IdentityRole { Name = "AdminManager" },
            //    new IdentityRole { Name = "FinancialManager" },
            //    new IdentityRole { Name = "SeniorCustomerCare" },
            //    new IdentityRole { Name = "CustomerCare" },
            //    new IdentityRole { Name = "TeamMember" }
            //    );

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

            string[]       roleNames = { "Admin", "ProductionManager", "HRManager", "HRTeam", "AdminManager", "FinancialManager", "SeniorCustomerCare", "CustomerCare", "ServiceTeamMember", "ServiceManager", "ProductionTeamMember" };
            IdentityResult roleResult;

            foreach (var roleName in roleNames)
            {
                if (!RoleManager.RoleExists(roleName))
                {
                    roleResult = RoleManager.Create(new IdentityRole(roleName));
                }
            }
            var userRoleList = new TupleList <string, string>
            {
                { "customercare", "CustomerCare" },
                { "seniorcustomercare", "SeniorCustomerCare" },
                { "adminmanager", "AdminManager" },
                { "financialmanager", "FinancialManager" },
                { "productionmanager", "ProductionManager" },
                { "servicemanager", "ServiceManager" },
                { "hrmanager", "HRManager" },
                { "hrteam1", "HRTeam" },
                { "serviceteam1", "ServiceTeamMember" },
                { "productionteam1", "ProductionTeamMember" },
            };

            foreach (var userRole in userRoleList)
            {
                if (!context.Users.Any(u => u.UserName == userRole.Item1))
                {
                    var store   = new UserStore <ApplicationUser>(context);
                    var manager = new UserManager <ApplicationUser>(store);
                    var user    = new ApplicationUser {
                        UserName = userRole.Item1
                    };

                    manager.Create(user, userRole.Item1);
                    manager.AddToRole(user.Id, userRole.Item2);
                }
            }

            //List<string> employeeList = new List<string> { "teammember1" , "teammember2", "teammember3", "teammember4" };

            //foreach (var item in employeeList)
            //{
            //    if (!context.Users.Any(u => u.UserName == item))
            //    {
            //        var store = new UserStore<ApplicationUser>(context);
            //        var manager = new UserManager<ApplicationUser>(store);
            //        var user = new ApplicationUser { UserName = item };

            //        manager.Create(user, item);
            //        manager.AddToRole(user.Id, "TeamMember");
            //    }
            //}

            //string[] userNames = { "customercare", "seniorcustomercare", "adminmanager", "financialmanager", "productionmanager", "servicemanager", "hrmanager", "hrteam1" };
            // var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            // UserManager.AddToRoles("User ");
        }
コード例 #37
0
        protected override void Seed(BugTracker.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

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

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

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

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

            // Add Admin to the Roles Table
            var userId = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userId, "Admin");

            // GuestAdmin

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

            // Add GuestAdmin to the Roles Table
            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "Admin");


            // Role for Project Manager
            if (!context.Roles.Any(r => r.Name == "ProjectManager"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "ProjectManager"
                });
            }

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

            // Add ProjectManager to the Roles Table
            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "ProjectManager");

            // Project Manager 2
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Vicky PM",
                    LastName  = "PM"
                }, "Bugtracker-1");
            }

            // Add ProjectManager to the Roles Table
            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "ProjectManager");

            // Guest Project Manager
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Guest PM",
                    LastName  = "PM"
                }, "Guest-1");
            }

            // Add ProjectManager to the Roles Table
            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "ProjectManager");



            // Role For Developer
            if (!context.Roles.Any(r => r.Name == "Developer"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "Developer"
                });
            }

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

            // Add Developer to the Roles Table
            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "Developer");


            // Developer 2
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "hmitra Developer",
                    LastName  = "D"
                }, "Bugtracker-1");
            }

            // Add Developer to the Roles Table
            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "Developer");

            // Developer 3
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Rano Developer",
                    LastName  = "D"
                }, "Bugtracker-1");
            }

            // Add Developer to the Roles Table
            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "Developer");

            // Guest Developer
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Guest Dev",
                    LastName  = "D"
                }, "Guest-1");
            }

            // Add Developer to the Roles Table
            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "Developer");

            // Role for Submitter
            if (!context.Roles.Any(r => r.Name == "Submitter"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "Submitter"
                });
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Submitter",
                    LastName  = "S"
                }, "Submitter-1");
            }
            // Add Submitter to the Roles Table
            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "Submitter");

            // Submitter 2
            // Role for Submitter
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Submitter2",
                    LastName  = "S"
                }, "Bugtracker-1");
            }
            // Add Submitter to the Roles Table
            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "Submitter");

            // Guest Submitter

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Guest Submitter",
                    LastName  = "S"
                }, "Guest-1");
            }
            // Add Submitter to the Roles Table
            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "Submitter");

            //  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" }
            //    );
            //
        }
コード例 #38
0
        private void createRolesandUsers()
        {
            ApplicationDbContext context = new ApplicationDbContext();

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

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

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

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

                string userPWD = "Admin@1234";

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

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

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

                //Here we create a Principal user who will maintain the website

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

                string userPWD = "Azeem@1234";

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

                //Add default User to Role Principal
                if (chkUser.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, "Principal");
                }
            }
            if (!roleManager.RoleExists("Supervisor"))
            {
                // first we create Supervisor role
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Supervisor";
                roleManager.Create(role);

                //Here we create a Supervisor user who will maintain the website

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

                string userPWD = "Kashif@1234";

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

                //Add default User to Role Supervisor
                if (chkUser.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, "Supervisor");
                }
            }
            if (!roleManager.RoleExists("SuperAdmin"))
            {
                // first we create Supervisor role
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "SuperAdmin";
                roleManager.Create(role);

                //Here we create a Supervisor user who will maintain the website

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

                string userPWD = "SuperAdmin@1234";

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

                //Add default User to Role Supervisor
                if (chkUser.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, "SuperAdmin");
                }
            }
            // creating Creating Manager role
            if (!roleManager.RoleExists("Teacher"))
            {
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Teacher";
                roleManager.Create(role);
            }

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

            if (!roleManager.RoleExists("Parent"))
            {
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Parent";
                roleManager.Create(role);
            }
        }
コード例 #39
0
        protected override void Seed(WebApplication1.Models.MyDbContext 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.Markets.AddOrUpdate(
                m => m.Id,
                new Market()
            {
                Id = 1, Name = "Binance", Description = "Day la san Binance"
            },
                new Market()
            {
                Id = 2, Name = "Huobi", Description = "Day la san Huobi"
            },
                new Market()
            {
                Id = 3, Name = "Bitmex", Description = "Day la san Bitmex"
            }
                );
            context.Coins.AddOrUpdate(
                c => c.Id,
                new Coin()
            {
                Id = "BNB_BTC_1", Name = "BNB", BaseAsset = "BNB", QuoteAsset = "BTC", LastPrice = 55.84, Volumn24h = 12245.49, MarketId = 1
            },
                new Coin()
            {
                Id = "ETH_BTC_1", Name = "Ethereum", BaseAsset = "ETH", QuoteAsset = "BTC", LastPrice = 14.47, Volumn24h = 14244.47, MarketId = 1
            },
                new Coin()
            {
                Id = "XRP_BTC_2", Name = "Ripple", BaseAsset = "XRP", QuoteAsset = "BTC", LastPrice = 141.11, Volumn24h = 141121.11, MarketId = 2
            },
                new Coin()
            {
                Id = "BCH_BTC_2", Name = "Bitcoin Cash", BaseAsset = "BCH", QuoteAsset = "BTC", LastPrice = 235.85, Volumn24h = 234235.85, MarketId = 2
            },
                new Coin()
            {
                Id = "DASH_BTC_3", Name = "Dash", BaseAsset = "DASH", QuoteAsset = "BTC", LastPrice = 2.79, Volumn24h = 11235.23, MarketId = 3
            },
                new Coin()
            {
                Id = "DLT_BTC_3", Name = "Agrello", BaseAsset = "DLT", QuoteAsset = "BTC", LastPrice = 5.04, Volumn24h = 231342.35, MarketId = 3
            }
                );
            var roleStore   = new RoleStore <AppRole>(context);
            var roleManager = new RoleManager <AppRole>(roleStore);

            if (!context.Roles.Any(r => r.Name == "Admin"))
            {
                var role = new AppRole("Admin");
                roleManager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name == "User"))
            {
                var role = new AppRole("User");
                roleManager.Create(role);
            }
            var store   = new UserStore <AppUser>(context);
            var manager = new UserManager <AppUser>(store);

            if (!context.Users.Any(u => u.UserName == "adminne"))
            {
                var user = new AppUser()
                {
                    UserName = "******"
                };
                manager.Create(user, "123456");
                manager.AddToRole(user.Id, "Admin");
            }
            if (!context.Users.Any(u => u.UserName == "userne"))
            {
                var user = new AppUser()
                {
                    UserName = "******"
                };
                manager.Create(user, "123456");
                manager.AddToRole(user.Id, "User");
            }
        }
コード例 #40
0
ファイル: DbConfiguration.cs プロジェクト: juden101/softuni
        protected override void Seed(ApplicationDbContext context)
        {
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var userStore   = new UserStore <ApplicationUser>(context);
                var userManager = new UserManager <ApplicationUser>(userStore);
                var user        = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**", FullName = "Administrator"
                };

                userManager.PasswordValidator = new PasswordValidator
                {
                    RequiredLength          = 1,
                    RequireDigit            = false,
                    RequireLowercase        = false,
                    RequireNonLetterOrDigit = false,
                    RequireUppercase        = false
                };

                var userCreateResult = userManager.Create(user, "adminadmin");

                if (!context.Roles.Any(r => r.Name == "Administrator"))
                {
                    var roleStore        = new RoleStore <IdentityRole>(context);
                    var roleManager      = new RoleManager <IdentityRole>(roleStore);
                    var roleCreateResult = roleManager.Create(new IdentityRole("Administrator"));

                    var adminRoleRoleResult = userManager.AddToRole(user.Id, "Administrator");
                }
            }

            if (!context.Events.Any())
            {
                context.Events.Add(new Event()
                {
                    Title         = "Party at softuni",
                    StartDateTime = DateTime.Now.Date.AddDays(5).AddHours(21).AddMinutes(30),
                    Author        = context.Users.First()
                });

                context.Events.Add(new Event()
                {
                    Title         = "Passed anonymous event",
                    StartDateTime = DateTime.Now.Date.AddDays(-2).AddHours(10).AddMinutes(50),
                    Duration      = TimeSpan.FromHours(1.5),
                    Comments      = new HashSet <Comment>()
                    {
                        new Comment()
                        {
                            Text = "Anonymous comment"
                        },
                        new Comment()
                        {
                            Text = "User comment", Author = context.Users.First()
                        }
                    }
                });
            }

            base.Seed(context);
        }
コード例 #41
0
        protected override void Seed(DatabaseMasterContext context)
        {
            using (var idc = new IdentityContext())
            {
                var userStore    = new UserStore <ApplicationUser>(idc);
                var userManager  = new UserManager <ApplicationUser>(userStore);
                var userToInsert = new ApplicationUser
                {
                    Email          = "*****@*****.**",
                    UserName       = "******",
                    PhoneNumber    = "503-984-5029",
                    FirstName      = "Jason",
                    LastName       = "Nguyen",
                    ProfilePicture = ImageToByteArray(Image.FromFile(HostingEnvironment.MapPath(@"~/Content/Images/Profile1.jpg"))),
                };
                userManager.Create(userToInsert, "vt1989");

                userToInsert = new ApplicationUser
                {
                    Email          = "*****@*****.**",
                    UserName       = "******",
                    FirstName      = "Amy",
                    LastName       = "Vo",
                    ProfilePicture = ImageToByteArray(Image.FromFile(HostingEnvironment.MapPath(@"~/Content/Images/Profile2.jpg"))),
                };
                userManager.Create(userToInsert, "vt1989");
            }



            //set up products
            using (var cContext = new ShoppingCartContext())
            {
                //set up account address

                AddressFlow.AddNewAddress("*****@*****.**", new Address()
                {
                    AddressType = new AddressType()
                    {
                        Code = "Primary", Description = "Primary address"
                    },
                    Code    = Guid.NewGuid().ToString(),
                    Line1   = "1508 duong 30 thang 4",
                    Line2   = "F12, Tp Vung tau",
                    Line3   = "Viet Nam",
                    Primary = true
                });

                AddressFlow.AddNewAddress("*****@*****.**", new Address()
                {
                    AddressType = new AddressType()
                    {
                        Code = "Alternative", Description = "Alternative address"
                    },
                    Code    = Guid.NewGuid().ToString(),
                    Line1   = "17000 duong Phan Chau Trinh",
                    Line2   = "F11, Tp Vung tau",
                    Line3   = "Viet Nam",
                    Primary = false
                });

                var sequences = new List <Sequence>
                {
                    new Sequence()
                    {
                        Code = "Order", StartValue = 10000, CurrentValue = 10000
                    },
                    new Sequence()
                    {
                        Code = "Item", StartValue = 20000, CurrentValue = 20004
                    },
                    new Sequence()
                    {
                        Code = "Category", StartValue = 30000, CurrentValue = 30001
                    }
                };

                cContext.Sequences.AddRange(sequences);
                cContext.SaveChanges();

                cContext.Categories.AddRange(new List <Category>
                {
                    new Category {
                        Code = "30000", Description = "Female-Winter-Collection"
                    },
                    new Category {
                        Code = "30001", Description = "Female-Casual-Collection"
                    },
                });
                cContext.SaveChanges();

                var products = new List <Product>
                {
                    new Product
                    {
                        Id          = 1,
                        Code        = "20000",
                        BuyInPrice  = 150000,
                        Description = "Heathered Knit Drawstring Jumpsuit",
                        Image       =
                            ImageToByteArray(Image.FromFile(HostingEnvironment.MapPath(@"~/Content/Images/Image1.jpg"))),
                        FeatureProduct    = true,
                        Weight            = 1,
                        QuantityOnHand    = 29,
                        DetailDescription = "Heathered Knit Drawstring Jumpsuit. Ship from USA.",
                        Categories        = new List <Category>()
                        {
                            cContext.Categories.SingleOrDefault(c => c.Code == "30000")
                        },
                        //ProductOffers = new List<ProductOffer>()
                        //{
                        //    new ProductOffer()
                        //    {
                        //        Code = "1001-R",
                        //        Product = cContext.Products.Single(p=> p.Code == "1001"),
                        //        Price = 15m,
                        //        Discountable = true,
                        //        PriceType = cContext.PriceTypes.Single(t=>t.Code == "R"),
                        //    },
                        //    new ProductOffer()
                        //    {
                        //        Code = "1001-W",
                        //        Product = cContext.Products.Single(p=> p.Code == "1001"),
                        //        Price = 12m,
                        //        Discountable = true,
                        //        PriceType = cContext.PriceTypes.Single(t=>t.Code == "W"),
                        //    }
                        //}
                    },
                    new Product
                    {
                        Id          = 2,
                        Code        = "20001",
                        BuyInPrice  = 150000,
                        Description = "Two-pocket Gingham Shirt",
                        Image       =
                            ImageToByteArray(Image.FromFile(HostingEnvironment.MapPath(@"~/Content/Images/Image2.jpg"))),
                        FeatureProduct    = true,
                        Weight            = 0.5m,
                        QuantityOnHand    = 22,
                        DetailDescription = "this is a good product , Heathered Knit Drawstring Jumpsuit. Ship from USA.",
                        Categories        = new List <Category>()
                        {
                            cContext.Categories.SingleOrDefault(c => c.Code == "30000")
                        },
                        //ProductOffers = new List<ProductOffer>()
                        //{
                        //    new ProductOffer()
                        //    {
                        //        Code = "1002-R",
                        //        Product = cContext.Products.Single(p=> p.Code == "1002"),
                        //        Price = 12.5m,
                        //        Discountable = true,
                        //        PriceType = cContext.PriceTypes.Single(t=>t.Code == "R"),
                        //    },
                        //    new ProductOffer()
                        //    {
                        //        Code = "1002-W",
                        //        Product = cContext.Products.Single(p=> p.Code == "1002"),
                        //        Price = 10.5m,
                        //        Discountable = true,
                        //        PriceType = cContext.PriceTypes.Single(t=>t.Code == "W"),
                        //    }
                        //}
                    },
                    new Product
                    {
                        Id          = 3,
                        Code        = "20002",
                        BuyInPrice  = 150000,
                        Description = "Upside-Down Eiffei Tower Tee",
                        Image       =
                            ImageToByteArray(Image.FromFile(HostingEnvironment.MapPath(@"~/Content/Images/Image3.jpg"))),
                        FeatureProduct    = true,
                        Weight            = 0.25m,
                        QuantityOnHand    = 40,
                        DetailDescription = "this is a good product , Heathered Knit Drawstring Jumpsuit. Ship from USA.",
                        Categories        = new List <Category>()
                        {
                            cContext.Categories.SingleOrDefault(c => c.Code == "30001")
                        },
                        //ProductOffers = new List<ProductOffer>()
                        //{
                        //    new ProductOffer()
                        //    {
                        //        Code = "1003-R",
                        //        Product = cContext.Products.Single(p=> p.Code == "1003"),
                        //        Price = 6.5m,
                        //        Discountable = true,
                        //        PriceType = cContext.PriceTypes.Single(t=>t.Code == "R"),
                        //    },
                        //    new ProductOffer()
                        //    {
                        //        Code = "1003-W",
                        //        Product = cContext.Products.Single(p=> p.Code == "1003"),
                        //        Price = 5.5m,
                        //        Discountable = true,
                        //        PriceType = cContext.PriceTypes.Single(t=>t.Code == "W"),
                        //    }
                        //}
                    },
                    new Product
                    {
                        Id                = 4,
                        Code              = "20003",
                        BuyInPrice        = 150000,
                        Description       = "Perforated Faux Leather Loafers",
                        DetailDescription = "this is a good product , Heathered Knit Drawstring Jumpsuit. Ship from USA.",
                        Image             =
                            ImageToByteArray(Image.FromFile(HostingEnvironment.MapPath(@"~/Content/Images/Image4.jpg"))),
                        FeatureProduct = true,
                        Weight         = .125m,
                        QuantityOnHand = 15,
                        Categories     = new List <Category>()
                        {
                            cContext.Categories.SingleOrDefault(c => c.Code == "30001")
                        },
                        //ProductOffers = new List<ProductOffer>()
                        //{
                        //    new ProductOffer()
                        //    {
                        //        Code = "1004-R",
                        //        Product = cContext.Products.Single(p=> p.Code == "1004"),
                        //        Price = 8.5m,
                        //        Discountable = true,
                        //        PriceType = cContext.PriceTypes.Single(t=>t.Code == "R"),
                        //    },
                        //    new ProductOffer()
                        //    {
                        //        Code = "1004-W",
                        //        Product = cContext.Products.Single(p=> p.Code == "1004"),
                        //        Price = 7.25m,
                        //        Discountable = true,
                        //        PriceType = cContext.PriceTypes.Single(t=>t.Code == "W"),
                        //    }
                        //}
                    },
                    new Product
                    {
                        Id                = 5,
                        Code              = "20004",
                        BuyInPrice        = 150000,
                        Description       = "Faux Leather Skinny Pants",
                        DetailDescription = "this is a good product , Heathered Knit Drawstring Jumpsuit. Ship from USA.",
                        Image             =
                            ImageToByteArray(Image.FromFile(HostingEnvironment.MapPath(@"~/Content/Images/Image5.jpg"))),
                        FeatureProduct = false,
                        Weight         = 1m,
                        QuantityOnHand = 20,
                        Categories     = new List <Category>()
                        {
                            cContext.Categories.SingleOrDefault(c => c.Code == "30001")
                        },
                        //ProductOffers = new List<ProductOffer>()
                        //{
                        //    new ProductOffer()
                        //    {
                        //        Code = "1005-R",
                        //        Product = cContext.Products.Single(p=> p.Code == "1005"),
                        //        Price = 10m,
                        //        Discountable = true,
                        //        PriceType = cContext.PriceTypes.Single(t=>t.Code == "R"),
                        //    },
                        //    new ProductOffer()
                        //    {
                        //        Code = "1005-W",
                        //        Product = cContext.Products.Single(p=> p.Code == "1005"),
                        //        Price = 9m,
                        //        Discountable = true,
                        //        PriceType = cContext.PriceTypes.Single(t=>t.Code == "W"),
                        //    }
                        //}
                    }
                };

                products.ForEach(s => cContext.Products.Add(s));
                cContext.SaveChanges();

                cContext.PriceTypes.AddRange(new List <PriceType>()
                {
                    new PriceType()
                    {
                        Code        = "R",
                        Description = "Retail",
                    },
                    new PriceType()
                    {
                        Code        = "W",
                        Description = "Whole Sale",
                    }
                });
                cContext.SaveChanges();


                cContext.ProductOffers.AddRange(new List <ProductOffer>()
                {
                    new ProductOffer()
                    {
                        Code         = "20000-R",
                        Product      = cContext.Products.Single(p => p.Code == "20000"),
                        Price        = 300000m,
                        Discountable = true,
                        PriceType    = cContext.PriceTypes.Single(t => t.Code == "R"),
                    },
                    new ProductOffer()
                    {
                        Code         = "20000-W",
                        Product      = cContext.Products.Single(p => p.Code == "20000"),
                        Price        = 240000m,
                        Discountable = true,
                        PriceType    = cContext.PriceTypes.Single(t => t.Code == "W"),
                    },
                    new ProductOffer()
                    {
                        Code         = "20001-R",
                        Product      = cContext.Products.Single(p => p.Code == "20001"),
                        Price        = 200000m,
                        Discountable = true,
                        PriceType    = cContext.PriceTypes.Single(t => t.Code == "R"),
                    },
                    new ProductOffer()
                    {
                        Code         = "20001-W",
                        Product      = cContext.Products.Single(p => p.Code == "20001"),
                        Price        = 180000m,
                        Discountable = true,
                        PriceType    = cContext.PriceTypes.Single(t => t.Code == "W"),
                    },
                    new ProductOffer()
                    {
                        Code         = "20002-R",
                        Product      = cContext.Products.Single(p => p.Code == "20002"),
                        Price        = 310000m,
                        Discountable = true,
                        PriceType    = cContext.PriceTypes.Single(t => t.Code == "R"),
                    },
                    new ProductOffer()
                    {
                        Code         = "20002-W",
                        Product      = cContext.Products.Single(p => p.Code == "20002"),
                        Price        = 280000m,
                        Discountable = true,
                        PriceType    = cContext.PriceTypes.Single(t => t.Code == "W"),
                    },
                    new ProductOffer()
                    {
                        Code         = "20003-R",
                        Product      = cContext.Products.Single(p => p.Code == "20003"),
                        Price        = 500000m,
                        Discountable = true,
                        PriceType    = cContext.PriceTypes.Single(t => t.Code == "R"),
                    },
                    new ProductOffer()
                    {
                        Code         = "20003-W",
                        Product      = cContext.Products.Single(p => p.Code == "20003"),
                        Price        = 450000m,
                        Discountable = true,
                        PriceType    = cContext.PriceTypes.Single(t => t.Code == "W"),
                    },
                    new ProductOffer()
                    {
                        Code         = "20004-R",
                        Product      = cContext.Products.Single(p => p.Code == "20004"),
                        Price        = 430000m,
                        Discountable = true,
                        PriceType    = cContext.PriceTypes.Single(t => t.Code == "R"),
                    },
                    new ProductOffer()
                    {
                        Code         = "20004-W",
                        Product      = cContext.Products.Single(p => p.Code == "20004"),
                        Price        = 400000m,
                        Discountable = true,
                        PriceType    = cContext.PriceTypes.Single(t => t.Code == "W"),
                    },
                });

                cContext.SaveChanges();

                //promotion
                cContext.Promotions.AddRange(new List <Promotion>()
                {
                    new Promotion()
                    {
                        Code = "Christmas discount",
                        PromotionLineItems = new List <PromotionLineItem>()
                        {
                            new PromotionLineItem()
                            {
                                Code        = "15PercentOff_1001",
                                Description = "15 percent off Female-Winter-Collection",
                                Active      = false,
                                StartDate   = DateTime.Now,
                                EndDate     = DateTime.Now.AddDays(2),
                                PromotionLineItemExpression = "Category=1001;PriceType=R;PercentDiscount=0.15"
                            },
                            new PromotionLineItem()
                            {
                                Code        = "15offFemale-Casual-Collection",
                                Description = "15d off Female-Casual-Collection",
                                Active      = false,
                                StartDate   = DateTime.Now,
                                EndDate     = DateTime.Now.AddDays(2),
                                PromotionLineItemExpression = "Category=1002;PriceType=R;AmountDiscount=15000"
                            },
                            new PromotionLineItem()
                            {
                                Code        = "25_percent_off_item_1004",
                                Description = "25 percent off item 1004",
                                Active      = false,
                                StartDate   = DateTime.Now,
                                EndDate     = DateTime.Now.AddDays(2),
                                PromotionLineItemExpression = "ItemCode=1004;PriceType=R;PercentDiscount=0.25"
                            },
                            new PromotionLineItem()
                            {
                                Code        = "25_off_item_item_1005",
                                Description = "25 off item item 1005",
                                Active      = false,
                                StartDate   = DateTime.Now,
                                EndDate     = DateTime.Now.AddDays(2),
                                PromotionLineItemExpression = "ItemCode=1005;PriceType=R;AmountDiscount=25000"
                            },
                            new PromotionLineItem()
                            {
                                Code        = "Buy_5_1004_get_1_item_1004_free",
                                Description = "Buy 5 item 1004 get 1 item 1004 free",
                                Active      = false,
                                StartDate   = DateTime.Now,
                                EndDate     = DateTime.Now.AddDays(2),
                                PromotionLineItemExpression = "PriceType=R;BuyItemCode=1004;BuyItemCount=5;GetItemCode=1004;GetItemCount=1"
                            },
                            new PromotionLineItem()
                            {
                                Code        = "Buy_5_item_1004_get_2_item_1001_free",
                                Description = "Buy 5 item 1004 get 2 item 1001 free",
                                Active      = false,
                                StartDate   = DateTime.Now,
                                EndDate     = DateTime.Now.AddDays(2),
                                PromotionLineItemExpression = "PriceType=R;BuyItemCode=1004;BuyItemCount=5;GetItemCode=1001;GetItemCount=2"
                            },
                        }
                    },
                });
                cContext.SaveChanges();

                //cContext.CartLineItems.AddRange(new List<CartLineItem>
                //{
                //    new CartLineItem()
                //    {
                //        Code = Guid.NewGuid().ToString(),
                //        DiscountAmount = 0m,
                //        Quantity = 5,
                //        OriginalPrice = 0m,
                //        ShippingCost = 0m,
                //        DiscountedPrice = 0m,
                //        ProductCode = "1001",
                //        PriceType = "R",
                //        DateCreated = DateTime.Now
                //    },
                //    new CartLineItem()
                //    {
                //        Code = Guid.NewGuid().ToString(),
                //        DiscountAmount = 0m,
                //        Quantity = 5,
                //        OriginalPrice = 0m,
                //        ShippingCost = 0m,
                //        DiscountedPrice = 0m,
                //        ProductCode = "1002",
                //        PriceType = "W",
                //        DateCreated = DateTime.Now
                //    },
                //});

                //cContext.SaveChanges();

                var paymentStatuses = new List <PaymentStatus>
                {
                    new PaymentStatus()
                    {
                        Code = "Hold", Description = "On Hold"
                    },
                    new PaymentStatus()
                    {
                        Code = "Processing", Description = "Processing"
                    },
                    new PaymentStatus()
                    {
                        Code = "Processed", Description = "Processed"
                    },
                    new PaymentStatus()
                    {
                        Code = "Completed", Description = "Completed"
                    }
                };

                cContext.PaymentStatuses.AddRange(paymentStatuses);
                cContext.SaveChanges();


                cContext.PaymentTypes.AddRange(new List <PaymentType>
                {
                    new PaymentType()
                    {
                        Code = "Bank", Description = "Chuyển tiền qua tài khoản"
                    },
                    new PaymentType()
                    {
                        Code = "Cash", Description = "Gởi tiền mặt"
                    },
                });
                cContext.SaveChanges();

                cContext.PaymentTransactions.AddRange(new List <PaymentTransaction>
                {
                    new PaymentTransaction()
                    {
                        Code           = Guid.NewGuid().ToString(),
                        Amount         = 6.66m,
                        PartialPayment = true,
                        PaymentStatus  = cContext.PaymentStatuses.Single(ps => ps.Code == "Completed"),
                        PaymentTypeId  = 1,
                        //PostedAmount = 6.66m,
                    }
                });


                var paymentTransactionId = cContext.SaveChanges();

                cContext.Carts.AddRange(new List <Cart>
                {
                    new Cart()
                    {
                        Product     = cContext.Products.Single(p => p.Code == "20003"),
                        Code        = Guid.NewGuid().ToString(),
                        Quantity    = 1,
                        DateCreated = DateTime.Now,
                    }
                });


                cContext.Orders.AddRange(new List <Order>
                {
                    new Order()
                    {
                        OrderNumber          = SeqHelper.Next("Order"),
                        UserName             = "******",
                        FullName             = "Jason Nguyen",
                        Phone                = "503-111-4444",
                        OrderDate            = DateTime.Now,
                        ShippingAddressId    = 1,
                        PaymentTransactionId = paymentTransactionId,
                        Email                = "*****@*****.**",
                        OrderDetails         = new List <LineOrderDetail>()
                        {
                            new LineOrderDetail
                            {
                                ProductId = 1,
                                UnitPrice = 9.99m,
                                Quantity  = 1
                            }
                        }
                    }
                });

                cContext.AppSettings.AddRange(new List <AppSetting>
                {
                    new AppSetting()
                    {
                        Code        = "ShippingRate",
                        Description = "Shipping Rate per lb",
                        Value       = "100000",
                        ValueType   = "decimal"
                    },
                    new AppSetting()
                    {
                        Code        = "NotificationEmail1",
                        Description = "Send order notification to email 1",
                        Value       = "*****@*****.**",
                        ValueType   = "string"
                    },
                    new AppSetting()
                    {
                        Code        = "NotificationEmail2",
                        Description = "Send order notification to email 2",
                        Value       = "*****@*****.**",
                        ValueType   = "string"
                    }
                });

                cContext.SaveChanges();
            }
        }
コード例 #42
0
        internal static void SeedIdentities(ApplicationDbContext context)
        {
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            if (!roleManager.RoleExists(RoleNames.ROLE_ADMINISTRATOR))
            {
                roleManager.Create(new IdentityRole(RoleNames.ROLE_ADMINISTRATOR));
            }
            if (!roleManager.RoleExists(RoleNames.ROLE_CUSTOMER))
            {
                roleManager.Create(new IdentityRole(RoleNames.ROLE_CUSTOMER));
            }


            //Username and password details for demo user asssigned the role of Administrator
            string userName = "******";
            string password = "******";

            //Check to see if an Admin user has already been created in the database
            //If not a new ApplicationUser object is instantiated with account registration details required required to create the new user
            var user = userManager.FindByName(userName);

            if (user == null)
            {
                user = new ApplicationUser()
                {
                    UserName    = userName,
                    Email       = userName,
                    FirstName   = "Acme",
                    LastName    = "Admin",
                    DateOfBirth = new DateTime(1995, 2, 4),

                    Address = new Address
                    {
                        AddressLine1 = "1 Admin Street",
                        Town         = "Town",
                        County       = "County",
                        Postcode     = "PostCode"
                    }
                };

                //Creating and Assigning the new user the role of Adminstrator
                IdentityResult userResult = userManager.Create(user, password);
                if (userResult.Succeeded)
                {
                    userManager.AddToRole(user.Id, RoleNames.ROLE_ADMINISTRATOR);
                }
            }

            //Details for demo Customer user 1 in the role of Customer
            userName = "******";
            password = "******";

            //Check to see if a Demo Customer user 1 has already been created in the database
            //If not a new ApplicationUser object is instantiated with account registration details required to create the new user
            user = userManager.FindByName(userName);
            if (user == null)
            {
                user = new ApplicationUser()
                {
                    UserName    = userName,
                    Email       = userName,
                    FirstName   = "Joe",
                    LastName    = "Black",
                    DateOfBirth = new DateTime(1984, 5, 12),

                    Address = new Address
                    {
                        AddressLine1 = "53 Fox St",
                        Town         = "Hartbeesfontein",
                        County       = "North West",
                        Postcode     = "2600"
                    }
                };

                //Creating and Assigning the new user the role of Customer
                IdentityResult userResult = userManager.Create(user, password);
                if (userResult.Succeeded)
                {
                    userManager.AddToRole(user.Id, RoleNames.ROLE_CUSTOMER);
                }
            }


            //Details for demo customer user 2 in the role of Customer
            userName = "******";
            password = "******";

            //Check to see if demo Customer user 2 has already been created in the database
            //If not a new ApplicationUser object is instantiated with account registration details required to create the new user
            user = userManager.FindByName(userName);
            if (user == null)
            {
                user = new ApplicationUser()
                {
                    UserName    = userName,
                    Email       = userName,
                    FirstName   = "Ntobeko",
                    LastName    = "Nhlanhla",
                    DateOfBirth = new DateTime(1990, 21, 7),

                    Address = new Address
                    {
                        AddressLine1 = "691 Kamp St",
                        Town         = "Belhar",
                        County       = "Western Cape",
                        Postcode     = "7504"
                    }
                };

                //Creating and Assigning the new user the role of Customer
                IdentityResult userResult = userManager.Create(user, password);
                if (userResult.Succeeded)
                {
                    userManager.AddToRole(user.Id, RoleNames.ROLE_CUSTOMER);
                }
            }

            //Details for demo customer user 3 in the role of Customer
            userName = "******";
            password = "******";

            //Check to see if demo Customer user 2 has already been created in the database
            //If not a new ApplicationUser object is instantiated with account registration details required to create the new user
            user = userManager.FindByName(userName);
            if (user == null)
            {
                user = new ApplicationUser()
                {
                    UserName    = userName,
                    Email       = userName,
                    FirstName   = "Vilina",
                    LastName    = "Maharaj",
                    DateOfBirth = new DateTime(1999, 1, 28),

                    Address = new Address
                    {
                        AddressLine1 = "481 Main Rd",
                        Town         = "Stanger",
                        County       = "KwaZulu-Natal",
                        Postcode     = "4453"
                    }
                };

                //Creating and Assigning the new user the role of Customer
                IdentityResult userResult = userManager.Create(user, password);
                if (userResult.Succeeded)
                {
                    userManager.AddToRole(user.Id, RoleNames.ROLE_CUSTOMER);
                }
            }
        }
コード例 #43
0
        protected override void Seed(Falcon_Bug_Tracker.Models.ApplicationDbContext context)
        {
            #region Role Creation
            var roleManager = new RoleManager <IdentityRole>(
                new RoleStore <IdentityRole>(context));

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

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

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

            if (!context.Roles.Any(r => r.Name == "Submitter"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "Submitter"
                });
            }
            #endregion
            #region User Creation
            var userManager = new UserManager <ApplicationUser>(
                new UserStore <ApplicationUser>(context));
            var demoPassword = WebConfigurationManager.AppSettings["DemoPassword"];

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName       = "******",
                    Email          = "*****@*****.**",
                    FirstName      = "Josh",
                    LastName       = "Casteel",
                    AvatarPath     = "/Images/Avatars/avatar_default.png",
                    EmailConfirmed = true
                }, "Abc&123!");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName       = "******",
                    Email          = "*****@*****.**",
                    FirstName      = "Michael",
                    LastName       = "Trueman",
                    AvatarPath     = "/Images/Avatars/avatar_default.png",
                    EmailConfirmed = true
                }, demoPassword);
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Jenny",
                    LastName   = "Gump",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, demoPassword);
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Eleanor",
                    LastName   = "Shellstrop",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, demoPassword);
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Darren",
                    LastName   = "Richardson",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, demoPassword);
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName       = "******",
                    Email          = "*****@*****.**",
                    FirstName      = "Jon",
                    LastName       = "Snow",
                    AvatarPath     = "/Images/Avatars/avatar_default.png",
                    EmailConfirmed = true
                }, "Abc&123!");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "John",
                    LastName   = "Locke",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, "Abc&123!");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Jack",
                    LastName   = "Shepard",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, "Abc&123!");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Jake",
                    LastName   = "Sully",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, "Abc&123!");
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Kate",
                    LastName   = "Austen",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, "Abc&123!");
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "James",
                    LastName   = "Ford",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, "Abc&123!");
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Ben",
                    LastName   = "Linus",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, "Abc&123!");
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Juliet",
                    LastName   = "Burke",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, "Abc&123!");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Karen",
                    LastName   = "Blonde",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, "Abc&123!");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Arya",
                    LastName   = "Stark",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, "Abc&123!");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Hugo",
                    LastName   = "Reyes",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, "Abc&123!");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Sayid",
                    LastName   = "Jarrah",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, "Abc&123!");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    FirstName  = "Claire",
                    LastName   = "Littleton",
                    AvatarPath = "/Images/Avatars/avatar_default.png"
                }, "Abc&123!");
            }

            var DemoAdmin = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(DemoAdmin, "Admin");

            var DemoPM = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(DemoPM, "ProjectManager");

            var DemoDev = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(DemoDev, "Developer");

            var DemoSub = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(DemoSub, "Submitter");

            var AdminId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(AdminId, "Admin");

            var AdminId2 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(AdminId2, "Admin");

            var PMId1 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(PMId1, "ProjectManager");

            var PMId2 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(PMId2, "ProjectManager");

            var DevId1 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(DevId1, "Developer");

            var DevId2 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(DevId2, "Developer");

            var DevId3 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(DevId3, "Developer");

            var DevId4 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(DevId4, "Developer");

            var DevId5 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(DevId5, "Developer");

            var SubId1 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(SubId1, "Submitter");

            var SubId2 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(SubId2, "Submitter");

            var SubId3 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(SubId3, "Submitter");

            var SubId4 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(SubId4, "Submitter");

            var SubId5 = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(SubId5, "Submitter");

            #endregion
            #region Tickets Properties
            context.TicketTypes.AddOrUpdate(
                t => t.Name,
                new TicketType {
                Name = "Software"
            },
                new TicketType {
                Name = "Hardware"
            },
                new TicketType {
                Name = "UI"
            },
                new TicketType {
                Name = "Defect"
            },
                new TicketType {
                Name = "Other"
            }
                );

            context.TicketPriorities.AddOrUpdate(
                t => t.Name,
                new TicketPriority {
                Name = "Critical"
            },
                new TicketPriority {
                Name = "High"
            },
                new TicketPriority {
                Name = "Low"
            },
                new TicketPriority {
                Name = "On Hold"
            }
                );

            context.TicketStatuses.AddOrUpdate(
                t => t.Name,
                new TicketStatus {
                Name = "Open"
            },
                new TicketStatus {
                Name = "Assigned"
            },
                new TicketStatus {
                Name = "Resolved"
            },
                new TicketStatus {
                Name = "Reopened"
            },
                new TicketStatus {
                Name = "Archived"
            }
                );
            #endregion
            #region Project Creation
            context.Projects.AddOrUpdate(
                p => p.Name,
                new Project()
            {
                Name = "First Demo", Description = "The first demo project seed", Created = DateTime.Now.AddDays(-3)
            },
                new Project()
            {
                Name = "Second Demo", Description = "The second demo project seed", Created = DateTime.Now.AddDays(-7)
            },
                new Project()
            {
                Name = "Third Demo", Description = "The third demo project seed", Created = DateTime.Now.AddDays(-15)
            },
                new Project()
            {
                Name = "Fourth Demo", Description = "The fourth demo project seed", Created = DateTime.Now.AddDays(-45)
            },
                new Project()
            {
                Name = "Fifth Demo", Description = "The fifth demo project seed", Created = DateTime.Now.AddDays(-60)
            }
                );
            context.SaveChanges();
            #endregion


            Random        rand             = new Random();
            var           ticketPriorityId = context.TicketPriorities.Select(t => t.Id).ToList();
            var           ticketStatusId   = context.TicketStatuses.FirstOrDefault(t => t.Name == "Open").Id;
            var           ticketTypeId     = context.TicketTypes.Select(t => t.Id).ToList();
            var           projectId        = context.Projects.Select(p => p.Id).ToList();
            List <string> submitters       = rolehelper.UsersInRole("Submitter").Select(u => u.Id).ToList();
            for (var i = 1; i <= 20; i++)
            {
                int    randProj      = context.Projects.Find(rand.Next(1, (context.Projects.Count() + 1))).Id;
                string randSubmitter = submitters[rand.Next(0, submitters.Count())];
                if (!projHelper.IsUserOnProject(randSubmitter, randProj))
                {
                    projHelper.AddUserToProject(randSubmitter, randProj);
                }

                context.Tickets.AddOrUpdate(
                    t => t.Title,
                    new Ticket()
                {
                    Title            = $"Seeded Issue {i}",
                    Description      = $"Description for Project {randProj}",
                    Created          = DateTime.Now.AddDays(rand.Next(0, 20)),
                    SubmitterId      = randSubmitter,
                    ProjectId        = randProj,
                    TicketPriorityId = ticketPriorityId[rand.Next(0, ticketPriorityId.Count())],
                    TicketTypeId     = ticketTypeId[rand.Next(0, ticketTypeId.Count())],
                    TicketStatusId   = ticketStatusId
                });
            }
        }
コード例 #44
0
        public ActionResult Import(InvitationFileModel model)
        {
            var invitationList = CreateCheckModel(model);
            var host           = GetCurrentUser();

            var studentService = new StudentService(Db);

            /*
             * if (!string.IsNullOrEmpty(invitationList.Error))
             *  return View("InvitationList", invitationList);
             */


            foreach (var invitation in invitationList.Invitations)
            {
                var user = UserManager.FindByEmail(invitation.Email);

                if (user == null)
                {
                    var now = DateTime.Now;
                    user = new ApplicationUser
                    {
                        UserName       = invitation.Email,
                        Email          = invitation.Email,
                        FirstName      = invitation.FirstName,
                        LastName       = invitation.LastName,
                        Registered     = now,
                        MemberState    = MemberState.Student,
                        Remark         = "CIE",
                        ExpiryDate     = null, // Einladung bleibt dauerhaft bestehen - Deprovisionierung automatisch
                        Submitted      = now,
                        EmailConfirmed =
                            true,            // damit ist auch ein "ForgotPassword" möglich, auch wenn er die Einladung nicht angenommen hat.
                        IsApproved = true,   // Damit bekommt der Nutzer von Anfang an E-Mails
                        Faculty    = host.Id // Benutzer der eingeladen hat
                    };

                    // Benutzer anlegen, mit Dummy Passwort
                    var result = UserManager.Create(user, "Cie98#lcl?");

                    if (result.Succeeded)
                    {
                        // analog Forget E-Mail Versand
                        string code = UserManager.GeneratePasswordResetToken(user.Id);

                        var mailModel = new ForgotPasswordMailModel
                        {
                            User          = user,
                            Token         = code,
                            CustomSubject = "Your NINE Account",
                            CustomBody    = "",
                            Attachments   = null,
                            IsNewAccount  = true,
                        };


                        try
                        {
                            new MailController().InvitationMail(mailModel, host, "en").Deliver();
                        }
                        catch (SmtpFailedRecipientException ex)
                        {
                            invitation.Remark = ex.Message;
                        }
                    }
                }

                var student = studentService.GetCurrentStudent(user);
                if (student == null)
                {
                    student               = new Student();
                    student.Created       = DateTime.Now;
                    student.Curriculum    = invitation.Curriculum;
                    student.FirstSemester = invitation.Semester;
                    student.UserId        = user.Id;

                    Db.Students.Add(student);
                }


                if (invitation.Course != null)
                {
                    var subscription =
                        invitation.Course.Occurrence.Subscriptions.FirstOrDefault(x => x.UserId.Equals(user.Id));

                    if (subscription == null)
                    {
                        subscription               = new OccurrenceSubscription();
                        subscription.TimeStamp     = DateTime.Now;
                        subscription.UserId        = user.Id;
                        subscription.OnWaitingList = invitation.OnWaitinglist;
                        subscription.Occurrence    = invitation.Course.Occurrence;
                        subscription.HostRemark    = invitation.Remark;
                        invitation.Course.Occurrence.Subscriptions.Add(subscription);
                    }
                }
            }

            Db.SaveChanges();

            return(View("InvitationList", invitationList));
        }
コード例 #45
0
        protected override void Seed(GesNaturaMVC.DAL.GesNaturaDbContext 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.
            //

            //Roles
            const string roleName = "Admin";
            const string userName = "******";
            const string password = "******";

            // Antes de adicionar o role verifica se existe
            if (!context.Roles.Any(r => r.Name == roleName))
            {
                context.Roles.Add(new IdentityRole(roleName));
                context.SaveChanges();
            }
            var             userStore   = new UserStore <ApplicationUser>(context);
            var             userManager = new UserManager <ApplicationUser>(userStore);
            ApplicationUser user        = null;

            // Antes de adicionar o utilizador verifica se existe
            if (!context.Users.Any(u => u.UserName == userName))
            {
                user = new ApplicationUser {
                    UserName = userName
                };
                userManager.Create(user, password);
                context.SaveChanges();
            }
            else
            { // Se o utilizador já existe
                user = context.Users.Single(u => u.UserName.Equals(userName,
                                                                   StringComparison.CurrentCultureIgnoreCase));
            }
            userManager.AddToRole(user.Id, roleName);
            context.SaveChanges();


            //context.Percursos.AddOrUpdate(x => x.ID,
            //    new Percurso()
            //    {
            //        ID = 1,
            //        Nome = "Caminho do Paço",
            //        Descricao = "Percurso junto ao Rio Germinade, onde podemos observar várias " +
            //        "espécies de aves. Inserido em pleno parque N. Sra de Lurdes",
            //        Dificuldade = "Baixa",
            //        Distancia = 2,
            //        DuracaoAproximada = 2,
            //        Tipologia = "Circular",
            //        GPS_Lat_Inicio = 41.002450F,
            //        GPS_Long_Inicio = -8.162835F,
            //        KmlPath = "https://docs.google.com/uc?export=download&id=0Bxc0V7hINajBcmdCOW9YMFNTLWM"

            //    },
            //    new Percurso()
            //    {
            //        ID = 2,
            //        Nome = "Caminho do Loureiro",
            //        Descricao = "Rumo ao monte. Subir ao cimo do monte, e respirar ar puro",
            //        Dificuldade = "Media",
            //        Distancia = 2,
            //        DuracaoAproximada = 2,
            //        Tipologia = "Circular",
            //        GPS_Lat_Inicio = 40.997354F,
            //        GPS_Long_Inicio = -8.161707F,
            //        KmlPath = "https://docs.google.com/uc?export=download&id=0Bxc0V7hINajBdWc5NGRUUmNzRHc"

            //    },
            //    new Percurso()
            //    {
            //        ID = 3,
            //        Nome = "Caminho da Balsa",
            //        Descricao = "Percurso entre 2 maravilhas da Natureza: Parque N. Sra Lurdes" +
            //        " e a ponte da Balsa",
            //        Dificuldade = "Baixa",
            //        Distancia = 2,
            //        DuracaoAproximada = 1,
            //        Tipologia = "Linear",
            //        GPS_Lat_Inicio = 40.998240F,
            //        GPS_Long_Inicio = -8.171382F,
            //        KmlPath = "https://docs.google.com/uc?export=download&id=0Bxc0V7hINajBdEcwcWpzNXZHb2c"

            //    });

            //context.POIs.AddOrUpdate(x => x.ID,
            //     new POI() {
            //         ID =1,
            //         Nome ="Miradouro de Aves",
            //         Descricao ="Local onde é possivel admirar aves de Rapina",
            //         GPS_Lat=40.995009F,
            //         GPS_Long=-8.159134F,
            //         PercursoId=2
            //     },
            //     new POI()
            //     {
            //         ID = 2,
            //         Nome = "Antiga Azenha",
            //         Descricao = "Local de grandes recordações com uma envolvência natural soberba",
            //         GPS_Lat = 41.000737F,
            //         GPS_Long = -8.163427F,
            //         PercursoId = 3
            //     });

            //context.Reinoes.AddOrUpdate(x=>x.ID,
            //    new Reino() { ID = 1, Nome="Animal"},
            //    new Reino() { ID = 2, Nome="Vegetal"});

            //context.Classes.AddOrUpdate(x => x.ID,
            //    new Classe() { ID = 1, Nome = "Aves", ReinoID=1 },
            //    new Classe() { ID = 2, Nome = "Insetos", ReinoID=1 },
            //    new Classe() { ID = 3, Nome = "Arvores", ReinoID = 2 },
            //    new Classe() { ID = 4, Nome = "Repteis", ReinoID = 1 });

            //context.Ordems.AddOrUpdate(x => x.ID,
            //    new Ordem() { ID = 1, Nome = "Passeriformes", ClasseID = 1 },
            //    new Ordem() { ID = 2, Nome = "Fagales", ClasseID = 2 },
            //    new Ordem() { ID = 3, Nome = "Accipitriformes", ClasseID = 1 },
            //    new Ordem() { ID = 4, Nome = "Bucerotiformes", ClasseID = 1 });

            //context.Familias.AddOrUpdate(x => x.ID,
            //    new Familia() { ID = 1, Nome = "Motacillidae", OrdemID = 1 },
            //    new Familia() { ID = 2, Nome = "Paridae", OrdemID = 1 },
            //    new Familia() { ID = 3, Nome = "Passeridae", OrdemID = 1 });

            //context.Generoes.AddOrUpdate(x => x.ID,
            //    new Genero() { ID = 1, Nome = "Motacilla", FamiliaID = 1 },
            //    new Genero() { ID = 2, Nome = "Parus",     FamiliaID = 2 },
            //    new Genero() { ID = 3, Nome = "Passer",    FamiliaID = 3 });

            //context.Especies.AddOrUpdate(x => x.ID,
            //    new Especie() { ID = 1, Nome = "Alvéola branca", NomeCientifico = "Motacilla alba", GeneroID = 1 },
            //    new Especie() { ID = 2, Nome = "Chapim-real", NomeCientifico = "Parus major", GeneroID = 2 },
            //    new Especie() { ID = 3, Nome = "Pardal-comum", NomeCientifico = "Passer domesticus", GeneroID = 3 });
        }
コード例 #46
0
        protected override void Seed(Galo_Personal_Site.Models.ApplicationDbContext context)
        {
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

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

            if (!context.Roles.Any(r => r.Name == "Moderator"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "Moderator"
                });
            }

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

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Galo",
                    LastName    = "Lopez",
                    DisplayName = "Galo"
                }, "Cuentame1!");
            }

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

            userManager.AddToRole(userId, "Admin");
            /*-----------------------------------------------------------------------------------------*/
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Bobby",
                    LastName    = "Davis",
                    DisplayName = "Bobby Davis"
                }, "password1");
            }

            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "Moderator");
            /*-----------------------------------------------------------------------------------------*/
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Antonio",
                    LastName    = "Raynor",
                    DisplayName = "Antonio Raynor"
                }, "Abc&123!");
            }

            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "Moderator");
            /*-----------------------------------------------------------------------------------------*/
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Andrew",
                    LastName    = "Jensen",
                    DisplayName = "Andrew Jensen"
                }, "Abc&123!");
            }

            userId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userId, "Moderator");
        }
コード例 #47
0
        static void CreateSampleUser(WealthEconomyContext context)
        {
            // Managers & stores & repositories
            var userStore              = new UserStore(context);
            var userManager            = new UserManager <User, int>(userStore);
            var resourcePoolRepository = new ResourcePoolRepository(context);

            // Sample user
            var sampleUserName = "******";
            var sampleEmail    = "*****@*****.**";
            var sampleUser     = new User(sampleUserName, sampleEmail)
            {
                EmailConfirmed          = true,
                EmailConfirmationSentOn = DateTime.UtcNow,
                HasPassword             = true
            };
            var sampleUserPassword = DateTime.Now.ToString("yyyyMMdd");

            userManager.Create(sampleUser, sampleUserPassword);
            context.SaveChanges();

            // Add to regular role
            userManager.AddToRole(sampleUser.Id, "Regular");
            context.SaveChanges();

            // Login as (required in order to save the rest of the items)
            Security.LoginAs(sampleUser.Id, "Regular");

            // Sample resource pools
            var billionDollarQuestion      = resourcePoolRepository.CreateBillionDollarQuestion(sampleUser);
            var upoSample                  = resourcePoolRepository.CreateUPOSample(sampleUser);
            var basicsExistingSystemSample = resourcePoolRepository.CreateBasicsExistingSystemSample(sampleUser);
            var basicsNewSystemSample      = resourcePoolRepository.CreateBasicsNewSystemSample(sampleUser);
            var priorityIndexSample        = resourcePoolRepository.CreatePriorityIndexSample(sampleUser);
            var knowledgeIndexSample       = resourcePoolRepository.CreateKnowledgeIndexSample(sampleUser);
            var knowledgeIndexPopularSoftwareLicenseSample = resourcePoolRepository.CreateKnowledgeIndexPopularSoftwareLicenseSample(sampleUser);
            var totalCostIndexExistingSystemSample         = resourcePoolRepository.CreateTotalCostIndexExistingSystemSample(sampleUser);
            var totalCostIndexNewSystemSample = resourcePoolRepository.CreateTotalCostIndexNewSystemSample(sampleUser);
            var allInOneSample = resourcePoolRepository.CreateAllInOneSample(sampleUser);

            // Set Id fields explicitly, since strangely EF doesn't save them in the order that they've been added to ResourcePoolSet.
            // And they're referred with these Ids on front-end samples
            billionDollarQuestion.Id      = 1;
            upoSample.Id                  = 8;
            basicsExistingSystemSample.Id = 9;
            basicsNewSystemSample.Id      = 10;
            priorityIndexSample.Id        = 2;
            knowledgeIndexSample.Id       = 3;
            knowledgeIndexPopularSoftwareLicenseSample.Id = 4;
            totalCostIndexExistingSystemSample.Id         = 5;
            totalCostIndexNewSystemSample.Id = 6;
            allInOneSample.Id = 7;

            // Insert
            resourcePoolRepository.Insert(billionDollarQuestion);
            resourcePoolRepository.Insert(upoSample);
            resourcePoolRepository.Insert(basicsExistingSystemSample);
            resourcePoolRepository.Insert(basicsNewSystemSample);
            resourcePoolRepository.Insert(priorityIndexSample);
            resourcePoolRepository.Insert(knowledgeIndexSample);
            resourcePoolRepository.Insert(knowledgeIndexPopularSoftwareLicenseSample);
            resourcePoolRepository.Insert(totalCostIndexExistingSystemSample);
            resourcePoolRepository.Insert(totalCostIndexNewSystemSample);
            resourcePoolRepository.Insert(allInOneSample);

            // First save
            context.SaveChanges();
        }
コード例 #48
0
        protected override void Seed(BugTrack.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.
            var RoleManager = new RoleManager <IdentityRole>(
                new RoleStore <IdentityRole>(context));

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

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

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

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

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

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

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

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

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

            //Seed a few Demo Users
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Demo",
                    LastName  = "Admin",
                }, "AdminBug@1");

                var userID = userManager.FindByEmail("*****@*****.**").Id;
                userManager.AddToRole(userID, "Admin");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Demo",
                    LastName  = "Manager",
                }, "Projectm2");

                var userID = userManager.FindByEmail("*****@*****.**").Id;
                userManager.AddToRole(userID, "ProjectManager");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Demo",
                    LastName  = "Developer",
                }, "Develop3!");

                var userID = userManager.FindByEmail("*****@*****.**").Id;
                userManager.AddToRole(userID, "Developer");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Demo",
                    LastName  = "Submitter",
                }, "Submit4!");

                var userID = userManager.FindByEmail("*****@*****.**").Id;
                userManager.AddToRole(userID, "Submitter");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Wilten",
                    LastName  = "Houston",
                }, "Byakugan301!");

                var userID = userManager.FindByEmail("*****@*****.**").Id;
                userManager.AddToRole(userID, "Admin");
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Tyrell",
                    LastName  = "Coleman",
                }, "Neji301!");

                var userID = userManager.FindByEmail("*****@*****.**").Id;
                userManager.AddToRole(userID, "ProjectManager");
            }

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

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

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Ken",
                    LastName  = "Houston",
                }, "Sharigan301!");

                var userID = userManager.FindByEmail("*****@*****.**").Id;
                userManager.AddToRole(userID, "Developer");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Brittini",
                    LastName  = "Houston",
                }, "August@18");

                var userID = userManager.FindByEmail("*****@*****.**").Id;
                userManager.AddToRole(userID, "Submitter");
            }

            if (context.TicketPriorities.Count() == 0)
            {
                context.TicketPriorities.AddOrUpdate(
                    p => p.Name,
                    new TicketPriority {
                    ID = 100, Name = "Immediate"
                },
                    new TicketPriority {
                    ID = 200, Name = "High"
                },
                    new TicketPriority {
                    ID = 300, Name = "Medium"
                },
                    new TicketPriority {
                    ID = 400, Name = "Low"
                },
                    new TicketPriority {
                    ID = 500, Name = "None"
                }
                    );
            }

            if (context.TicketStatus.Count() == 0)
            {
                context.TicketStatus.AddOrUpdate(
                    p => p.Name,
                    new TicketStatus {
                    ID = 100, Name = "UnAssigned"
                },
                    new TicketStatus {
                    ID = 200, Name = "In Progress"
                },
                    new TicketStatus {
                    ID = 300, Name = "On Hold"
                },
                    new TicketStatus {
                    ID = 400, Name = "Resolved"
                },
                    new TicketStatus {
                    ID = 500, Name = "Closed"
                }
                    );
            }

            if (context.TicketTypes.Count() == 0)
            {
                context.TicketTypes.AddOrUpdate(
                    p => p.Name,
                    new TicketType {
                    ID = 100, Name = "New Bug"
                },
                    new TicketType {
                    ID = 200, Name = "Documentation Needed"
                },
                    new TicketType {
                    ID = 300, Name = "ScreenCast Demo Request"
                }
                    );
            }

            if (context.Projects.Count() == 0)
            {
                context.Projects.AddOrUpdate(
                    p => p.Name,
                    new Project {
                    ID = 100, Name = "Metal Gear"
                },
                    new Project {
                    ID = 200, Name = "Andromeda"
                },
                    new Project {
                    ID = 300, Name = "Samurai"
                }
                    );
            }

            if (context.Tickets.Count() == 0)
            {
                context.Tickets.AddOrUpdate(
                    p => p.Title,
                    new Ticket
                {
                    ProjectID        = 100,
                    TicketPriorityID = 300,
                    TicketStatusID   = 100,
                    TicketTypeID     = 100
                });


                context.Tickets.AddOrUpdate(
                    p => p.Title,
                    new Ticket
                {
                    ProjectID        = 200,
                    TicketPriorityID = 200,
                    TicketStatusID   = 300,
                    TicketTypeID     = 100
                });

                context.Tickets.AddOrUpdate(
                    p => p.Title,
                    new Ticket
                {
                    ProjectID        = 300,
                    TicketPriorityID = 100,
                    TicketStatusID   = 500,
                    TicketTypeID     = 100
                });
            }
        }
コード例 #49
0
ファイル: Configuration.cs プロジェクト: tollyx/MOAS-LMS
        protected override void Seed(MOAS_LMS.Models.ApplicationDbContext db)
        {
            var roleStore   = new RoleStore <IdentityRole>(db);
            var roleManager = new RoleManager <IdentityRole>(roleStore);

            var roleNames = new[] { "Admin", "User" };

            Console.WriteLine("Seeding Roles...");
            foreach (var roleName in roleNames)
            {
                if (db.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 userStore   = new UserStore <ApplicationUser>(db);
            var userManager = new UserManager <ApplicationUser>(userStore);

            var students = new[] { "*****@*****.**", "*****@*****.**", "*****@*****.**" };
            var admins   = new[] { "*****@*****.**", "*****@*****.**", "*****@*****.**" };

            Console.WriteLine("Seeding admins...");
            foreach (var email in admins)
            {
                if (db.Users.Any(u => u.UserName == email))
                {
                    continue;
                }
                var user = new ApplicationUser {
                    UserName = email, Email = email
                };
                var result = userManager.Create(user, "password");
                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors));
                }
                userManager.AddToRole(user.Id, "Admin");
            }

            db.ActivityTypes.AddOrUpdate(
                at => at.Name,
                new ActivityType {
                Name = "E-Learning", AllowUploads = false
            },
                new ActivityType {
                Name = "Seminar", AllowUploads = false
            },
                new ActivityType {
                Name = "Assignment", AllowUploads = true
            }
                );
            db.SaveChanges();
            Console.WriteLine("Seeding courses...");
            var courseNames = new[] { "C#/.Net", "Java/Spring", "Web development", "Python/Django", "Javascript/Node" };

            for (int i = 0; i < courseNames.Length; i++)
            {
                db.Courses.AddOrUpdate(
                    c => c.Title,
                    new CourseModel
                {
                    Title       = courseNames[i],
                    Description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                    StartDate   = DateTime.Now,
                    EndDate     = DateTime.Now.AddDays(13)
                }
                    );
            }
            db.SaveChanges();
            Console.WriteLine("Seeding users...");
            var usercourse = db.Courses.First();

            foreach (var email in students)
            {
                if (db.Users.Any(u => u.UserName == email))
                {
                    continue;
                }
                var user = new ApplicationUser {
                    UserName = email, Email = email, Course = usercourse, FirstName = email.Substring(0, email.IndexOf('@')), LastName = email.Substring(0, email.IndexOf('@')) + "sson"
                };
                var result = userManager.Create(user, "password");
                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors));
                }
                userManager.AddToRole(user.Id, "User");
            }

            db.SaveChanges();
            Console.WriteLine("Seeding modules...");
            var       moduleNames  = new[] { "C#", ".Net", "HTML", "C++", "ASP/MVC", "Java", "Spring", "Javascript", "Rust", "Python", "Django", "Assembly", "React", "Angular" };
            const int moduleLength = 3;

            foreach (var course in db.Courses.ToList())
            {
                for (int j = 0; j < 4; j++)
                {
                    db.Modules.AddOrUpdate(
                        c => c.Name,
                        new ModuleModel {
                        Name        = moduleNames[(course.Id + j) % moduleNames.Length] + course.Id,
                        Description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                        StartDate   = course.StartDate.AddDays(j * moduleLength),
                        EndDate     = course.StartDate.AddDays((j + 1) * moduleLength),
                        Course      = course
                    }
                        );
                }
            }

            db.SaveChanges();
            int       activityi      = 0;
            const int activitylength = 1;
            var       actTypes       = db.ActivityTypes.ToList();

            Console.WriteLine("Seeding activities...");
            foreach (var module in db.Modules.ToList())
            {
                foreach (var act in actTypes)
                {
                    db.Activities.AddOrUpdate(
                        a => a.Name,
                        new ActivityModel
                    {
                        Name         = act.Name + module.Id,
                        Description  = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                        StartDate    = module.StartDate.AddDays(activityi * activitylength),
                        EndDate      = module.StartDate.AddDays((activityi + 1) * activitylength),
                        ActivityType = act,
                        Module       = module,
                    }
                        );
                    activityi++;
                }
            }

            db.SaveChanges();
            var ext        = new[] { "exe", "zip", "rar", "7z", "docx", "pdf", "tar.gz", "md", "txt", "ppx", "png", "bmp", "gif", "html", "js", "cs", "java", "jar", "py", "rs" };
            var teachnames = new[] { "Instructions", "Seminar", "Links", "Virus", "Readme", "Assignment", "Todo", "Zenbu" };
            var teachers   = db.Users.Where(u => admins.Contains(u.Email)).ToList();

            Console.WriteLine("Seeding course docs....");
            foreach (var course in db.Courses.ToList())
            {
                if (course.Id % 2 == 0)
                {
                    var filename = $"{teachnames[course.Id % teachnames.Length]}.{ext[course.Id % ext.Length]}";
                    var doc      = new DocumentModel {
                        Uploader  = teachers[course.Id % teachers.Count],
                        Course    = course,
                        FileName  = filename,
                        Path      = $"Fake/Course/{course.Id}/{filename}",
                        IsHandIn  = false,
                        TimeStamp = course.StartDate.AddDays(-4),
                    };
                    db.Documents.AddOrUpdate(d => d.Path, doc);
                }
            }

            db.SaveChanges();
            Console.WriteLine("Seeding module docs...");
            foreach (var module in db.Modules.ToList())
            {
                if (module.Id % 2 == 0)
                {
                    var filename = $"{teachnames[module.Id % teachnames.Length]}.{ext[module.Id % ext.Length]}";
                    var doc      = new DocumentModel {
                        Uploader  = teachers[module.Id % teachers.Count],
                        Module    = module,
                        FileName  = filename,
                        Path      = $"Module/{module.Id}/{filename}",
                        IsHandIn  = false,
                        TimeStamp = module.StartDate.AddDays(-4),
                    };
                    db.Documents.AddOrUpdate(d => d.Path, doc);
                }
            }

            db.SaveChanges();
            Console.WriteLine("Seeding activity docs/hand-ins...");
            foreach (var activity in db.Activities.ToList())
            {
                if (activity.Id % 2 == 0)
                {
                    var filename = $"{teachnames[activity.Id % teachnames.Length]}.{ext[activity.Id % ext.Length]}";
                    var doc      = new DocumentModel {
                        Uploader  = teachers[activity.Id % teachers.Count],
                        Activity  = activity,
                        FileName  = filename,
                        Path      = $"Fake/Activity/{activity.Id}/{filename}",
                        IsHandIn  = false,
                        TimeStamp = activity.StartDate.AddDays(-4),
                    };
                    db.Documents.AddOrUpdate(d => d.Path, doc);
                }
                if (activity.ActivityType.AllowUploads)
                {
                    int i = activity.Id;
                    foreach (var student in activity.Module.Course.Students.ToList())
                    {
                        var filename = $"{activity.Name}-Handin.{ext[i % ext.Length]}";
                        var doc      = new DocumentModel {
                            Uploader  = student,
                            Activity  = activity,
                            FileName  = filename,
                            Path      = $"Fake/Activity/{activity.Id}/{filename}",
                            IsHandIn  = true,
                            TimeStamp = activity.EndDate.AddDays(-2 + i++ % 4),
                        };
                        if (i % 2 != 0)
                        {
                            doc.Feedback = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Maiores, vel aut sequi vero sapiente quidem quae odit? Explicabo quam autem consequuntur quibusdam ipsam, necessitatibus porro ipsum sequi, nihil tempore repudiandae.";
                        }
                        db.Documents.AddOrUpdate(d => d.Path, doc);
                    }
                }
            }
        }
コード例 #50
0
        protected override void Seed(DataContext context)
        {
            //  This method will be called after migrating to the latest version.

            var adminRole = new IdentityRole("Admin")
            {
                Id = "1"
            };
            var writerRole = new IdentityRole("Writer")
            {
                Id = "2"
            };

            context.Roles.AddOrUpdate(r => r.Id, adminRole, writerRole);

            context.SaveChanges();
            var user = context.Users.FirstOrDefault(u => u.UserName == "Admin");

            if (user == null)
            {
                var manager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
                var r       = manager.Create(new ApplicationUser
                {
                    UserName = "******"
                }, "admin123");
                user = context.Users.FirstOrDefault(u => u.UserName == "Admin");

                user.Roles.Add(new IdentityUserRole()
                {
                    RoleId = "1", UserId = user.Id
                });
                user.Roles.Add(new IdentityUserRole()
                {
                    RoleId = "2", UserId = user.Id
                });

                var tag1 = new Tag {
                    Label = "Hello"
                };
                var tag2 = new Tag {
                    Label = "Test"
                };
                context.Tags.AddOrUpdate(t => t.Label, tag1, tag2);
                context.SaveChanges();


                var text = "";
                using (var sr = new StreamReader(HttpContext.Current.Server.MapPath("~/Content/lorem.txt")))
                {
                    text = sr.ReadToEnd();
                }


                context.Posts.AddOrUpdate(p => p.Title, new BlogPost
                {
                    Author = user,
                    Title  = "Hello",
                    Tags   = new List <Tag>()
                    {
                        tag1, tag2
                    },
                    Created  = DateTime.UtcNow,
                    Updated  = DateTime.UtcNow,
                    IsDraft  = false,
                    Text     = text,
                    Comments = new List <Comment>()
                });

                context.SaveChanges();
            }
        }
コード例 #51
0
        protected override void Seed(TravelExpenseReport.Models.ApplicationDbContext context)
        {
            var roleStore   = new RoleStore <IdentityRole>(context);
            var roleManager = new RoleManager <IdentityRole>(roleStore);

            foreach (string roleName in new[] { "Assistant", "GroupAdmin", "Patient", "Administrator", "Other", "Outsider" })
            {
                if (!context.Roles.Any(r => r.Name == roleName))
                {
                    var role = new IdentityRole {
                        Name = roleName
                    };
                    roleManager.Create(role);
                }
            }

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

            var NewUserList = new List <ApplicationUser>();

            var users = new List <ApplicationUser> {
                new ApplicationUser {
                    FullName = "Oscar Antonsson", Email = "*****@*****.**", UserName = "******", CustomerId = 1
                },
                new ApplicationUser {
                    FullName = "Sara Björn", Email = "*****@*****.**", UserName = "******", CustomerId = 2
                },
                new ApplicationUser {
                    FullName = "Allan Persson", Email = "*****@*****.**", UserName = "******", CustomerId = 1
                }
            };

            foreach (var u in users)
            {
                userManager.Create(u, "foobar");
                var user = userManager.FindByEmail(u.Email);
                NewUserList.Add(user);
                userManager.AddToRole(user.Id, "GroupAdmin");
            }


            var users2 = new List <ApplicationUser> {
                new ApplicationUser {
                    FullName = "Lena Källgren", Email = "*****@*****.**", UserName = "******", CustomerId = 1
                },
                new ApplicationUser {
                    FullName = "Bella Ax", Email = "*****@*****.**", UserName = "******", CustomerId = 2
                },
                new ApplicationUser {
                    FullName = "Rickard Nilsson", Email = "*****@*****.**", UserName = "******", CustomerId = 1
                }
            };

            foreach (var u in users2)
            {
                userManager.Create(u, "foobar");
                var user = userManager.FindByEmail(u.Email);
                NewUserList.Add(user);
                userManager.AddToRole(user.Id, "Assistant");
            }

            var users3 = new List <ApplicationUser> {
                new ApplicationUser {
                    FullName = "Nicklas Sten", Email = "*****@*****.**", UserName = "******", CustomerId = 1, PatientId = 1
                },
                new ApplicationUser {
                    FullName = "Carmen Sanchez", Email = "*****@*****.**", UserName = "******", CustomerId = 2, PatientId = 2
                },
                new ApplicationUser {
                    FullName = "Diana Westman", Email = "*****@*****.**", UserName = "******", CustomerId = 2, PatientId = 3
                },
                new ApplicationUser {
                    FullName = "Eros Venti", Email = "*****@*****.**", UserName = "******", CustomerId = 1, PatientId = 4
                }
            };

            foreach (var u in users3)
            {
                userManager.Create(u, "foobar");
                var user = userManager.FindByEmail(u.Email);
                NewUserList.Add(user);
                userManager.AddToRole(user.Id, "Patient");
            }

            var users4 = new List <ApplicationUser> {
                new ApplicationUser {
                    FullName = "Anna Karlsson", Email = "*****@*****.**", UserName = "******", CustomerId = 1
                },
                new ApplicationUser {
                    FullName = "Ulf Svensson", Email = "*****@*****.**", UserName = "******", CustomerId = 2
                },
                new ApplicationUser {
                    FullName = "Paula Abdul", Email = "*****@*****.**", UserName = "******", CustomerId = 1
                }
            };

            foreach (var u in users4)
            {
                userManager.Create(u, "foobar");
                var user = userManager.FindByEmail(u.Email);
                NewUserList.Add(user);
                userManager.AddToRole(user.Id, "Administrator");
            }
            var users5 = new List <ApplicationUser> {
                new ApplicationUser {
                    FullName = "Klara Berguv", Email = "*****@*****.**", UserName = "******", CustomerId = 1
                },
                new ApplicationUser {
                    FullName = "Anton Vargas", Email = "*****@*****.**", UserName = "******", CustomerId = 2
                }
            };

            foreach (var u in users5)
            {
                userManager.Create(u, "foobar");
                var user = userManager.FindByEmail(u.Email);
                NewUserList.Add(user);
                userManager.AddToRole(user.Id, "Other");
            }
            var users6 = new List <ApplicationUser> {
                new ApplicationUser {
                    FullName = "Dan Asp", Email = "*****@*****.**", UserName = "******", CustomerId = 1
                },
                new ApplicationUser {
                    FullName = "Aston Martin", Email = "*****@*****.**", UserName = "******", CustomerId = 2
                }
            };

            foreach (var u in users6)
            {
                userManager.Create(u, "foobar");
                var user = userManager.FindByEmail(u.Email);
                NewUserList.Add(user);
                userManager.AddToRole(user.Id, "Outsider");
            }

            var expenseTypes = new List <ExpenseType> {
                new ExpenseType
                {
                    ExpenseTypeId   = 1,
                    ExpenseTypeName = "Tåg"
                },
                new ExpenseType
                {
                    ExpenseTypeId   = 2,
                    ExpenseTypeName = "Flyg"
                },
                new ExpenseType
                {
                    ExpenseTypeId   = 3,
                    ExpenseTypeName = "Taxi"
                },
                new ExpenseType
                {
                    ExpenseTypeId   = 4,
                    ExpenseTypeName = "Egen bil"
                },
                new ExpenseType
                {
                    ExpenseTypeId   = 5,
                    ExpenseTypeName = "Buss, spårvagn, tunnelbana"
                },
                new ExpenseType
                {
                    ExpenseTypeId   = 6,
                    ExpenseTypeName = "Hyrbil"
                },
                new ExpenseType
                {
                    ExpenseTypeId   = 7,
                    ExpenseTypeName = "Övrigt"
                }
            };

            foreach (var et in expenseTypes)
            {
                context.ExpenseTypes.AddOrUpdate(e => e.ExpenseTypeName, et);
            }

            var statusTypes = new List <StatusType> {
                new StatusType
                {
                    StatusTypeId = 1,
                    StatusName   = "Ny"
                },
                new StatusType
                {
                    StatusTypeId = 2,
                    StatusName   = "Inskickad"
                },
                new StatusType
                {
                    StatusTypeId = 3,
                    StatusName   = "Ej godkänd"
                },
                new StatusType
                {
                    StatusTypeId = 4,
                    StatusName   = "Godkänd"
                },
                new StatusType
                {
                    StatusTypeId = 5,
                    StatusName   = "Verifierad"
                },
                new StatusType
                {
                    StatusTypeId = 6,
                    StatusName   = "Utbetald"
                }
            };

            foreach (var st in statusTypes)
            {
                context.StatusTypes.AddOrUpdate(s => s.StatusName, st);
            }

            var legalAmount = new List <LegalAmount> {
                new LegalAmount
                {
                    LegalAmountId        = 1,
                    ValidDate            = DateTime.Parse("2014-01-01"),
                    FullDayAmount        = 210,
                    HalfDayAmount        = 105,
                    NightAmount          = 100,
                    MilageAmount         = 175,
                    BreakfastAmount      = 42,
                    LunchOrDinnerAmount  = 74,
                    LunchAndDinnerAmount = 148,
                    AllMealsAmount       = 190
                },
                new LegalAmount
                {
                    LegalAmountId        = 2,
                    ValidDate            = DateTime.Parse("2015-01-01"),
                    FullDayAmount        = 220,
                    HalfDayAmount        = 110,
                    NightAmount          = 110,
                    MilageAmount         = 185,
                    BreakfastAmount      = 44,
                    LunchOrDinnerAmount  = 77,
                    LunchAndDinnerAmount = 154,
                    AllMealsAmount       = 198
                }
            };

            foreach (var la in legalAmount)
            {
                context.LegalAmounts.AddOrUpdate(l => l.LegalAmountId, la);
            }

            var travelReport = new List <TravelReport> {
                new TravelReport
                {
                    TravelReportId      = 1,
                    ApplicationUserId   = NewUserList[2].Id,
                    PatientId           = 4,
                    TravelReportName    = "2016-001",
                    Destination         = "Flen",
                    Purpose             = "Utbildning",
                    DepartureDate       = DateTime.Parse("2016-04-20 00:00:00"),
                    DepartureTime       = TimeSpan.Parse("13:00:00"),
                    ReturnDate          = DateTime.Parse("2016-05-22 00:00:00"),
                    ReturnTime          = TimeSpan.Parse("16:00:00"),
                    DepartureHoursExtra = 1,
                    ReturnHoursExtra    = 2,
                    FullDay             = 33,
                    HalfDay             = 2,
                    Night = 33,
                    BreakfastDeduction      = 0,
                    LunchOrDinnerDeduction  = 0,
                    LunchAndDinnerDeduction = 0,
                    AllMealsDeduction       = 0,
                    StatusTypeId            = 1,
                    Comment = null
                },
                new TravelReport
                {
                    TravelReportId      = 2,
                    ApplicationUserId   = NewUserList[1].Id,
                    PatientId           = 3,
                    TravelReportName    = "2016-001",
                    Destination         = "Malmö",
                    Purpose             = "Studiebesök",
                    DepartureDate       = DateTime.Parse("2016-04-23 00:00:00"),
                    DepartureTime       = TimeSpan.Parse("08:30:00"),
                    ReturnDate          = DateTime.Parse("2016-04-27 00:00:00"),
                    ReturnTime          = TimeSpan.Parse("20:00:00"),
                    DepartureHoursExtra = 1,
                    ReturnHoursExtra    = 2,
                    FullDay             = 4,
                    HalfDay             = 0,
                    Night = 5,
                    BreakfastDeduction      = 0,
                    LunchOrDinnerDeduction  = 1,
                    LunchAndDinnerDeduction = 0,
                    AllMealsDeduction       = 0,
                    StatusTypeId            = 1,
                    Comment = null
                },
                new TravelReport
                {
                    TravelReportId      = 3,
                    ApplicationUserId   = NewUserList[3].Id,
                    PatientId           = 1,
                    TravelReportName    = "2016-001",
                    Destination         = "Uppsala",
                    Purpose             = "Läger",
                    DepartureDate       = DateTime.Parse("2016-04-20 00:00:00"),
                    DepartureTime       = TimeSpan.Parse("17:45:00"),
                    ReturnDate          = DateTime.Parse("2016-04-25 00:00:00"),
                    ReturnTime          = TimeSpan.Parse("07:30:00"),
                    DepartureHoursExtra = 2,
                    ReturnHoursExtra    = 0,
                    FullDay             = 4,
                    HalfDay             = 2,
                    Night = 5,
                    BreakfastDeduction      = 0,
                    LunchOrDinnerDeduction  = 0,
                    LunchAndDinnerDeduction = 1,
                    AllMealsDeduction       = 0,
                    StatusTypeId            = 1,
                    Comment = null
                },
                new TravelReport
                {
                    TravelReportId      = 4,
                    ApplicationUserId   = NewUserList[2].Id,
                    PatientId           = 1,
                    TravelReportName    = "2015-001",
                    Destination         = "Sundsvall",
                    Purpose             = "Besöka släkt över Valborg",
                    DepartureDate       = DateTime.Parse("2015-06-29 00:00:00"),
                    DepartureTime       = TimeSpan.Parse("11:59:00"),
                    ReturnDate          = DateTime.Parse("2015-08-01 00:00:00"),
                    ReturnTime          = TimeSpan.Parse("18:30:00"),
                    DepartureHoursExtra = 2,
                    ReturnHoursExtra    = 0,
                    FullDay             = 31,
                    HalfDay             = 2,
                    Night = 32,
                    BreakfastDeduction      = 0,
                    LunchOrDinnerDeduction  = 0,
                    LunchAndDinnerDeduction = 0,
                    AllMealsDeduction       = 10,
                    StatusTypeId            = 1,
                    Comment = null
                },
                new TravelReport
                {
                    TravelReportId      = 5,
                    ApplicationUserId   = NewUserList[5].Id,
                    PatientId           = 4,
                    TravelReportName    = "2016-001",
                    Destination         = "Göteborg",
                    Purpose             = "Besök på Liseberg",
                    DepartureDate       = DateTime.Parse("2016-04-24 00:00:00"),
                    DepartureTime       = TimeSpan.Parse("06:00:00"),
                    ReturnDate          = DateTime.Parse("2016-04-27 00:00:00"),
                    ReturnTime          = TimeSpan.Parse("17:00:00"),
                    DepartureHoursExtra = 0,
                    ReturnHoursExtra    = 2,
                    FullDay             = 3,
                    HalfDay             = 1,
                    Night = 3,
                    BreakfastDeduction      = 0,
                    LunchOrDinnerDeduction  = 0,
                    LunchAndDinnerDeduction = 0,
                    AllMealsDeduction       = 0,
                    StatusTypeId            = 1,
                    Comment = null
                },
                new TravelReport
                {
                    TravelReportId      = 6,
                    ApplicationUserId   = NewUserList[1].Id,
                    TravelReportName    = "2016-002",
                    PatientId           = 3,
                    Destination         = "Västerås",
                    Purpose             = "Bandymatch",
                    DepartureDate       = DateTime.Parse("2016-04-19 00:00:00"),
                    DepartureTime       = TimeSpan.Parse("08:30:00"),
                    ReturnDate          = DateTime.Parse("2016-05-29 00:00:00"),
                    ReturnTime          = TimeSpan.Parse("18:30:00"),
                    DepartureHoursExtra = 1,
                    ReturnHoursExtra    = 2,
                    FullDay             = 40,
                    HalfDay             = 1,
                    Night = 40,
                    BreakfastDeduction      = 0,
                    LunchOrDinnerDeduction  = 1,
                    LunchAndDinnerDeduction = 0,
                    AllMealsDeduction       = 0,
                    StatusTypeId            = 1,
                    Comment = null
                },
                new TravelReport
                {
                    TravelReportId      = 7,
                    ApplicationUserId   = NewUserList[3].Id,
                    PatientId           = 4,
                    TravelReportName    = "2016-002",
                    Destination         = "Enköping",
                    Purpose             = "Studiebesök boende",
                    DepartureDate       = DateTime.Parse("2016-04-26 00:00:00"),
                    DepartureTime       = TimeSpan.Parse("17:45:00"),
                    ReturnDate          = DateTime.Parse("2016-04-29 00:00:00"),
                    ReturnTime          = TimeSpan.Parse("07:30:00"),
                    DepartureHoursExtra = 2,
                    ReturnHoursExtra    = 0,
                    FullDay             = 2,
                    HalfDay             = 2,
                    Night = 3,
                    BreakfastDeduction      = 0,
                    LunchOrDinnerDeduction  = 0,
                    LunchAndDinnerDeduction = 0,
                    AllMealsDeduction       = 0,
                    StatusTypeId            = 1,
                    Comment = null
                },
                new TravelReport
                {
                    TravelReportId      = 8,
                    ApplicationUserId   = NewUserList[4].Id,
                    PatientId           = 2,
                    TravelReportName    = "2016-001",
                    Destination         = "Sundsvall",
                    Purpose             = "Besöka släkt",
                    DepartureDate       = DateTime.Parse("2016-05-02 00:00:00"),
                    DepartureTime       = TimeSpan.Parse("10:30:00"),
                    ReturnDate          = DateTime.Parse("2016-06-07 00:00:00"),
                    ReturnTime          = TimeSpan.Parse("19:30:00"),
                    DepartureHoursExtra = 0,
                    ReturnHoursExtra    = 2,
                    FullDay             = 37,
                    HalfDay             = 0,
                    Night = 36,
                    BreakfastDeduction      = 0,
                    LunchOrDinnerDeduction  = 0,
                    LunchAndDinnerDeduction = 0,
                    AllMealsDeduction       = 0,
                    StatusTypeId            = 2,
                    Comment = null
                },
                new TravelReport
                {
                    TravelReportId      = 9,
                    ApplicationUserId   = NewUserList[10].Id,
                    TravelReportName    = "2016-001",
                    PatientId           = 1,
                    Destination         = "Sälen",
                    Purpose             = "Konferens",
                    DepartureDate       = DateTime.Parse("2016-07-01 00:00:00"),
                    DepartureTime       = TimeSpan.Parse("08:45:00"),
                    ReturnDate          = DateTime.Parse("2016-07-13 00:00:00"),
                    ReturnTime          = TimeSpan.Parse("22:30:00"),
                    DepartureHoursExtra = 1,
                    ReturnHoursExtra    = 2,
                    FullDay             = 13,
                    HalfDay             = 0,
                    Night = 13,
                    BreakfastDeduction      = 0,
                    LunchOrDinnerDeduction  = 1,
                    LunchAndDinnerDeduction = 0,
                    AllMealsDeduction       = 0,
                    StatusTypeId            = 1,
                    Comment = null
                },
                new TravelReport
                {
                    TravelReportId      = 10,
                    ApplicationUserId   = NewUserList[11].Id,
                    PatientId           = 2,
                    TravelReportName    = "2016-001",
                    Destination         = "Malmö",
                    Purpose             = "Ledningsgruppsmöte",
                    DepartureDate       = DateTime.Parse("2016-07-14 00:00:00"),
                    DepartureTime       = TimeSpan.Parse("17:45:00"),
                    ReturnDate          = DateTime.Parse("2016-07-16 00:00:00"),
                    ReturnTime          = TimeSpan.Parse("19:30:00"),
                    DepartureHoursExtra = 2,
                    ReturnHoursExtra    = 0,
                    FullDay             = 1,
                    HalfDay             = 1,
                    Night = 1,
                    BreakfastDeduction      = 0,
                    LunchOrDinnerDeduction  = 0,
                    LunchAndDinnerDeduction = 0,
                    AllMealsDeduction       = 0,
                    StatusTypeId            = 1,
                    Comment = null
                }
            };


            foreach (var tr in travelReport)
            {
                context.TravelReports.AddOrUpdate(t => t.TravelReportId, tr);
            }


            //var expenses = new List<Expense> {
            //                new Expense
            //                {
            //                    ExpenseId = 1,
            //                    ExpenseTypeId = 1,
            //                    ExpenseDescription = null,
            //                    ExpenseDate = DateTime.Parse("2016-04-20"),
            //                    ExpenseAmountInfo = "140,15",
            //                    ExpenseAmount = 140,
            //                    ExpenseMilage = 0,
            //                    TravelReportId = 1
            //                },
            //                 new Expense
            //                {
            //                    ExpenseId = 2,
            //                    ExpenseTypeId = 3,
            //                    ExpenseDescription = null,
            //                    ExpenseDate = DateTime.Parse("2016-04-20"),
            //                    ExpenseAmountInfo = "345,45",
            //                    ExpenseAmount = 345,
            //                    ExpenseMilage = 0,
            //                    TravelReportId = 1
            //                },
            //                  new Expense
            //                {
            //                    ExpenseId = 3,
            //                    ExpenseTypeId = 2,
            //                    ExpenseDescription = null,
            //                    ExpenseDate = DateTime.Parse("2016-04-23"),
            //                    ExpenseAmountInfo = "350,45",
            //                    ExpenseAmount = 350,
            //                    ExpenseMilage = 0,
            //                    TravelReportId = 2
            //                },
            //                 new Expense
            //                {
            //                    ExpenseId = 4,
            //                    ExpenseTypeId= 2,
            //                    ExpenseDescription = null,
            //                    ExpenseDate = DateTime.Parse("2016-04-27"),
            //                    ExpenseAmountInfo = "3100,00",
            //                    ExpenseAmount = 3100,
            //                    ExpenseMilage = 0,
            //                    TravelReportId = 5
            //                },
            //                new Expense
            //                {
            //                    ExpenseId = 5,
            //                    ExpenseTypeId = 4,
            //                    ExpenseDescription = null,
            //                    ExpenseDate = DateTime.Parse("2016-04-25"),
            //                    ExpenseAmountInfo = "485,95",
            //                    ExpenseAmount = 0,
            //                    ExpenseMilage = 485,
            //                    TravelReportId = 5
            //                },
            //                 new Expense
            //                {
            //                    ExpenseId = 6,
            //                    ExpenseTypeId = 4,
            //                    ExpenseDescription  = null,
            //                    ExpenseDate = DateTime.Parse("2016-04-27"),
            //                    ExpenseAmountInfo = "766,98",
            //                    ExpenseAmount = 0,
            //                    ExpenseMilage = 375,
            //                    TravelReportId = 6
            //                },
            //                 new Expense
            //                {
            //                     ExpenseId = 7,
            //                     ExpenseTypeId = 2,
            //                     ExpenseDescription = null,
            //                     ExpenseDate = DateTime.Parse("2016-05-09"),
            //                     ExpenseAmountInfo = "5630,00",
            //                     ExpenseAmount = 5630,
            //                     ExpenseMilage = 0,
            //                    TravelReportId = 8
            //                },
            //                new Expense
            //                {
            //                    ExpenseId = 8,
            //                    ExpenseTypeId = 3,
            //                    ExpenseDescription = null,
            //                    ExpenseDate = DateTime.Parse("2016-05-07"),
            //                    ExpenseAmountInfo = "367,50",
            //                    ExpenseAmount = 367,
            //                    ExpenseMilage = 0,
            //                    TravelReportId = 8
            //                 }
            //};

            //foreach (var ex in expenses)
            //{
            //    context.Expenses.AddOrUpdate(e => e.ExpenseId, ex);
            //    //context.ExpenseTypes.AddOrUpdate(et);

            //}


            var patients = new List <Patient> {
                new Patient
                {
                    PatientId   = 1,
                    PatientName = NewUserList[6].FullName,
                    UserId      = NewUserList[6].Id,
                    CustomerId  = NewUserList[6].CustomerId
                },
                new Patient
                {
                    PatientId   = 2,
                    PatientName = NewUserList[7].FullName,
                    UserId      = NewUserList[7].Id,
                    CustomerId  = NewUserList[7].CustomerId
                },
                new Patient
                {
                    PatientId   = 3,
                    PatientName = NewUserList[8].FullName,
                    UserId      = NewUserList[8].Id,
                    CustomerId  = NewUserList[8].CustomerId
                },
                new Patient
                {
                    PatientId   = 4,
                    PatientName = NewUserList[9].FullName,
                    UserId      = NewUserList[9].Id,
                    CustomerId  = NewUserList[9].CustomerId
                }
            };

            foreach (var pt in patients)
            {
                context.Patients.AddOrUpdate(p => p.PatientId, pt);
            }

            var staffRoles = new List <StaffRole> {
                new StaffRole
                {
                    StaffRoleId = 1,
                    Name        = "Assistent"
                },
                new StaffRole
                {
                    StaffRoleId = 2,
                    Name        = "Arbetsledare"
                },
                new StaffRole
                {
                    StaffRoleId = 3,
                    Name        = "Administratör"
                },
                new StaffRole
                {
                    StaffRoleId = 4,
                    Name        = "Övrig"
                }
            };

            foreach (var sr in staffRoles)
            {
                context.StaffRoles.AddOrUpdate(s => s.StaffRoleId, sr);
            }


            var patientUsers = new List <PatientUser> {
                new PatientUser
                {
                    PatientUserId = 1,
                    PatientId     = 1,
                    StaffUserId   = NewUserList[3].Id,
                    StaffRoleId   = 1
                },
                new PatientUser
                {
                    PatientUserId = 2,
                    PatientId     = 2,
                    StaffUserId   = NewUserList[4].Id,
                    StaffRoleId   = 1
                },
                new PatientUser
                {
                    PatientUserId = 3,
                    PatientId     = 3,
                    StaffUserId   = NewUserList[4].Id,
                    StaffRoleId   = 1
                },
                new PatientUser
                {
                    PatientUserId = 4,
                    PatientId     = 1,
                    StaffUserId   = NewUserList[2].Id,
                    StaffRoleId   = 2
                },
                new PatientUser
                {
                    PatientUserId = 5,
                    PatientId     = 2,
                    StaffUserId   = NewUserList[1].Id,
                    StaffRoleId   = 2
                },
                new PatientUser
                {
                    PatientUserId = 6,
                    PatientId     = 3,
                    StaffUserId   = NewUserList[1].Id,
                    StaffRoleId   = 2
                },
                new PatientUser
                {
                    PatientUserId = 7,
                    PatientId     = 4,
                    StaffUserId   = NewUserList[5].Id,
                    StaffRoleId   = 1
                },
                new PatientUser
                {
                    PatientUserId = 8,
                    PatientId     = 4,
                    StaffUserId   = NewUserList[2].Id,
                    StaffRoleId   = 2
                },
                new PatientUser
                {
                    PatientUserId = 9,
                    PatientId     = 4,
                    StaffUserId   = NewUserList[3].Id,
                    StaffRoleId   = 1
                },
                new PatientUser
                {
                    PatientUserId = 10,
                    PatientId     = 1,
                    StaffUserId   = NewUserList[0].Id,
                    StaffRoleId   = 1
                },
                new PatientUser
                {
                    PatientUserId = 11,
                    PatientId     = 1,
                    StaffUserId   = NewUserList[13].Id,
                    StaffRoleId   = 4
                },
                new PatientUser
                {
                    PatientUserId = 12,
                    PatientId     = 2,
                    StaffUserId   = NewUserList[14].Id,
                    StaffRoleId   = 4
                },
                new PatientUser
                {
                    PatientUserId = 13,
                    PatientId     = 3,
                    StaffUserId   = NewUserList[14].Id,
                    StaffRoleId   = 4
                }
            };

            foreach (var pu in patientUsers)
            {
                context.PatientUsers.AddOrUpdate(p => p.PatientUserId, pu);
            }

            var note = new List <Note> {
                new Note
                {
                    NoteId            = 1,
                    NoteTime          = DateTime.Now,
                    NoteInfo          = "Skickar in",
                    NoteStatus        = "Ny",
                    TravelReportId    = 7,
                    ApplicationUserId = NewUserList[3].FullName
                },
                new Note
                {
                    NoteId            = 2,
                    NoteTime          = DateTime.Now,
                    NoteInfo          = "Inte godkänd",
                    NoteStatus        = "Ej godkänd",
                    TravelReportId    = 7,
                    ApplicationUserId = NewUserList[2].FullName
                },
                new Note
                {
                    NoteId            = 3,
                    NoteTime          = DateTime.Now,
                    NoteInfo          = "Skickar in igen",
                    NoteStatus        = "Inskickad",
                    TravelReportId    = 7,
                    ApplicationUserId = NewUserList[3].FullName
                },
                new Note
                {
                    NoteId            = 4,
                    NoteTime          = DateTime.Now,
                    NoteInfo          = "Godkänd",
                    NoteStatus        = "Godkänd",
                    TravelReportId    = 7,
                    ApplicationUserId = NewUserList[10].FullName
                }
            };

            foreach (var nr in note)
            {
                context.Notes.AddOrUpdate(n => n.NoteId, nr);
            }
        }
コード例 #52
0
        protected override void Seed(T2.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.


            var manager     = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new ApplicationDbContext()));

            var userAdmin = new ApplicationUser()
            {
                UserName        = "******",
                Email           = "*****@*****.**",
                EmailConfirmed  = true,
                FirstName       = "Vittorio",
                LastName        = "Cicognani",
                Level           = 1,
                JoinDate        = DateTime.Now,
                NCorrectAnswers = 0,
                NFaultAnswers   = 0
            };

            manager.Create(userAdmin, "MySuperP@ssword!!");


            var userCertificator = new ApplicationUser()
            {
                UserName        = "******",
                Email           = "*****@*****.**",
                EmailConfirmed  = true,
                FirstName       = "Maurizio   ",
                LastName        = "Ori",
                Level           = 2,
                JoinDate        = DateTime.Now,
                NCorrectAnswers = 0,
                NFaultAnswers   = 0
            };

            manager.Create(userCertificator, "MyCertificatorP@ssword!!");


            var userSimple = new ApplicationUser()
            {
                UserName        = "******",
                Email           = "*****@*****.**",
                EmailConfirmed  = true,
                FirstName       = "Matteo",
                LastName        = "Argnani",
                Level           = 3,
                JoinDate        = DateTime.Now,
                NCorrectAnswers = 0,
                NFaultAnswers   = 0
            };

            manager.Create(userSimple, "MySimpleP@ssword!!!");



            if (roleManager.Roles.Count() == 0)
            {
                roleManager.Create(new IdentityRole {
                    Name = "SuperAdmin"
                });
                roleManager.Create(new IdentityRole {
                    Name = "Admin"
                });
                roleManager.Create(new IdentityRole {
                    Name = "User"
                });
            }

            var adminUser = manager.FindByName("SuperPowerUser");

            manager.AddToRoles(adminUser.Id, new string[] { "SuperAdmin" });

            var certificatorUser = manager.FindByName("CertificatorUser");

            manager.AddToRoles(certificatorUser.Id, new string[] { "Admin" });

            var simpleUser = manager.FindByName("SimpleUser");

            manager.AddToRoles(simpleUser.Id, new string[] { "User" });
        }
コード例 #53
0
        public static Response CreateUserASP(UserRequest userRequest)
        {
            try
            {
                var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(userContext));
                var oldUserASP  = userManager.FindByEmail(userRequest.EMail);
                if (oldUserASP != null)
                {
                    return(new Response
                    {
                        IsSuccess = false,
                        Message = "001. User already exists"
                    });
                }

                var userASP = new ApplicationUser
                {
                    Email       = userRequest.EMail,
                    UserName    = userRequest.EMail,
                    PhoneNumber = userRequest.Phone
                };

                var result = userManager.Create(userASP, userRequest.Password);

                if (result.Succeeded)
                {
                    var newUserASP = userManager.FindByEmail(userRequest.EMail);
                    userManager.AddClaim(newUserASP.Id, new Claim(ClaimTypes.GivenName, userRequest.FistName));
                    userManager.AddClaim(newUserASP.Id, new Claim(ClaimTypes.Name, userRequest.LastName));

                    if (!string.IsNullOrEmpty(userRequest.Address))
                    {
                        userManager.AddClaim(newUserASP.Id, new Claim(ClaimTypes.StreetAddress, userRequest.Address));
                    }

                    if (!string.IsNullOrEmpty(userRequest.ImagePath))
                    {
                        userManager.AddClaim(newUserASP.Id, new Claim(ClaimTypes.Uri, userRequest.ImagePath));
                    }

                    return(new Response
                    {
                        IsSuccess = true
                    });
                }

                var errors = string.Empty;
                foreach (var error in result.Errors)
                {
                    errors += $"{error}, ";
                }

                return(new Response
                {
                    IsSuccess = false,
                    Message = errors
                });
            }
            catch (Exception ex)
            {
                return(new Response
                {
                    IsSuccess = false,
                    Message = ex.Message
                });
            }
        }
コード例 #54
0
        protected override void Seed(ApplicationDbContext context)
        {
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            if (!roleManager.RoleExists("Editor"))
            {
                roleManager.Create(new IdentityRole("Editor"));
            }
            var user1 = new ApplicationUser
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };
            var userCreated1 = userManager.Create(user1, "Testtest1!");

            if (userCreated1.Succeeded)
            {
                userManager.AddToRole(user1.Id, "Editor");
            }



            var user2 = new ApplicationUser
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };
            var userCreated2 = userManager.Create(user2, "Testtest1!");

            if (userCreated2.Succeeded)
            {
                userManager.AddToRole(user2.Id, "Editor");
            }


            var user3 = new ApplicationUser
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };
            var userCreated3 = userManager.Create(user3, "Testtest1!");

            if (userCreated3.Succeeded)
            {
                userManager.AddToRole(user3.Id, "Editor");
            }



            var user4 = new ApplicationUser
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };
            var userCreated4 = userManager.Create(user4, "Testtest1!");

            if (userCreated4.Succeeded)
            {
                userManager.AddToRole(user4.Id, "Editor");
            }



            var user5 = new ApplicationUser
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };
            var userCreated5 = userManager.Create(user5, "Testtest1!");

            if (userCreated5.Succeeded)
            {
                userManager.AddToRole(user5.Id, "Editor");
            }


            //Location SEED
            context.Locations.Add(new Location {
                LocationId = 1, Country = "Romania", City = "Alba-Iulia", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 2, Country = "Romania", City = "Alba-Iulia", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 3, Country = "Romania", City = "Alexandria", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 4, Country = "Romania", City = "Alexandria", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 5, Country = "Romania", City = "Arad", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 6, Country = "Romania", City = "Arad", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 7, Country = "Romania", City = "Bacau", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 8, Country = "Romania", City = "Bacau", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 9, Country = "Romania", City = "Baia Mare", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 10, Country = "Romania", City = "Baia Mare", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 11, Country = "Romania", City = "Bistrita", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 12, Country = "Romania", City = "Bistrita", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 13, Country = "Romania", City = "Botosani", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 14, Country = "Romania", City = "Botosani", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 15, Country = "Romania", City = "Brasov", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 16, Country = "Romania", City = "Brasov", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 17, Country = "Romania", City = "Braila", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 18, Country = "Romania", City = "Braila", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 19, Country = "Romania", City = "Bucuresti", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 20, Country = "Romania", City = "Bucuresti", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 21, Country = "Romania", City = "Buzau", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 22, Country = "Romania", City = "Buzau", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 23, Country = "Romania", City = "Calarasi", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 24, Country = "Romania", City = "Calarasi", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 25, Country = "Romania", City = "Cluj-Napoca", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 26, Country = "Romania", City = "Cluj-Napoca", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 27, Country = "Romania", City = "Constanta", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 28, Country = "Romania", City = "Constanta", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 29, Country = "Romania", City = "Craiova", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 30, Country = "Romania", City = "Craiova", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 31, Country = "Romania", City = "Deva", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 32, Country = "Romania", City = "Deva", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 33, Country = "Romania", City = "Drobeta-Turnu-Severin", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 34, Country = "Romania", City = "Drobeta-Turnu-Severin", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 35, Country = "Romania", City = "Focsani", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 36, Country = "Romania", City = "Focsani", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 37, Country = "Romania", City = "Galati", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 38, Country = "Romania", City = "Galati", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 39, Country = "Romania", City = "Giurgiu", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 40, Country = "Romania", City = "Giurgiu", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 41, Country = "Romania", City = "Iasi", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 42, Country = "Romania", City = "Iasi", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 43, Country = "Romania", City = "Miercurea Ciuc", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 44, Country = "Romania", City = "Miercurea Ciuc", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 45, Country = "Romania", City = "Oradea", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 46, Country = "Romania", City = "Oradea", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 47, Country = "Romania", City = "Piatra Neamt", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 48, Country = "Romania", City = "Piatra Neamt", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 49, Country = "Romania", City = "Pitesti", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 50, Country = "Romania", City = "Pitesti", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 51, Country = "Romania", City = "Ploiesti", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 52, Country = "Romania", City = "Ploiest", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 53, Country = "Romania", City = "Ramnicu Valcea", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 54, Country = "Romania", City = "Ramnicu Valcea", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 55, Country = "Romania", City = "Resita", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 56, Country = "Romania", City = "Resita", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 57, Country = "Romania", City = "Satu Mare", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 58, Country = "Romania", City = "Satu Mare", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 59, Country = "Romania", City = "Sfantu Gheorghe", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 60, Country = "Romania", City = "Sfantu Gheorghe", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 61, Country = "Romania", City = "Sibiu", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 62, Country = "Romania", City = "Sibiu", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 63, Country = "Romania", City = "Slatina", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 64, Country = "Romania", City = "Slatina", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 65, Country = "Romania", City = "Slobozia", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 66, Country = "Romania", City = "Slobozia", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 67, Country = "Romania", City = "Suceava", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 68, Country = "Romania", City = "Suceava", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 69, Country = "Romania", City = "Targoviste", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 70, Country = "Romania", City = "Targoviste", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 71, Country = "Romania", City = "Targu Jiu", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 72, Country = "Romania", City = "Targu Jiu", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 73, Country = "Romania", City = "Targu Mures", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 74, Country = "Romania", City = "Targu Mures", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 75, Country = "Romania", City = "Timisoara", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 76, Country = "Romania", City = "Timisoara", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 77, Country = "Romania", City = "Tulcea", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 78, Country = "Romania", City = "Tulcea", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 79, Country = "Romania", City = "Vaslui", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 80, Country = "Romania", City = "Vaslui", Placement = Zone.Periferial
            });
            context.Locations.Add(new Location {
                LocationId = 81, Country = "Romania", City = "Zalau", Placement = Zone.Central
            });
            context.Locations.Add(new Location {
                LocationId = 82, Country = "Romania", City = "Zalau", Placement = Zone.Periferial
            });



            //Housing SEED
            context.Housings.Add(new Housing {
                HousingId = 1, Link = "https://www.olx.ro/oferta/garsoniera-de-inchiriat-IDeq6lo.html#bb6f20793c;promoted", Price = 1100, NoOfRooms = 1, LocationId = 15
            });
            context.Housings.Add(new Housing {
                HousingId = 2, Link = "https://www.olx.ro/oferta/inchiriez-apartament-2-camere-studio-coresi-avantgarden-brasov-IDer4E6.html#c48a4bf265;promoted", Price = 1900, NoOfRooms = 2, LocationId = 16
            });
            context.Housings.Add(new Housing {
                HousingId = 3, Link = "https://www.olx.ro/oferta/chirie-apartament-3-camere-lujerului-IDenLrR.html#0ede99b094;promoted", Price = 1900, NoOfRooms = 3, LocationId = 19
            });
            context.Housings.Add(new Housing {
                HousingId = 4, Link = "https://www.olx.ro/oferta/chirie-apartament-3-camere-unirii-camera-de-comert-caut-coleg-IDeh0B5.html#0ede99b094;promoted", Price = 950, NoOfRooms = 3, LocationId = 19
            });
            context.Housings.Add(new Housing {
                HousingId = 5, Link = "https://www.olx.ro/oferta/garsoniera-chirie-IDdVUEb.html#0abeddb25a;promoted", Price = 900, NoOfRooms = 1, LocationId = 19
            });
            context.Housings.Add(new Housing {
                HousingId = 6, Link = "https://www.storia.ro/ro/oferta/urgent-gars-prima-chirie-in-residence-militari-1000lei-IDk6GY.html", Price = 1000, NoOfRooms = 1, LocationId = 19
            });
            context.Housings.Add(new Housing {
                HousingId = 7, Link = "https://www.olx.ro/oferta/garsoniera-chirie-IDerhis.html#0ede99b094", Price = 1000, NoOfRooms = 1, LocationId = 20
            });
            context.Housings.Add(new Housing {
                HousingId = 8, Link = "https://www.storia.ro/ro/oferta/apartament-2-camere-chirie-rond-pipera-penny-IDlJYz.html", Price = 2500, NoOfRooms = 2, LocationId = 20
            });
            context.Housings.Add(new Housing {
                HousingId = 9, Link = "https://www.storia.ro/ro/oferta/apartament-cu-4-camere-162-mp-3-terase-garaj-zona-strazii-buna-IDlyrS.html", Price = 4000, NoOfRooms = 4, LocationId = 25
            });
            context.Housings.Add(new Housing {
                HousingId = 10, Link = "https://www.olx.ro/oferta/inchiriez-apartament-2-camere-manastur-IDeq6Pn.html#2a0d862cf5;promoted", Price = 2000, NoOfRooms = 2, LocationId = 25
            });
            context.Housings.Add(new Housing {
                HousingId = 11, Link = "https://www.storia.ro/ro/oferta/apartament-2-camere-semidecomandat-gheorgheni-aleea-padis-IDkiYO.html", Price = 1500, NoOfRooms = 2, LocationId = 26
            });
            context.Housings.Add(new Housing {
                HousingId = 12, Link = "https://www.olx.ro/oferta/inchiriere-apartament-IDereOH.html#9d238f6d60;promoted", Price = 2400, NoOfRooms = 4, LocationId = 27
            });
            context.Housings.Add(new Housing {
                HousingId = 13, Link = "https://www.olx.ro/oferta/inchiriez-apartament-2-camere-la-casa-zona-centrala-promenada-mall-IDedZlj.html#93e8e400cc;promoted", Price = 1200, NoOfRooms = 2, LocationId = 61
            });
            context.Housings.Add(new Housing {
                HousingId = 14, Link = "https://www.olx.ro/oferta/chirie-fara-garantie-pe-termne-scurt-comisioane-0-IDdqorY.html#4e1af1f3e1;promoted", Price = 1000, NoOfRooms = 1, LocationId = 75
            });
            context.Housings.Add(new Housing {
                HousingId = 15, Link = "https://www.olx.ro/oferta/apartament-2-camere-linistit-langa-iulius-mall-IDdYaml.html#4e1af1f3e1;promoted", Price = 1600, NoOfRooms = 2, LocationId = 75
            });



            //Ads SEED
            context.Ads.Add(new Ad {
                AdId = 1, ProfileId = 1, Housing = context.Housings.Find(3), HousingYear = 2021, HousingMonth = "09", HousingDay = "15"
            });
            context.Ads.Add(new Ad {
                AdId = 2, ProfileId = 2, Housing = context.Housings.Find(4), HousingYear = 2021, HousingMonth = "10", HousingDay = "01"
            });
            context.Ads.Add(new Ad {
                AdId = 3, ProfileId = 4, Housing = context.Housings.Find(5), HousingYear = 2021, HousingMonth = "10", HousingDay = "01"
            });
            context.Ads.Add(new Ad {
                AdId = 4, ProfileId = 5, Housing = context.Housings.Find(7), HousingYear = 2021, HousingMonth = "09", HousingDay = "01"
            });


            Profile profile1 = new Profile {
                ProfileId = 1, FirstName = "Andrei", LastName = "Popescu", Age = 19, GenderType = Gender.Male, LocationId = 19, AplicationUserName = "******"
            };
            Profile profile2 = new Profile {
                ProfileId = 2, FirstName = "Alexanda", LastName = "Ionescu", Age = 20, GenderType = Gender.Female, LocationId = 27, AplicationUserName = "******"
            };
            Profile profile3 = new Profile {
                ProfileId = 3, FirstName = "Daniel", LastName = "Baltariu", Age = 19, GenderType = Gender.Male, LocationId = 28, AplicationUserName = "******"
            };
            Profile profile4 = new Profile {
                ProfileId = 4, FirstName = "Andreea", LastName = "Stanculescu", Age = 20, GenderType = Gender.Female, LocationId = 19, AplicationUserName = "******"
            };
            Profile profile5 = new Profile {
                ProfileId = 5, FirstName = "Stefan", LastName = "Popescu", Age = 22, GenderType = Gender.Others, LocationId = 75, AplicationUserName = "******"
            };

            context.Profiles.Add(profile1);
            context.Profiles.Add(profile2);
            context.Profiles.Add(profile3);
            context.Profiles.Add(profile4);
            context.Profiles.Add(profile5);



            context.SaveChanges();
            base.Seed(context);
        }
コード例 #55
0
        protected override void Seed(SAS_LMS.Models.ApplicationDbContext context)
        {
            var roleStore   = new RoleStore <IdentityRole>(context);
            var roleManager = new RoleManager <IdentityRole>(roleStore);
            var roleName    = "Teacher";

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

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

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

            var email = "*****@*****.**";

            if (!context.Users.Any(u => u.UserName == email))
            {
                var user = new ApplicationUser
                {
                    UserName       = email,
                    Email          = email,
                    EnrollmentDate = DateTime.Now
                };
                var result = userManager.Create(user, "Admin123!");
                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors));
                }
            }

            var adminUser = userManager.FindByName("*****@*****.**");

            userManager.AddToRole(adminUser.Id, "Teacher");

            context.ActivityTypes.AddOrUpdate(
                p => p.Name,
                new ActivityType {
                Name = "e-Learning"
            },
                new ActivityType {
                Name = "Lecture"
            },
                new ActivityType {
                Name = "Exercise"
            },
                new ActivityType {
                Name = "Submission"
            }
                );
        }
コード例 #56
0
        protected override void Seed(BlogTest.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.

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

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

            if (!context.Roles.Any(r => r.Name == "Moderator"))
            {
                roleManger.Create(new IdentityRole {
                    Name = "Moderator"
                });
            }

            #region Add User creation and role assignment
            var userStore  = new UserStore <ApplicationUser>(context);
            var userManger = new UserManager <ApplicationUser>(userStore);

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Benjamin",
                    LastName    = "Yarema",
                    DisplayName = "BenLee"
                };
                //Creates the user in the DB
                userManger.Create(user, "Abc&123!");

                //here we attach the admin role to this user
                userManger.AddToRoles(user.Id, "Admin");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Jason",
                    LastName    = "Twichell",
                    DisplayName = "Prof"
                };
                //Creates the user in the DB
                userManger.Create(user, "Abc&123!");

                //here we attach the admin role to this user
                userManger.AddToRoles(user.Id, "Moderator");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Andrew",
                    LastName    = "Russell",
                    DisplayName = "Prof's SideKick"
                };
                //Creates the user in the DB
                userManger.Create(user, "Abc&123!");

                //here we attach the admin role to this user
                userManger.AddToRoles(user.Id, "Moderator");
            }

            #endregion

            #region



            #endregion
        }
コード例 #57
0
ファイル: Configuration.cs プロジェクト: llenroc/swetugg-web
        protected override void Seed(Swetugg.Web.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

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

                manager.Create(role);
            }

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

                manager.Create(role);
            }

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

                manager.Create(role);
            }

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

                manager.Create(role);
            }

            if (!context.Users.Any())
            {
                // If no users have been created yet, insert a default Admin account.
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };

                manager.Create(user, "ChangeMe.123");
                manager.AddToRoles(user.Id, "Administrator", "ConferenceManager", "User");
            }
        }
コード例 #58
0
        protected override void Seed(WebApplication5.Models.ApplicationDbContext context)
        {
            // ADD 3 TEST USERS WITH DIFFERENT ROLES
            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new UserManager <ApplicationUser>(userStore);

            if (!context.Users.Any(t => t.UserName == "*****@*****.**"))
            {
                var user = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                userManager.Create(user, "Passw0rd!");

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

                userManager.AddToRole(user.Id, "TCAdmin");
            }

            if (!context.Users.Any(t => t.UserName == "*****@*****.**"))
            {
                var user = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                userManager.Create(user, "Passw0rd!");

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

                userManager.AddToRole(user.Id, "TCManager");
            }

            if (!context.Users.Any(t => t.UserName == "*****@*****.**"))
            {
                var user = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                userManager.Create(user, "Passw0rd!");

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

                userManager.AddToRole(user.Id, "TCAgent");
            }
            //  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" }
            //    );
            //
        }
コード例 #59
0
        protected override void Seed(BugTracker.Models.ApplicationDbContext context)
        {
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

            if (!context.Roles.Any(r => r.Name == "Admin"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "Admin"
                });
            }
            if (!context.Roles.Any(r => r.Name == "Project Manager"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "Project Manager"
                });
            }
            if (!context.Roles.Any(r => r.Name == "Developer"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "Developer"
                });
            }
            if (!context.Roles.Any(r => r.Name == "Submitter"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "Submitter"
                });
            }

            ApplicationUser adminUser = null;

            if (!context.Users.Any(p => p.UserName == "*****@*****.**"))
            {
                adminUser             = new ApplicationUser();
                adminUser.UserName    = "******";
                adminUser.Email       = "*****@*****.**";
                adminUser.Name        = "Admin";
                adminUser.LastName    = "User";
                adminUser.DisplayName = "Shital";
                userManager.Create(adminUser, "Password-1");
            }
            else
            {
                adminUser = context.Users.Where(p => p.UserName == "*****@*****.**")
                            .FirstOrDefault();
            }
            if (!userManager.IsInRole(adminUser.Id, "Admin"))
            {
                userManager.AddToRole(adminUser.Id, "Admin");
            }

            ApplicationUser devUser = null;

            if (!context.Users.Any(p => p.UserName == "*****@*****.**"))
            {
                devUser             = new ApplicationUser();
                devUser.UserName    = "******";
                devUser.Email       = "*****@*****.**";
                devUser.Name        = "Developer";
                devUser.LastName    = "User";
                devUser.DisplayName = "Mark";
                userManager.Create(devUser, "Password-1");
            }
            else
            {
                devUser = context.Users.Where(p => p.UserName == "*****@*****.**")
                          .FirstOrDefault();
            }

            ApplicationUser projectUser = null;

            if (!context.Users.Any(p => p.UserName == "*****@*****.**"))
            {
                projectUser             = new ApplicationUser();
                projectUser.UserName    = "******";
                projectUser.Email       = "*****@*****.**";
                projectUser.Name        = "ProjectManager";
                projectUser.LastName    = "User";
                projectUser.DisplayName = "Jay";
                userManager.Create(projectUser, "Password-1");
            }
            else
            {
                projectUser = context.Users.Where(p => p.UserName == "*****@*****.**")
                              .FirstOrDefault();
            }

            ApplicationUser submitterUser = null;

            if (!context.Users.Any(p => p.UserName == "*****@*****.**"))
            {
                submitterUser             = new ApplicationUser();
                submitterUser.UserName    = "******";
                submitterUser.Email       = "*****@*****.**";
                submitterUser.Name        = "Submitter";
                submitterUser.LastName    = "User";
                submitterUser.DisplayName = "Jhon";
                userManager.Create(submitterUser, "Password-1");
            }
            else
            {
                submitterUser = context.Users.Where(p => p.UserName == "*****@*****.**")
                                .FirstOrDefault();
            }
            if (!userManager.IsInRole(submitterUser.Id, "Submitter"))
            {
                userManager.AddToRole(submitterUser.Id, "Submitter");
            }
            if (!userManager.IsInRole(devUser.Id, "Developer"))
            {
                userManager.AddToRole(devUser.Id, "Developer");
            }
            if (!userManager.IsInRole(projectUser.Id, "Project Manager"))
            {
                userManager.AddToRole(projectUser.Id, "Project Manager");
            }

            context.Types.AddOrUpdate(
                new Models.Classes.Type()
            {
                Id = 1, Name = "Bug Fixes"
            },
                new Models.Classes.Type()
            {
                Id = 2, Name = "Software Update"
            },
                new Models.Classes.Type()
            {
                Id = 3, Name = "Adding Helpers"
            },
                new Models.Classes.Type()
            {
                Id = 4, Name = "Database Error"
            }
                );
            context.Prorities.AddOrUpdate(
                new Models.Classes.Priority()
            {
                Id = 1, Name = "High"
            },
                new Models.Classes.Priority()
            {
                Id = 2, Name = "Low"
            },
                new Models.Classes.Priority()
            {
                Id = 3, Name = "Medium"
            },
                new Models.Classes.Priority()
            {
                Id = 4, Name = "Urgent"
            }
                );
            context.Statues.AddOrUpdate(
                new Models.Classes.Status()
            {
                Id = 1, Name = "Not Started"
            },
                new Models.Classes.Status()
            {
                Id = 2, Name = "Finished"
            },
                new Models.Classes.Status()
            {
                Id = 3, Name = "On Hold"
            },
                new Models.Classes.Status()
            {
                Id = 4, Name = "In Progress"
            }
                );
        }
コード例 #60
0
ファイル: Startup.cs プロジェクト: diina-gh/Green
        private void createRolesandUsers()
        {
            ApplicationDbContext context = new ApplicationDbContext();

            ServiceMetierPlants.Service1Client service = new ServiceMetierPlants.Service1Client();

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

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

                    var user = new ApplicationUser();
                    user.UserName = "******";
                    user.Email    = "*****@*****.**";
                    string userPWD = "P@ssword01";
                    var    chkUser = UserManager.Create(user, userPWD);

                    Utilisateur u = new Utilisateur();
                    u.NomPrenomU   = "Anid";
                    u.IdentifiantU = user.UserName;
                    u.EmailU       = user.Email;
                    u.TelU         = "770123456";
                    u.IdUser       = user.Id;
                    service.AddUtilisateur(u);

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

                // creating Creating AGENT DE SAISIE role
                if (!roleManager.RoleExists("Medecin"))
                {
                    var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                    role.Name = "Medecin";
                    roleManager.Create(role);
                    Profil p = new Profil();
                    p.LibelleProfil = "Medecin";
                    service.AddProfil(p);
                    //db.profils.Add(p);
                    //db.SaveChanges();
                }
                // creating Creating AGENT DE SAISIE role
                if (!roleManager.RoleExists("Sécrétaire"))
                {
                    var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                    role.Name = "Sécrétaire";
                    roleManager.Create(role);
                    Profil p = new Profil();
                    p.LibelleProfil = "Sécrétaire";
                    service.AddProfil(p);
                    //db.profils.Add(p);
                    //db.SaveChanges();
                }
                var leUser = UserManager.FindByName("Hady");
                if (leUser == null)
                {
                    var user = new ApplicationUser();
                    user.UserName = "******";
                    user.Email    = "*****@*****.**";
                    string userPWD = "P@ssword01";
                    var    chkUser = UserManager.Create(user, userPWD);

                    Utilisateur u = new Utilisateur();
                    u.NomPrenomU   = "Dina";
                    u.IdentifiantU = user.UserName;
                    u.EmailU       = user.Email;
                    u.TelU         = "781234567";
                    u.IdUser       = user.Id;
                    service.AddUtilisateur(u);

                    if (chkUser.Succeeded)
                    {
                        var result1 = UserManager.AddToRole(user.Id, "Sécrétaire");
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }