private void InitDefaultUsersAndRoles(UserManager<QuestionsAnswersUser> userManager,
			RoleManager<IdentityRole> roleManager)
		{
			if (roleManager.FindByName("admin") == null)
			{
				roleManager.Create(new IdentityRole("admin"));
			}

			if (roleManager.FindByName("user") == null)
			{
				roleManager.Create(new IdentityRole("user"));
			}

			if (userManager.FindByName("admin") == null)
			{
				var user = new QuestionsAnswersUser {UserName = "******"};
				var result = userManager.Create(user, "adminadmin");
				if (result.Succeeded)
				{
					userManager.AddToRole(user.Id, "admin");
				}
			}

			userManager.Users.Where(u => !u.Roles.Any()).ToList().ForEach(u => userManager.AddToRole(u.Id, "user"));
		}
Пример #2
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();
        }
Пример #3
0
        internal static void SeedModerator(TechSupportDbContext context)
        {
            const string moderatorEmail = "*****@*****.**";
            const string mderatorPassword = "******";

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

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

            var admin = new User
            {
                FirstName = "Gosho",
                LastName = "Moderatora",
                Email = moderatorEmail,
                Address = "Sopot",
                UserName = moderatorEmail
            };

            userManager.Create(admin, mderatorPassword);

            userManager.AddToRole(admin.Id, GlobalConstants.ModeratorRole);
            userManager.AddToRole(admin.Id, GlobalConstants.DefaultRole);

            context.SaveChanges();
        }
Пример #4
0
        internal static void SeedAdmin(TechSupportDbContext 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 = "Pesho",
                LastName = "Admina",
                Email = AdminEmail,
                Address = "Sopot",
                UserName = AdminEmail
            };

            userManager.Create(admin, AdminPassword);
            userManager.AddToRole(admin.Id, GlobalConstants.AdminRole);
            userManager.AddToRole(admin.Id, GlobalConstants.ModeratorRole);
            userManager.AddToRole(admin.Id, GlobalConstants.DefaultRole);

            context.SaveChanges();
        }
Пример #5
0
        private void AddPermisionToADM(ApplicationDbContext db)
        {
            var userManarge = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
            var user = userManarge.FindByName("*****@*****.**");

            if (!userManarge.IsInRole(user.Id, "View"))
            {
                userManarge.AddToRole(user.Id, "View");
            }
            if (!userManarge.IsInRole(user.Id, "Create"))
            {
                userManarge.AddToRole(user.Id, "Create");
            }
            if (!userManarge.IsInRole(user.Id, "Edit"))
            {
                userManarge.AddToRole(user.Id, "Edit");
            }
            if (!userManarge.IsInRole(user.Id, "Delete"))
            {
                userManarge.AddToRole(user.Id, "Delete");
            }
            if (!userManarge.IsInRole(user.Id, "Adm"))
            {
                userManarge.AddToRole(user.Id, "Adm");
            }
        }
    /// <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");
        }
    }
Пример #7
0
        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();
        }
Пример #8
0
        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();
        }
Пример #9
0
        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
        }
Пример #10
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("*****@*****.**");
        }
Пример #11
0
        //Método para quemar el super usuario del sistema:
        private void CheckSuperUser()
        {
            //me conecto all db:
            var userContext = new ApplicationDbContext();
            //Aqui controlo los usuarios:
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
            var db = new DemocracyContext();
            this.CheckRole("Admin", userContext);
            this.CheckRole("User", userContext);

            //validar si el usuario existe en la tabla user:
            var user = db.Users.Where(u=>u.userName.ToLower().Equals("*****@*****.**")).FirstOrDefault();

            if (user == null)
            {
                //creamos nuestro usuario Administrador:
                user = new User
                {
                    Address = "Calle Madrid 55",
                    FirstName = "Emilio",
                    LastName = "Barrera",
                    Phone = "693661995",
                    userName = "******",
                    Photo = "~/Content/Photos/fondo.jpg"
                };

                db.Users.Add(user);
                db.SaveChanges();
            }

            //valido si el uusarip existe en las tablas de the ASP NET User:
            var userASP = userManager.FindByName(user.userName);

            if (userASP == null)
            {
                userASP = new ApplicationUser
                {
                  UserName = user.userName,
                  Email = user.userName,
                  PhoneNumber = user.Phone                
                 
                };

                userManager.Create(userASP, "Eabs+++++55555");
                userManager.AddToRole(userASP.Id, "Admin");
            }

            userManager.AddToRole(userASP.Id, "Admin");
        }
Пример #12
0
 internal bool UpdateUser(string username, string realUsername, string permission)
 {
     IdentityResult result = null;
     Models.ApplicationDbContext context = new Models.ApplicationDbContext();
     var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
     var user = userMgr.FindByName(username);
     if (!string.IsNullOrEmpty(realUsername))
     {
         user.RealUserName = realUsername;
         result = userMgr.Update(user);
     }
     if (!string.IsNullOrEmpty(permission) && !userMgr.IsInRole(user.Id, permission))
     {
         userMgr.RemoveFromRoles(user.Id, "read", "edit", "administrator");
         switch (permission)
         {
             case "administrator":
                 result = userMgr.AddToRole(user.Id, "administrator");
                 break;
             case "edit":
                 result = userMgr.AddToRole(user.Id, "edit");
                 break;
             default:
                 result = userMgr.AddToRole(user.Id, "read");
                 break;
         }
     }
     if (result == IdentityResult.Success) return true; else return false;
 }
Пример #13
0
        internal void AddUserAndRole()
        {
            // access the application context and create result variables.
            Models.ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

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

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

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

            // If the new admin user was successfully created, add the new user to the "admin" role.
            if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "admin"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "admin");
            }
        }
        public static void SeedRoles()
        {
            var context = new ApplicationDbContext();
            if (!context.Roles.Any())
            {
                if (!context.Roles.Any())
                {
                    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

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

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

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

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


                    var createResult = userManager.Create(user, "123456");
                    if (!createResult.Succeeded)
                    {
                        throw new Exception(string.Join("; ", createResult.Errors));
                    }
                    userManager.AddToRole(user.Id, "admin");
                    context.SaveChanges();
                }
            }
        }
Пример #15
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");
            }
        }
        public ActionResult Create(ClientViewModel client)
        {
            if (!ModelState.IsValid) return View();

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

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

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

            return RedirectToAction("Index", "Home");
        }
Пример #17
0
        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);
        }
Пример #18
0
        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");
                }
            }
        }
Пример #19
0
        private static void seedUserRoles(string Admin, string User, ApplicationDbContext db)
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

            manager.AddToRoles(Admin, Roles.ADMIN);
            manager.AddToRole(User, Roles.USER);
        }
Пример #20
0
 public bool AddUserToRole(string userId, string roleName)
 {
     var um = new UserManager<ApplicationUser>(
         new UserStore<ApplicationUser>(new SubHubContext()));
     var idResult = um.AddToRole(userId, roleName);
     return idResult.Succeeded;
 }
Пример #21
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;
        }
        
    }
Пример #22
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();
            }
        }
Пример #23
0
        public void ListViewUsers_UpdateItem(string Id, string commandArgument)
        {
            var item = this.UsersService.GetById(Id);

            if (item == null)
            {
                var errorMessage = $"User with id {this.ID} was not found";
                Notificator.AddErrorMessage(errorMessage);

                this.ModelState.AddModelError("", errorMessage);
                return;
            }
            
            var isAdmin = ((CheckBox)ListViewAllUsers.Items[ListViewAllUsers.EditIndex].FindControl("CbIsADmin")).Checked;

            // TODO: extract in separate class or service
            var userManager = new UserManager<User>(new UserStore<User>(new XShareDbContext()));

            if (isAdmin)
            {
                userManager.AddToRole(item.Id, "admin");
            }
            else
            {
                userManager.RemoveFromRole(item.Id, "admin");
            }

            this.TryUpdateModel(item);
            if (this.ModelState.IsValid)
            {
                this.UsersService.UpdateUser(item);
                Notificator.AddInfoMessage($"You've just updated the info for user {item.UserName}");
            }
        }
Пример #24
0
        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();
                }
            }
        }
Пример #25
0
        public static void Start()
        {
            using (var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new UsersDbContext())))
            {
                foreach (var roleName in RolesList.Where(roleName => !roleManager.RoleExists(roleName)))
                {
                    roleManager.Create(new IdentityRole(roleName));
                }
            }
            using (
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new UsersDbContext()))
                )
            {
                if (userManager.FindByName(Constants.AdminUserName) != null)
                {
                    return;
                }

                var admin = new ApplicationUser {UserName = Constants.AdminUserName};
                var result = userManager.Create(admin, "AdminPass");
                if (!result.Succeeded)
                {
                    var txt = new StringBuilder();

                    foreach (var error in result.Errors)
                    {
                        txt.AppendLine(error);
                    }
                    throw new Exception(txt.ToString());
                }

                userManager.AddToRole(admin.Id, Constants.Roles.Admin);
            }
        }
Пример #26
0
        public static void AddUserRole(string userName, string roleName)
        {
            using (var context = new ApplicationDbContext())
            {
                try
                {
                    if (!context.Roles.Any(r => r.Name == roleName)) return;

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

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

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

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

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

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

                    throw;
                }
            }
        }
Пример #27
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 = "******",
                ImgUrl = "user2-160x160.jpg",
                Description = "High Level",
                SinceDate = new DateTime(2016, 1, 1)
            };

            IdUserResult = userMgr.Create(appUser, "1qaz2wsxE");
            var user = userMgr.FindByName("administrator");
            if (!userMgr.IsInRole(user.Id, "administrator"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByName("administrator").Id, "administrator");
            }
        }
        public 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));
        }
Пример #29
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;
            }
        }
        /*This should be removed after the first admin gets made */
        // GET: MakeMeAdmin/Create
        public ActionResult Create(string email)
        {
            using (var context = new ApplicationDbContext())
            {
                var fadmin = context.KeyValueSettings.FirstOrDefault(s => s.Key == "FirstAdminSet");
                if (fadmin == null || fadmin.Value == "false")
                {
                    var roleStore = new RoleStore<IdentityRole>(context);
                    var roleManager = new RoleManager<IdentityRole>(roleStore);

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

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

                    var user = userManager.FindByEmail(email);
                    userManager.AddToRole(user.Id, "Admin");
                    if (fadmin == null)
                    {
                        context.KeyValueSettings.Add(new KeyValueSettings() { Key = "FirstAdminSet", Value = "true" });
                    }
                    else
                    {
                        fadmin.Value = "true";
                    }
                    context.SaveChanges();
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            return Json(false, JsonRequestBehavior.AllowGet);
        }
Пример #31
0
        protected override void Seed(CarDealership.Models.CarDealershipDBContext context)
        {
            var userMgr = new UserManager <AppUser>(new UserStore <AppUser>(context));
            var roleMgr = new RoleManager <AppRole>(new RoleStore <AppRole>(context));

            if (!roleMgr.RoleExists("sales"))
            {
                roleMgr.Create(new AppRole()
                {
                    Name = "sales"
                });
            }

            if (!userMgr.Users.Any(u => u.UserName == "sales"))
            {
                var user = new AppUser()
                {
                    UserName = "******"
                };
                userMgr.Create(user, "testing123");
                userMgr.AddToRole(user.Id, "sales");
            }

            if (!roleMgr.RoleExists("admin"))
            {
                roleMgr.Create(new AppRole()
                {
                    Name = "admin"
                });
            }

            if (!userMgr.Users.Any(u => u.UserName == "admin"))
            {
                var user = new AppUser()
                {
                    UserName = "******"
                };
                userMgr.Create(user, "testing123");
                userMgr.AddToRole(user.Id, "admin");
            }

            context.Employees.AddOrUpdate(e => e.Email,
                                          new Employee
            {
                FirstName  = "Joe",
                LastName   = "Miller",
                EmployeeID = 1,
                Email      = "*****@*****.**",
                Phone      = "222-222-2222",
                Street1    = "1234 Main Street",
                City       = "Minneapolis",
                State      = "MN",
                PostalCode = "55121",
                Role       = "Sales"
            });
            context.SaveChanges();

            context.BodyTypes.AddOrUpdate(b => b.BodyTypeName,
                                          new BodyType
            {
                BodyTypeID   = 1,
                BodyTypeName = "Two-Door Car"
            },
                                          new BodyType
            {
                BodyTypeID   = 2,
                BodyTypeName = "Four-Door Car"
            },
                                          new BodyType
            {
                BodyTypeID   = 3,
                BodyTypeName = "Sports-Utility Vehicle"
            },
                                          new BodyType
            {
                BodyTypeID   = 4,
                BodyTypeName = "Pickup"
            },
                                          new BodyType
            {
                BodyTypeID   = 5,
                BodyTypeName = "Crossover"
            });
            context.SaveChanges();

            context.Makes.AddOrUpdate(m => m.MakeName,
                                      new Make
            {
                MakeID    = 1,
                MakeName  = "Mazda",
                AddedDate = DateTime.Parse("11/07/2017"),
                AddedBy   = "admin"
            },
                                      new Make
            {
                MakeID    = 2,
                MakeName  = "Toyota",
                AddedDate = DateTime.Parse("11/07/2017"),
                AddedBy   = "admin"
            },
                                      new Make
            {
                MakeID    = 3,
                MakeName  = "Chevy",
                AddedDate = DateTime.Parse("11/07/2017"),
                AddedBy   = "admin"
            },
                                      new Make
            {
                MakeID    = 4,
                MakeName  = "BMW",
                AddedDate = DateTime.Parse("11/07/2017"),
                AddedBy   = "admin"
            },
                                      new Make
            {
                MakeID    = 5,
                MakeName  = "Ford",
                AddedDate = DateTime.Parse("11/07/2017"),
                AddedBy   = "admin"
            });
            context.SaveChanges();

            context.CarModels.AddOrUpdate(cm => cm.ModelName,
                                          new CarModel
            {
                CarModelID = 1,
                ModelName  = "3",
                AddedDate  = DateTime.Parse("11/07/2017"),
                AddedBy    = "Admin",
                Make       = "Mazda"
            },
                                          new CarModel
            {
                CarModelID = 2,
                ModelName  = "Corolla",
                AddedDate  = DateTime.Parse("11/07/2017"),
                AddedBy    = "Admin",
                Make       = "Toyota"
            },
                                          new CarModel
            {
                CarModelID = 3,
                ModelName  = "Silverado",
                AddedDate  = DateTime.Parse("11/07/2017"),
                AddedBy    = "Admin",
                Make       = "Chevy"
            },
                                          new CarModel
            {
                CarModelID = 4,
                ModelName  = "550S",
                AddedDate  = DateTime.Parse("11/07/2017"),
                AddedBy    = "Admin",
                Make       = "BMW"
            },
                                          new CarModel
            {
                CarModelID = 5,
                ModelName  = "Focus",
                AddedDate  = DateTime.Parse("11/07/2017"),
                AddedBy    = "Admin",
                Make       = "Ford"
            });
            context.SaveChanges();

            context.PurchaseTypes.AddOrUpdate(p => p.PurchaseTypeName,
                                              new PurchaseType
            {
                PurchaseTypeID   = 1,
                PurchaseTypeName = "Dealer Finance",
            },
                                              new PurchaseType
            {
                PurchaseTypeID   = 2,
                PurchaseTypeName = "Credit",
            },
                                              new PurchaseType
            {
                PurchaseTypeID   = 3,
                PurchaseTypeName = "Cash",
            });

            context.Vehicles.AddOrUpdate(v => v.Description,
                                         new Vehicle
            {
                VehicleID   = 1,
                Color       = "Meteorite Grey",
                Description = "Fancy new Mazda 3",
                Interior    = "Leather",
                IsAvailable = false,
                IsFeatured  = false,
                IsNew       = true,
                Mileage     = 520,
                CarBody     = context.BodyTypes.Where(b => b.BodyTypeName == "Four-Door Car").FirstOrDefault(),
                CarMake     = context.Makes.Where(m => m.MakeName == "Mazda").FirstOrDefault(),
                CarModel    = context.CarModels.Where(m => m.ModelName == "3").FirstOrDefault(),
                MSRP        = 20000M,
                SalePrice   = 16000M,
                IsAutomatic = false,
                VinNumber   = "4T3ZF13C12U459747",
                Year        = 2016,
            },
                                         new Vehicle
            {
                VehicleID   = 2,
                Color       = "Red",
                Description = "This is a two-door Toyota Corolla",
                Interior    = "Cloth",
                IsAvailable = true,
                IsFeatured  = true,
                IsNew       = true,
                Mileage     = 300,
                CarModel    = context.CarModels.Where(m => m.ModelName == "Corolla").FirstOrDefault(),
                CarMake     = context.Makes.Where(m => m.MakeName == "Toyota").FirstOrDefault(),
                MSRP        = 16000M,
                SalePrice   = 16000M,
                IsAutomatic = false,
                VinNumber   = "1FAFP53222G297529",
                Year        = 2015,
                CarBody     = context.BodyTypes.Where(b => b.BodyTypeName == "Two-Door Car").FirstOrDefault(),
            },
                                         new Vehicle
            {
                VehicleID   = 3,
                Color       = "Black",
                Description = "This is a car",
                Interior    = "Leather",
                IsAvailable = true,
                IsFeatured  = true,
                IsNew       = true,
                Mileage     = 520,
                CarMake     = context.Makes.Where(m => m.MakeName == "BMW").FirstOrDefault(),
                CarModel    = context.CarModels.Where(m => m.ModelName == "550S").FirstOrDefault(),
                MSRP        = 20000M,
                SalePrice   = 16000M,
                IsAutomatic = false,
                VinNumber   = "ZFF65THA9D0186686",
                Year        = 2017,
                CarBody     = context.BodyTypes.Where(b => b.BodyTypeName == "Two-Door Car").FirstOrDefault(),
            },
                                         new Vehicle
            {
                VehicleID   = 4,
                Color       = "Electric Blue",
                Description = "this is car here",
                Interior    = "Cloth",
                IsAvailable = true,
                IsFeatured  = false,
                IsNew       = false,
                Mileage     = 20000,
                CarMake     = context.Makes.Where(m => m.MakeName == "Ford").FirstOrDefault(),
                CarModel    = context.CarModels.Where(m => m.ModelName == "Focus").FirstOrDefault(),
                MSRP        = 20000M,
                SalePrice   = 16000M,
                IsAutomatic = true,
                VinNumber   = "4T3ZF13C12U459747",
                Year        = 2017,
                CarBody     = context.BodyTypes.Where(b => b.BodyTypeName == "Two-Door Car").FirstOrDefault(),
            },
                                         new Vehicle
            {
                VehicleID   = 5,
                Color       = "Black",
                Description = "This is a sweet new truck",
                Interior    = "Cloth",
                IsAvailable = true,
                IsFeatured  = true,
                IsNew       = true,
                Mileage     = 500,
                CarMake     = context.Makes.Where(m => m.MakeName == "Chevy").FirstOrDefault(),
                CarModel    = context.CarModels.Where(m => m.ModelName == "Silverado").FirstOrDefault(),
                MSRP        = 50000M,
                SalePrice   = 45000,
                IsAutomatic = false,
                VinNumber   = "JA4NW61S23J021156",
                Year        = 2017,
                CarBody     = context.BodyTypes.Where(b => b.BodyTypeName == "Pickup").FirstOrDefault(),
            },
                                         new Vehicle
            {
                VehicleID   = 6,
                Color       = "Canary Yellow",
                Description = "This car is spectacular",
                Interior    = "Leather",
                IsAvailable = true,
                IsFeatured  = true,
                IsNew       = true,
                Mileage     = 12,
                CarMake     = context.Makes.Where(m => m.MakeName == "Mazda").FirstOrDefault(),
                CarModel    = context.CarModels.Where(m => m.ModelName == "3").FirstOrDefault(),
                MSRP        = 50000M,
                SalePrice   = 50000M,
                IsAutomatic = true,
                VinNumber   = "1HGCR2F32DA718943",
                Year        = 2017,
                CarBody     = context.BodyTypes.Where(b => b.BodyTypeName == "Four-Door Car").FirstOrDefault(),
            });

            context.Contacts.AddOrUpdate(c => c.Email,
                                         new ContactUs
            {
                ContactUsID = 1,
                FirstName   = "Jake",
                LastName    = "Ganser",
                Email       = "*****@*****.**",
                Phone       = "763-242-5080",
                Message     = "I would like to talk with a sales person to learn more about this vehicle",
                Date        = DateTime.Parse("11/9/2017")
            },
                                         new ContactUs
            {
                ContactUsID = 2,
                FirstName   = "Ashley",
                LastName    = "Weber",
                Email       = "*****@*****.**",
                Phone       = "763-242-2344",
                Message     = "Do you have this vehicle with leather seats?",
                Date        = DateTime.Parse("11/9/2017")
            });

            context.Customers.AddOrUpdate(c => c.Email,
                                          new Customer
            {
                CustomerID = 1,
                FirstName  = "Bill",
                LastName   = "Johnson",
                Email      = "*****@*****.**",
                Phone      = "111-111-1111",
                City       = "Anoka",
                State      = "MN",
                Street1    = "7750 149th Ave",
                PostalCode = "55303",
            });

            context.Purchases.AddOrUpdate(p => p.PurchasePrice,
                                          new Purchase
            {
                PurchaseID    = 1,
                PurchaseDate  = DateTime.Parse("11/4/17"),
                PurchasePrice = 16000M,
                APurchaseType = context.PurchaseTypes.Where(p => p.PurchaseTypeID == 1).FirstOrDefault(),
                VinNumber     = "4T3ZF13C12U459747",
                ACustomer     = context.Customers.Where(c => c.CustomerID == 1).FirstOrDefault(),
            });

            context.Specials.AddOrUpdate(s => s.SpecialName,
                                         new Special
            {
                SpecialID   = 1,
                SpecialName = "Truck Month!!",
                Description = "Take $1,500 off the sales price of all new trucks in the month of November!",
                value       = 1500,
                BeginDate   = DateTime.Parse("11/01/2017"),
                EndDate     = DateTime.Parse("11/30/2017"),
                Vehicles    = context.Vehicles.Where(v => v.CarBody.BodyTypeID == 4).Where(v => v.IsNew == true).ToList()
            });
        }
        private async Task BuildForInternalAsync(Tenant tenant)
        {
            //Create Organization Units

            var organizationUnits = new List <OrganizationUnit>();

            var producing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Producing");

            var researchAndDevelopment = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Research & Development", producing);

            var ivrProducts = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "IVR Related Products", researchAndDevelopment);

            var voiceTech = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Voice Technologies", researchAndDevelopment);

            var inhouseProjects = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Inhouse Projects", researchAndDevelopment);

            var qualityManagement = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Quality Management", producing);

            var testing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Testing", producing);

            var selling = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Selling");

            var marketing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Marketing", selling);

            var sales = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Sales", selling);

            var custRelations = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Customer Relations", selling);

            var supporting = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Supporting");

            var buying = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Buying", supporting);

            var humanResources = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Human Resources", supporting);

            //Create users

            var users = _randomUserGenerator.GetRandomUsers(RandomHelper.GetRandom(12, 26), tenant.Id);

            foreach (var user in users)
            {
                //Create the user
                await _userManager.CreateAsync(user);

                await CurrentUnitOfWork.SaveChangesAsync();

                //Add to roles
                _userManager.AddToRole(user.Id, StaticRoleNames.Tenants.User);

                //Add to OUs
                var randomOus = RandomHelper.GenerateRandomizedList(organizationUnits).Take(RandomHelper.GetRandom(0, 3));
                foreach (var ou in randomOus)
                {
                    await _userManager.AddToOrganizationUnitAsync(user, ou);
                }

                //Set profile picture
                if (RandomHelper.GetRandom(100) < 70) //A user will have a profile picture in 70% probability.
                {
                    await SetRandomProfilePictureAsync(user);
                }
            }

            //Set a picture to admin!
            var admin = _userManager.FindByName(User.AdminUserName);

            await SetRandomProfilePictureAsync(admin);

            //Create Friendships
            var friends = RandomHelper.GenerateRandomizedList(users).Take(3).ToList();

            foreach (var friend in friends)
            {
                _friendshipManager.CreateFriendship(
                    new Friendship(
                        admin.ToUserIdentifier(),
                        friend.ToUserIdentifier(),
                        tenant.TenancyName,
                        friend.UserName,
                        friend.ProfilePictureId,
                        FriendshipState.Accepted)
                    );

                _friendshipManager.CreateFriendship(
                    new Friendship(
                        friend.ToUserIdentifier(),
                        admin.ToUserIdentifier(),
                        tenant.TenancyName,
                        admin.UserName,
                        admin.ProfilePictureId,
                        FriendshipState.Accepted)
                    );
            }

            //Create chat message
            var friendWithMessage = RandomHelper.GenerateRandomizedList(friends).First();

            _chatMessageRepository.InsertAndGetId(
                new ChatMessage(
                    friendWithMessage.ToUserIdentifier(),
                    admin.ToUserIdentifier(),
                    ChatSide.Sender,
                    L("Demo_SampleChatMessage"),
                    ChatMessageReadState.Read
                    )
                );

            _chatMessageRepository.InsertAndGetId(
                new ChatMessage(
                    admin.ToUserIdentifier(),
                    friendWithMessage.ToUserIdentifier(),
                    ChatSide.Receiver,
                    L("Demo_SampleChatMessage"),
                    ChatMessageReadState.Unread
                    )
                );
        }
Пример #33
0
        protected override void Seed(AutomatedTellerMachine.Models.ApplicationDbContext context)
        {
            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!");

                var service = new CheckingAccountService(context);
                service.CreateCheckingAccount("admin", "user", user.Id, 1000);

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

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

            context.Transactions.Add(new Transaction {
                Amount = 300, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 301, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 302, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 303, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 304, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 300, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 301, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 302, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 303, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 304, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 300, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 301, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 302, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 303, CheckingAccountId = 4
            });
            context.Transactions.Add(new Transaction {
                Amount = 304, CheckingAccountId = 4
            });
            //  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.
        }
Пример #34
0
        protected override void Seed(BugTrackerVS_16.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 == "Submitter"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "Submitter"
                });
            }

            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"
                });
            }

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

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Johnthan",
                    LastName    = "Mcphaul",
                    DisplayName = "jmcphaul"
                }, "John2905");
            }

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

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

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "project",
                    LastName    = "manager",
                    DisplayName = "PM"
                }, "projectmanager");
            }


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

            userManager.AddToRole(userId, "Admin");

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

            userManager.AddToRole(userId1, "Submitter");

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

            userManager.AddToRole(userId2, "ProjectManager");

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

            userManager.AddToRole(userId3, "Developer");

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

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

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

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


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

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

            if (!context.TicketStatuses.Any(u => u.Name == "New"))
            {
                context.TicketStatuses.Add(new TicketStatuses {
                    Name = "New"
                });
            }
        }
Пример #35
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            string message = string.Empty;

            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    user = await UserManager.FindByNameAsync(model.Email);

                    #region (Adding To Role)
                    string selectedRoleName = RoleManager.FindById(model.SelectedUserRoleId).Name;
                    UserManager.AddToRole(user.Id, selectedRoleName);
                    #endregion
                    #region (Add Profile)
                    #region (Add Profile)
                    // await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    //DoctorService doctorService = new DoctorService();
                    //if (1==1)//(selectedRoleName == CustomRoles.Doctor)
                    //{
                    //    DoctorDTO doctor = new DoctorDTO();
                    //    doctor.FirstName = "";
                    //    doctor.LastName = "";
                    //    doctor.Description = "";
                    //    doctor.DOB = new DateTime(1900, 1, 1);
                    //    doctor.LicenseNumber = "";
                    //    doctor.StatusID_FK = 0;
                    //    doctor.User_FK_Id = user.Id;
                    //    var docId = doctorService.AddDoctor(doctor);
                    //}
                    #endregion
                    MemberProfileService memberProfileService = new MemberProfileService();
                    MemberProfileDTO     member = new MemberProfileDTO();
                    member.FirstName        = "";
                    member.LastName         = "";
                    member.HighestEducation = "";
                    member.HomeDistrict     = "";
                    member.MobilePhone      = "";
                    member.Experience       = 0;
                    member.DOB = new DateTime(1900, 1, 1);
                    member.FK_FROM_IdentityUser = user.Id;
                    memberProfileService.AddMember(member);
                    #endregion

                    #region (Sending Email)
                    var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action(
                        "ConfirmEmail", "Account",
                        new { userId = user.Id, code = code },
                        protocol: Request.Url.Scheme);

                    await UserManager.SendEmailAsync(user.Id,
                                                     "Confirm your account",
                                                     "Please confirm your account by clicking this link: <a href=\""
                                                     + callbackUrl + "\">link</a>");

                    //await UserManager.SendEmailAsync(20,
                    //    "New Doctor Registration",
                    //    "His Email is " + model.Email + ". Please confirm his account by clicking this link: <a href=\""
                    //                                    + callbackUrl + "\">link</a>   Go to <a href='https://amardoctors.com'>Amardoctors</a>");
                    #endregion

                    return(RedirectToAction("Confirm", "Account", new { Email = user.Email }));
                }

                foreach (var item in result.Errors)
                {
                    message += item + " || ";
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(RedirectToAction("Register", new { message = message }));
        }
Пример #36
0
        protected override void Seed(ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
            //var hasher = new PasswordHasher();
            //context.Users.AddOrUpdate(u => u.UserName, new ApplicationUser
            //{
            //    UserName = "******",
            //    PasswordHash = hasher.HashPassword("appelmoes")
            //});
            //if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            //{
            //    var userStore = new UserStore<ApplicationUser>(context);
            //    var userManager = new UserManager<ApplicationUser>(userStore);

            //    var roleStore= new RoleStore<IdentityRole>(context);
            //    var roleManager = new RoleManager<IdentityRole>(roleStore);
            //    var user = new ApplicationUser{UserName = "******"};
            //    userManager.Create(user, "appelmoes");

            //    var role = new IdentityRole{ Name = "Managment"};
            //    roleManager.Create(role);

            //    userManager.AddToRole(user.Id,"Managment");

            //}

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

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

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

            ApplicationUser user;

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

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

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

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Admin0");
                userManager.AddToRole(user.Id, "Admin");
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Leraar1");
                userManager.AddToRole(user.Id, "Leraar");
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Leraar2");
                userManager.AddToRole(user.Id, "Leraar");
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Leraar3");
                userManager.AddToRole(user.Id, "Leraar");
            }
            if (!context.Users.Any(u => u.UserName == "Student1"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Student1");
                userManager.AddToRole(user.Id, "Student");
            }
            if (!context.Users.Any(u => u.UserName == "Student2"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Student2");
                userManager.AddToRole(user.Id, "Student");
            }
            if (!context.Users.Any(u => u.UserName == "Student3"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Student3");
                userManager.AddToRole(user.Id, "Student");
            }
            if (!context.Users.Any(u => u.UserName == "Student1"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Student4");
                userManager.AddToRole(user.Id, "Student");
            }
        }
Пример #37
0
        protected override void Seed(BugTrackerV2.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

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

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

                manager.Create(role);
            }

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

                manager.Create(role);
            }

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

                manager.Create(role);
            }

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

                manager.Create(role);
            }

            if (!context.Users.Any(u => u.UserName == "Admin"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******", FirstName = "Jon", LastName = "Schmidt"
                };

                manager.Create(user, ConfigurationManager.AppSettings["DemoPassword"]);
                manager.AddToRole(user.Id, "Admin");
            }

            if (!context.Users.Any(u => u.UserName == "Manager"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******", FirstName = "Jane", LastName = "Scott"
                };

                manager.Create(user, ConfigurationManager.AppSettings["DemoPassword"]);
                manager.AddToRole(user.Id, "Manager");
            }

            if (!context.Users.Any(u => u.UserName == "Developer"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******", FirstName = "Frank", LastName = "Vance"
                };

                manager.Create(user, ConfigurationManager.AppSettings["DemoPassword"]);
                manager.AddToRole(user.Id, "Developer");
            }

            if (!context.Users.Any(u => u.UserName == "Submitter"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******", FirstName = "Raul", LastName = "Melendrez"
                };

                manager.Create(user, ConfigurationManager.AppSettings["DemoPassword"]);
                manager.AddToRole(user.Id, "Submitter");
            }
        }
Пример #38
0
        public ActionResult AddRole(string userID, FormCollection form)
        {
            var roleId = Request["RoleId"];

            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(db));
            var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));
            var users       = UserManager.Users.ToList();
            var user        = users.Find(u => u.Id == userID);

            var userView = new UserView
            {
                Email  = user.Email,
                Name   = user.UserName,
                UserId = user.Id
            };

            if (string.IsNullOrEmpty(roleId))
            {
                ViewBag.Error = "You must select a role";

                var list = roleManager.Roles.ToList();
                list.Add(new IdentityRole {
                    Id = "", Name = "[Select a role...]"
                });
                list           = list.OrderBy(r => r.Name).ToList();
                ViewBag.RoleId = new SelectList(list, "Id", "Name");

                return(View(userView));
            }

            var roles = roleManager.Roles.ToList();
            var role  = roles.Find(r => r.Id == roleId);

            if (!UserManager.IsInRole(userID, role.Name))
            {
                UserManager.AddToRole(userID, role.Name);
            }

            var rolesView = new List <RoleView>();

            if (user.Roles != null)
            {
                foreach (var item in user.Roles)
                {
                    role = roles.Find(r => r.Id == item.RoleId);
                    var roleView = new RoleView
                    {
                        RoleId = role.Id,
                        Name   = role.Name
                    };
                    rolesView.Add(roleView);
                }
            }
            else
            {
                return(HttpNotFound());
            }

            userView = new UserView
            {
                Email  = user.Email,
                Name   = user.UserName,
                UserId = user.Id,
                Roles  = rolesView
            };

            return(View("Roles", userView));
        }
Пример #39
0
        protected override void Seed(ManageSub.DAL.ManageSubContext context)
        {
            var roleManager = new RoleManager <RoleModels>(new RoleStore <RoleModels>(new ManageSubContext()));
            var roleresult  = roleManager.Create(new RoleModels("user"));
            var roleresult2 = roleManager.Create(new RoleModels("admin"));
            var tarifs      = new List <TarifModels>
            {
                new TarifModels {
                    Id = 400, prix = 10.0, type = "abonnement"
                },
                new TarifModels {
                    Id = 402, prix = 20.0, type = "abonnement"
                },
                new TarifModels {
                    Id = 403, prix = 1.70, type = "ticket"
                },
                new TarifModels {
                    Id = 404, prix = 1.40, type = "ticket"
                }
            };

            tarifs.ForEach(s => context.TarifModels.Add(s));

            var typeAbo = new List <TypeAbonnementModels>
            {
                new TypeAbonnementModels {
                    Id = 500, Intitule = "Etudiant", Conditon = "Posseder une carte étudiant", TarifModelsID = tarifs.First().Id
                },
                new TypeAbonnementModels {
                    Id = 501, Intitule = "Normal", Conditon = "Pas de condition", TarifModelsID = tarifs.Last().Id
                }
            };

            typeAbo.ForEach(s => context.TypeAbonnementModels.Add(s));



            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userStore     = new UserStore <IdentityModels>(context);
                var userManager   = new UserManager <IdentityModels>(userStore);
                var userToInsert2 = new IdentityModels {
                    UserName = "******", PhoneNumber = "0797697898", Email = "*****@*****.**", EmailConfirmed = true
                };
                userManager.Create(userToInsert2, "azerty");
                userManager.AddToRole(userToInsert2.Id, "user");

                var carte = new List <CarteModels>
                {
                    new CarteModels {
                        Id = 200, IdentityModels = userToInsert2, dateCreation = DateTime.Parse("2015-09-01")
                    }
                };
                carte.ForEach(s => context.CarteModels.Add(s));
                var ticketList = new List <TicketModels>
                {
                    new TicketModels {
                        Id = 700, CarteModelsID = carte.First().Id, TarifModelsID = tarifs.ElementAt(2).Id
                    }
                };
                ticketList.ForEach(s => context.TicketModels.Add(s));

                var abos = new List <AbonnementModels>
                {
                    new AbonnementModels {
                        AbonnementModelsId = 100, finDeValidite = DateTime.Now.AddYears(1), TypeAbonnementModelsID = typeAbo.First().Id, CarteModelsID = carte.First().Id
                    },
                    new AbonnementModels {
                        AbonnementModelsId = 101, finDeValidite = DateTime.Now.AddYears(1), TypeAbonnementModelsID = typeAbo.Last().Id, CarteModelsID = carte.First().Id
                    }
                };
                abos.ForEach(s => context.AbonnementModels.Add(s));
            }



            if (!(context.Users.Any(u => u.UserName == "admin")))
            {
                var userStore    = new UserStore <IdentityModels>(context);
                var userManager  = new UserManager <IdentityModels>(userStore);
                var userToInsert = new IdentityModels {
                    UserName = "******", PhoneNumber = "0897876565", Email = "*****@*****.**", EmailConfirmed = true
                };
                userManager.Create(userToInsert, "azerty");
                userManager.AddToRole(userToInsert.Id, "admin");

                var carte = new List <CarteModels>
                {
                    new CarteModels {
                        Id = 201, IdentityModels = userToInsert, dateCreation = DateTime.Parse("2015-09-24")
                    }
                };
                carte.ForEach(s => context.CarteModels.Add(s));
            }
            context.SaveChanges();
        }
Пример #40
0
        protected override void Seed(BlogFall.Models.ApplicationDbContext context)
        {
            var autoGenerateSlugs    = false;
            var autoGenerateSlugsAll = false;

            //tüm kullanýcýlarý aktif yapar.
            //foreach (var item in context.Users)
            //{
            //    item.IsEnabled = true;
            //}
            //return;
            #region Admin Rolünü ve Kullanýcýsýný Oluþtur

            if (!context.Roles.Any(r => r.Name == "Admin"))
            {
                var store   = new RoleStore <IdentityRole>(context); //
                var manager = new RoleManager <IdentityRole>(store); //Rolemanager rolleri yönetmekten sorumlu.
                var role    = new IdentityRole {
                    Name = "Admin"
                };

                manager.Create(role);
            }

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

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

                //Oluþturulan kullanýcýya ait yazýlar ekleyelim:
                #region Kategoriler ve Yazýlar

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

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

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

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

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

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

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

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

                    context.Categories.Add(cat1);
                    context.Categories.Add(cat2);
                }
                #endregion
            }
            #endregion
            #region Admin kullanýcýsýna 77 yeni yazý ekle

            if (!context.Categories.Any(x => x.CategoryName == "Diðer"))
            {
                ApplicationUser admin = context.Users
                                        .Where(x => x.UserName == "*****@*****.**")
                                        .FirstOrDefault();

                if (admin != null)
                {
                    if (!context.Categories.Any(x => x.CategoryName == "Diðer"))
                    {
                        Category diger = new Category
                        {
                            CategoryName = "Diðer",
                            Posts        = new HashSet <Post>()
                        };

                        for (int i = 1; i <= 77; i++)
                        {
                            diger.Posts.Add(new Post
                            {
                                Title        = "Diðer Yazý" + i,
                                AuthorId     = admin.Id,
                                Content      = @"<p>Tincidunt integer eu augue augue nunc elit dolor, luctus placerat scelerisque euismod, iaculis eu lacus nunc mi elit, vehicula ut laoreet ac, aliquam sit amet justo nunc tempor, metus vel.</p>
<p>Placerat suscipit, orci nisl iaculis eros, a tincidunt nisi odio eget lorem nulla condimentum tempor mattis ut vitae feugiat augue cras ut metus a risus iaculis scelerisque eu ac ante.</p>",
                                CreationTime = DateTime.Now.AddMinutes(i)
                            });
                        }
                        context.Categories.Add(diger);
                    }
                }
            }

            #endregion

            #region Mevcut kategori ve yazýlarýn Slug'larýný oluþtur
            if (autoGenerateSlugs)
            {
                foreach (var item in context.Categories)
                {
                    if (autoGenerateSlugsAll || string.IsNullOrEmpty(item.Slug))
                    {
                        item.Slug = UrlService.URLFriendly(item.CategoryName);
                    }
                }
                foreach (var item in context.Posts)
                {
                    if (autoGenerateSlugsAll || string.IsNullOrEmpty(item.Slug))
                    {
                        item.Slug = UrlService.URLFriendly(item.Title);
                    }
                }
            }
            #endregion
        }
Пример #41
0
        protected override void Seed(ApplicationDbContext context)
        {
            #region Role

            if (!context.Roles.Any(r => r.Name == "OWNER"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "OWNER"
                };
                manager.Create(role);
            }
            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);
            }

            #endregion

            #region User


            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******", FullName = "مصطفی بابایی", Email = "*****@*****.**", PhoneNumber = "09196226887", IsEnabled = true
                };
                manager.Create(user, "123456");
                manager.AddToRole(user.Id, "OWNER");
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******", FullName = "سید علی الحسینی", Email = "*****@*****.**", PhoneNumber = "09123275196", IsEnabled = true
                };
                manager.Create(user, "123456");
                manager.AddToRole(user.Id, "OWNER");
            }

            #endregion

            #region Menu

            if (!context.Menu.Any(r => r.Title == "Home"))
            {
                var menu = new Menu {
                    Title = "Home", Caption = "خانه", IsEnable = true, Link = "/Home/Index", ParentId = 0
                };
                using (ApplicationDbContext db = new ApplicationDbContext())
                {
                    db.Menu.Add(menu);
                    db.SaveChanges();
                }
            }

            if (!context.Menu.Any(r => r.Title == "About"))
            {
                var menu = new Menu {
                    Title = "About", Caption = "درباره ما", IsEnable = true, Link = "/Home/About", ParentId = 0
                };
                using (ApplicationDbContext db = new ApplicationDbContext())
                {
                    db.Menu.Add(menu);
                    db.SaveChanges();
                }
            }

            if (!context.Menu.Any(r => r.Title == "FAQ"))
            {
                var menu = new Menu {
                    Title = "FAQ", Caption = "سوالات متداول", IsEnable = true, Link = "/Faq/Index", ParentId = 0
                };
                using (ApplicationDbContext db = new ApplicationDbContext())
                {
                    db.Menu.Add(menu);
                    db.SaveChanges();
                }
            }

            if (!context.Menu.Any(r => r.Title == "Contact"))
            {
                var menu = new Menu {
                    Title = "Contact", Caption = "ارتباط با ما", IsEnable = true, Link = "/Home/Contact", ParentId = 0
                };
                using (ApplicationDbContext db = new ApplicationDbContext())
                {
                    db.Menu.Add(menu);
                    db.SaveChanges();
                }
            }

            #endregion
        }
Пример #42
0
        public static InvitationToken Create(DbContext db, String email, User inviter,
                                             Organization organization, List <String> roles, List <Region> regions)
        {
            var UserStore   = new CUserStore <User>(db);
            var UserManager = new UserManager <User>(UserStore);
            var RoleManager = new RoleManager <Role>(new CRoleStore <Role>(db));


            InvitationToken result = new InvitationToken();

            while (result.Token == null)
            {
                var token  = GenerateToken();
                var exists = db.Set <InvitationToken>().Any(i => i.Token == token);
                if (!exists)
                {
                    result.Token = token;
                }
            }
            User user = new User();

            user.Email            = email;
            user.UserName         = email;
            user.fkOrganizationId = organization.Id;
            user.Id           = Guid.NewGuid().ToString();
            user.Organization = organization;

            var userRes = UserManager.Create(user);

            if (!userRes.Succeeded)
            {
                throw new ApplicationException(userRes.Errors.First());
            }

            result.User        = user;
            result.fkInviterId = inviter.Id;
            result.fkUserId    = user.Id;
            db.Set <InvitationToken>().Add(result);
            db.SaveChanges();

            result.Inviter = inviter;
            result.User    = user;

            foreach (var role in roles)
            {
                var res = UserManager.AddToRole(user.Id, role);
                Console.WriteLine(res);
            }
            foreach (var region in regions)
            {
                var scope = new UserScope
                {
                    fkUserId   = user.Id,
                    fkRegionId = region.Id
                };
                db.Set <UserScope>().Add(scope);
            }
            db.SaveChanges();

            return(result);
        }
Пример #43
0
        private void CreateRolesAndUsers()
        {
            ApplicationDbContext             identityDbContext          = new ApplicationDbContext();
            PatientManagementSystemDBContext patientManagementDbContext = new PatientManagementSystemDBContext();
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(identityDbContext));
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(identityDbContext));

            // creating a default admin role and user
            if (!roleManager.RoleExists("Admin"))
            {
                setupComplete = false;
                // create admin role
                var role = new IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);

                // Create admin super user
                var user = new ApplicationUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";

                string password = "******";
                var    chkUser  = userManager.Create(user, password);

                if (chkUser.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Admin");
                    // Seed admin data
                    SeedAdmin(user, patientManagementDbContext);
                }
            }

            // Create doctor role
            if (!roleManager.RoleExists("Doctor"))
            {
                var role = new IdentityRole();
                role.Name = "Doctor";
                roleManager.Create(role);

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

                string password = "******";

                var chkUser = userManager.Create(user, password);
                if (chkUser.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Doctor");
                    // seed doctor data
                    SeedDoctor(user, patientManagementDbContext);
                }
            }

            // Create patient role
            if (!roleManager.RoleExists("Patient"))
            {
                var role = new IdentityRole();
                role.Name = "Patient";
                roleManager.Create(role);

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

                string password = "******";

                var chkUser = userManager.Create(user, password);
                if (chkUser.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Patient");
                    // seed doctor data
                    SeedPatient(user, patientManagementDbContext);
                }
            }
        }
Пример #44
0
        protected override void Seed(WebContext context)
        {
            if (!(context.Roles.Any(x => x.Name == "ADMIN")))
            {
                context.Roles.Add(new IdentityRole()
                {
                    Name = "ADMIN"
                });
            }

            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userStore    = new UserStore <ApplicationUser>(context);
                var userManager  = new UserManager <ApplicationUser>(userStore);
                var userToInsert = new ApplicationUser
                {
                    FirstName = "£ukasz",
                    LastName  = "Zapa³a",
                    Address   = "Poland",
                    Email     = "*****@*****.**",
                    UserName  = "******"
                };
                userManager.Create(userToInsert, "Password@123");
                userManager.AddToRole(context.Users.FirstOrDefault(x => x.UserName == userToInsert.UserName).Id, "ADMIN");
            }

            var 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, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
            var imageSource = @"http://cdn3.saveritemedical.com/product-default.jpg";

            context.Products.AddOrUpdate(
                p => p.Id,
                // Beers
                new Product {
                Name = "Piwo £om¿a 500 ml", Category = "Piwo", Price = 2.58M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Piwo Tyskie 500 ml", Category = "Piwo", Price = 3.23M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Piwo ¯ywiec 500 ml", Category = "Piwo", Price = 3.34M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Piwo Kormoran Porter Warmiñski 500 ml", Category = "Piwo", Price = 8.49M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Piwo W¹socz 500 ml", Category = "Piwo", Price = 9.79M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Piwo Pilsner Urquell 500 ml", Category = "Piwo", Price = 5.99M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Piwo Pinta 500 ml", Category = "Piwo", Price = 7.99M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Piwo Reden 500 ml", Category = "Piwo", Price = 7.39M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Piwo Per³a 500 ml", Category = "Piwo", Price = .05M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Piwo Mi³os³aw 500 ml", Category = "Piwo", Price = 3.14M, Stock = 100, Description = description, ImagePath = imageSource
            },
                // Wine
                new Product {
                Name = "Wino Commandaria 750 ml", Category = "Wino", Price = 79.99M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Wino Grooteberg 750 ml", Category = "Wino", Price = 17.09M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Wino Marani 750 ml", Category = "Wino", Price = 26.39M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Wino Callia Alta 750 ml", Category = "Wino", Price = 79.99M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Wino Pure 750 ml", Category = "Wino", Price = 20.29M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Wino Lambrusco 750 ml", Category = "Wino", Price = 15.69M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Wino DE BORTOLI 750 ml", Category = "Wino", Price = 33.99M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Wino Emilie Durand 750 ml", Category = "Wino", Price = 62.99M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Wino Fresco 750 ml", Category = "Wino", Price = 11.99M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Wino Relumbron 750 ml", Category = "Wino", Price = 20.29M, Stock = 100, Description = description, ImagePath = imageSource
            },
                // Whisky
                new Product {
                Name = "Whisky Chivas Regal 700 ml", Category = "Whisky", Price = 248.00M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Whisky Ballantine's 700 ml", Category = "Whisky", Price = 119.00M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Whisky Bushmills 700 ml", Category = "Whisky", Price = 92.09M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Whisky Four Roses700 ml", Category = "Whisky", Price = 128.29M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Whisky Black Jack 700 ml", Category = "Whisky", Price = 59.99M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Whisky Grants 700 ml", Category = "Whisky", Price = 119.99M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Whisky Johnnie Walker 700 ml", Category = "Whisky", Price = 157.59M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Whisky Jim Beam 700 ml", Category = "Whisky", Price = 49.69M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Whisky Wild Turkey 700 ml", Category = "Whisky", Price = 94.59M, Stock = 100, Description = description, ImagePath = imageSource
            },
                new Product {
                Name = "Whisky Tullamore 700 ml", Category = "Whisky", Price = 154.59M, Stock = 100, Description = description, ImagePath = imageSource
            }
                );
        }
Пример #45
0
        protected override void Seed(IdentityDataContext context)
        {
            if (!context.Roles.Any(i => i.Name == "admin"))
            {
                var store   = new RoleStore <ApplicationRole>(context);
                var manager = new RoleManager <ApplicationRole>(store);

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

                manager.Create(role);
            }

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

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

                manager.Create(role);
            }

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

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

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

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

                var user = new ApplicationUser()
                {
                    Name     = "Gökhan",
                    Surname  = "Bulut",
                    UserName = "******",
                    Email    = "*****@*****.**"
                };

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

            base.Seed(context);
        }
Пример #46
0
        protected override void Seed(BugTracker.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
            //   context.Roles.Add(new IdentityRole { Name = "Admin" });
            if (!context.Roles.Any(r => r.Name == "Admin"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "Admin"
                };

                manager.Create(role);
            }

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

                manager.Create(role);
            }


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

                manager.Create(role);
            }


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

                manager.Create(role);
            }

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

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

            userManager.AddToRole(userIdSatya, "Admin");
            userManager.AddToRole(userIdSatya, "Developer");
            userManager.AddToRole(userIdSatya, "Project Manager");



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

            userManager.AddToRole(userIdAvatar, "Developer");
            //Users for Project Apollow 13

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Jim",
                    LastName    = "Lovell",
                    DisplayName = "Jim Lovell",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdJim = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdJim, "Developer");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Jack",
                    LastName    = "Swigert",
                    DisplayName = "Jack Swigert",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdJack = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdJack, "Submitter");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Fred",
                    LastName    = "Haise",
                    DisplayName = "Fred Haise",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdFred = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdFred, "Developer");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Gene",
                    LastName    = "Krantz",
                    DisplayName = "Gene Krantz",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdKranz = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdKranz, "Project Manager");


            // ********   Users for Project Seinfeld

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

            userManager.AddToRole(userIdJerry, "Project Manager");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Michael",
                    LastName    = "Richards",
                    DisplayName = "Michael Richards",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdKramer = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdKramer, "Admin");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Jason",
                    LastName    = "Alexander",
                    DisplayName = "Jason Alexander",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdGeorge = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdGeorge, "Developer");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Julia",
                    LastName    = "Dreyfus",
                    DisplayName = "Julia Dreyfus",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdElane = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdElane, "Project Manager");


            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Lary",
                    LastName    = "David",
                    DisplayName = "Lary David",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdLarry = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdLarry, "Admin");


            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Wayne",
                    LastName    = "Knight",
                    DisplayName = "Newman",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdNewman = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdNewman, "Submitter");


            // *********  Project Skunk Works

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Ben",
                    LastName    = "Rich",
                    DisplayName = "Ben Rich",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdBen = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdBen, "Admin");


            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Kelly",
                    LastName    = "Johnson",
                    DisplayName = "Kelly Johnson",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdKelly = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdKelly, "Admin");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Joseph",
                    LastName    = "Ware",
                    DisplayName = "Joseph Ware",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdJoseph = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdJoseph, "Submitter");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "James",
                    LastName    = "Sullivan",
                    DisplayName = "James Sullivan",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdJames = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdJames, "Submitter");


            // project Orion
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Cleon",
                    LastName    = "Lacefiled",
                    DisplayName = "Cleon Lacefiled",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdCleon = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdCleon, "Admin");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Larry",
                    LastName    = "Price",
                    DisplayName = "Larry Price",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdPrice = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdPrice, "Project Manager");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Bill",
                    LastName    = "Johns",
                    DisplayName = "Bill Johns",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdBill = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdBill, "Developer");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Gina",
                    LastName    = "Curet",
                    DisplayName = "Gina Curet",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdGina = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdGina, "Project Manager");

            // *************Project Tesla *********

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Elon",
                    LastName    = "Musk",
                    DisplayName = "Elon Musk",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdElon = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdElon, "Admin");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Brad",
                    LastName    = "Buss",
                    DisplayName = "Brad Buss",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdBrad = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdBrad, "Project Manager");

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    FirstName   = "Ira",
                    LastName    = "Ehrenpreis",
                    DisplayName = "Ira Ehrenpreis",
                    UserName    = "******",
                    Email       = "*****@*****.**"
                },
                                   "Password-1");
            }
            var userIdIra = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userIdIra, "Developer");

            var projects = new List <Project> {
                new Project {
                    Name = "Apollo 13"
                },
                new Project {
                    Name = "Seinfeld"
                },
                new Project {
                    Name = "Skunk Works"
                },
                new Project {
                    Name = "Orion"
                },
                new Project {
                    Name = "Tesla"
                }
            };

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

            var projectApollo   = context.Projects.Single(p => p.Name == "Apollo 13").Id;
            var projectSeinfeld = context.Projects.Single(p => p.Name == "Seinfeld").Id;
            var projectSkunk    = context.Projects.Single(p => p.Name == "Skunk Works").Id;
            var projectOrion    = context.Projects.Single(p => p.Name == "Orion").Id;
            var projectTesla    = context.Projects.Single(p => p.Name == "Tesla").Id;


            //var userIdSatya = userManager.FindByEmail("*****@*****.**").Id;
            //userManager.AddToRole(userIdSatya, "Admin");
            //userManager.AddToRole(userIdSatya, "Developer");


            var types = new List <TicketType>
            {
                new TicketType {
                    Name = "Bug"
                },
                new TicketType {
                    Name = "Unknown"
                },
                new TicketType {
                    Name = "Improvement"
                }
            };

            if (!context.TicketTypes.Any(r => r.Name == "Bug"))
            {
                types.ForEach(t => context.TicketTypes.Add(t));
                context.SaveChanges();
            }

            var typeBug         = context.TicketTypes.Single(p => p.Name == "Bug").Id;
            var typeUnknown     = context.TicketTypes.Single(p => p.Name == "Unknown").Id;
            var typeImprovement = context.TicketTypes.Single(p => p.Name == "Improvement").Id;

            var status = new List <TicketStatus>
            {
                new TicketStatus {
                    Name = "In progress"
                },
                new TicketStatus {
                    Name = "Not assigned"
                },
                new TicketStatus {
                    Name = "Closed"
                }
            };

            if (!context.TicketStatuses.Any(r => r.Name == "Not assigned"))
            {
                status.ForEach(s => context.TicketStatuses.Add(s));
                context.SaveChanges();
            }

            var statusInProgress  = context.TicketStatuses.Single(s => s.Name == "In Progress").Id;
            var statusNotAssigned = context.TicketStatuses.Single(s => s.Name == "Not Assigned").Id;
            var statusClosed      = context.TicketStatuses.Single(s => s.Name == "Closed").Id;


            var priority = new List <TicketPriority>
            {
                new TicketPriority {
                    Name = "Low"
                },
                new TicketPriority {
                    Name = "Medium"
                },
                new TicketPriority {
                    Name = "High"
                }
            };

            if (!context.TicketPriorities.Any(p => p.Name == "Low"))
            {
                priority.ForEach(p => context.TicketPriorities.Add(p));
                context.SaveChanges();
            }


            var priorityLow    = context.TicketPriorities.Single(p => p.Name == "Low");
            var priorityHigh   = context.TicketPriorities.Single(p => p.Name == "High");
            var priorityMedium = context.TicketPriorities.Single(p => p.Name == "Medium");

            var ticketsApollo = new List <Ticket>
            {
                new Ticket
                {
                    Title            = "Houston We Have a Problem",
                    Description      = "After completing the broadcast, flight control sent another message, 13, we got one more item for you when you get a chance. We'd like you to err, stir up your cryo tanks. In addition err, have a shaft and trunnion, for a look at the comet Bennett if you need it.Astronaut Jack Swigert replied, OK, stand by",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = projectApollo,
                    TicketTypeId     = typeBug,
                    TicketStatusId   = statusInProgress,
                    OwnerUserId      = userIdJim,
                    AssignedToUserId = userIdKranz,
                    TicketPriority   = priorityHigh,
                    TicketRead       = false
                },

                new Ticket {
                    Title            = "Can't attach a file to a ticket",
                    Description      = "It will be nice to have an Oxigen tank that works. Defect was found on the oxygen tank",
                    Created          = System.DateTimeOffset.UtcNow,
                    ProjectId        = projectApollo,
                    TicketTypeId     = typeImprovement,
                    TicketStatusId   = statusInProgress,
                    OwnerUserId      = userIdJack,
                    AssignedToUserId = userIdKranz,
                    TicketPriority   = priorityHigh,
                    TicketRead       = false
                }
            };

            if (!context.Tickets.Any(r => r.ProjectId == projectApollo))
            {
                ticketsApollo.ForEach(t => context.Tickets.Add(t));
                context.SaveChanges();
            }


            var ticketsSeinfeld = new List <Ticket>
            {
                new Ticket
                {
                    Title            = "Unfunny",
                    Description      = "Seinfeld began as a 23-minute pilot named The Seinfeld Chronicles. Created by stand-up comedian Jerry Seinfeld and writer Larry David, developed by NBC executive Rick Ludwin, and produced by Castle Rock Entertainment, it was a mix of Seinfeld's stand-up comedy routines and idiosyncratic, conversational scenes focusing on mundane aspects of everyday life such as laundry, the buttoning of the top button on one's shirt and the attempt by men to properly interpret the intent of women spending the night in Seinfeld's apartment.[7]The pilot was filmed at Stage 8 of Desilu Cahuenga studios, the same studio where The Dick Van Dyke Show was filmed (this was seen by the crew as a good omen),[8] and was recorded at Ren-Mar Studios in Hollywood.[9] The pilot was first screened to a group of two dozen NBC executives in Burbank, California in early 1989. Although it did not yield the explosion of laughter garnered by the pilots for the decades previous NBC successes like The Cosby Show and The Golden Girls, it drew a positive response from the assembled executives, such as Warren Littlefield, then the second-in-command for NBCs entertainment division, who relates, There was a sense this was something different. The room embraced the humor and the attitude. Littlefields boss, Brandon Tartikoff, by contrast, was not convinced that the show would work. A Jewish man from New York himself, Tartikoff characterized it as Too New York, too Jewish. Test audiences were even more harsh. NBCs practice at the time was to recruit 400 households by phone to ask them to evaluate pilots it aired on an unused channel on its cable system. An NBC research department memo summarized the pilots performance among the respondents as Weak, which Littlefield called a dagger to the heart.[7] Comments included, You cant get too excited about two guys going to the laundromat; Jerrys loser friend George is not a forceful character; Jerry needs a stronger supporting cast; and Why are they interrupting the stand-up for these stupid stories?",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = projectSeinfeld,
                    TicketTypeId     = typeImprovement,
                    TicketStatusId   = statusClosed,
                    OwnerUserId      = userIdJerry,
                    AssignedToUserId = userIdJerry,
                    TicketPriority   = priorityLow,
                    TicketRead       = false
                },

                new Ticket {
                    Title            = "Bro Manzier",
                    Description      = "Manzier  Fans of Seinfeld will remember the episode in which Kramer and Frank Costanza invented a men's bra. But the project froze because they couldn't agree on whether to call it a bro or a manzier",
                    Created          = System.DateTimeOffset.UtcNow,
                    ProjectId        = projectSeinfeld,
                    TicketTypeId     = typeImprovement,
                    TicketStatusId   = statusInProgress,
                    OwnerUserId      = userIdElane,
                    AssignedToUserId = userIdJerry,
                    TicketPriority   = priorityHigh,
                    TicketRead       = false
                }
            };

            if (!context.Tickets.Any(r => r.ProjectId == projectSeinfeld))
            {
                ticketsSeinfeld.ForEach(t => context.Tickets.Add(t));
                context.SaveChanges();
            }


            var ticketsSkunk = new List <Ticket>
            {
                new Ticket
                {
                    Title            = "U2",
                    Description      = "After World War II, the U.S. military desired better strategic reconnaissance to help determine Soviet capabilities and intentions. Into the 1950s, the best intelligence the American government had on the interior of the Soviet Union were German Luftwaffe photographs taken during the war of territory west of the Ural Mountains, so overflights to take aerial photographs of the Soviet Union began. After 1950, Soviet air defenses aggressively attacked all aircraft near its borders—sometimes even those over Japanese airspace—and the existing reconnaissance aircraft, primarily bombers converted for reconnaissance duty such as the Boeing RB-47, were vulnerable to anti-aircraft artillery, missiles, and fighters. Richard Leghorn of the United States Air Force suggested that an aircraft that could fly at 60,000 feet (18,300 m) should be safe from the MiG-17, the Soviet Union's best interceptor, which could barely reach 45,000 feet (13,700 m). He and others believed that Soviet radar, which used American equipment provided during the war, could not track aircraft above 65,000 feet.",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = projectSkunk,
                    TicketTypeId     = typeImprovement,
                    TicketStatusId   = statusNotAssigned,
                    OwnerUserId      = userIdKelly,
                    AssignedToUserId = userIdJoseph,
                    TicketPriority   = priorityLow,
                    TicketRead       = false
                },

                new Ticket {
                    Title            = "U2 over USSR",
                    Description      = "In July 1957, U.S. President Dwight D. Eisenhower requested permission from Pakistan's Prime Minister Huseyn Suhrawardy for the U.S. to establish a secret intelligence facility in Pakistan and for the U-2 spyplane to fly from Pakistan. The U-2 flew at altitudes that could not be reached by Soviet fighter jets of the era; it was believed to be beyond the reach of Soviet missiles as well. A facility established in Badaber (Peshawar Air Station), 10 miles (16 km) from Peshawar, was a cover for a major communications intercept operation run by the United States National Security Agency (NSA). Badaber was an excellent location because of its proximity to Soviet central Asia. This enabled the monitoring of missile test sites, key infrastructure and communications. The U-2 spy-in-the-sky was allowed to use the Pakistan Air Force portion of Peshawar Airport to gain vital photo intelligence in an era before satellite observation",
                    Created          = System.DateTimeOffset.UtcNow,
                    ProjectId        = projectSkunk,
                    TicketTypeId     = typeUnknown,
                    TicketStatusId   = statusInProgress,
                    OwnerUserId      = userIdJoseph,
                    AssignedToUserId = userIdBen,
                    TicketPriority   = priorityHigh,
                    TicketRead       = false
                },

                new Ticket {
                    Title            = "SR 71 fastest plane ever built NickName BlackBird",
                    Description      = "The SR-71 was designed for flight at over Mach 3 with a flight crew of two in tandem cockpits, with the pilot in the forward cockpit and the Reconnaissance Systems Officer (RSO) monitoring the surveillance systems and equipment from the rear cockpit.[20] The SR-71 was designed to minimize its radar cross-section, an early attempt at stealth design.[21] Finished aircraft were painted a dark blue, almost black, to increase the emission of internal heat and to act as camouflage against the night sky. The dark color led to the aircraft's call sign Blackbird.While the SR-71 carried electronic countermeasures to evade interception efforts, its greatest protection was its high speed and cruising altitude that made it almost invulnerable to the weapons of its day. Merely accelerating would typically be enough to evade a surface-to-air missile,[2] and the plane was faster than the Soviet Unions principal interceptor, the MiG-25.[22] During its service life, no SR-71 was shot down.",
                    Created          = System.DateTimeOffset.UtcNow,
                    ProjectId        = projectSkunk,
                    TicketTypeId     = typeUnknown,
                    TicketStatusId   = statusInProgress,
                    OwnerUserId      = userIdKelly,
                    AssignedToUserId = userIdJames,
                    TicketPriority   = priorityHigh,
                    TicketRead       = false
                },

                new Ticket {
                    Title            = "SR 71 Reactivation request",
                    Description      = "Due to unease over political situations in the Middle East and North Korea, the U.S. Congress re-examined the SR-71 beginning in 1993.[83] Rear Admiral Thomas F. Hall addressed the question of why the SR-71 was retired, saying it was under the belief that, given the time delay associated with mounting a mission, conducting a reconnaissance, retrieving the data, processing it, and getting it out to a field commander, that you had a problem in timelines that was not going to meet the tactical requirements on the modern battlefield. And the determination was that if one could take advantage of technology and develop a system that could get that data back real time... that would be able to meet the unique requirements of the tactical commander. Hall stated they were looking at alternative means of doing [the job of the SR-71].",
                    Created          = System.DateTimeOffset.UtcNow,
                    ProjectId        = projectSkunk,
                    TicketTypeId     = typeUnknown,
                    TicketStatusId   = statusInProgress,
                    OwnerUserId      = userIdJames,
                    AssignedToUserId = userIdSatya,
                    TicketPriority   = priorityHigh,
                    TicketRead       = false
                }
            };



            if (!context.Tickets.Any(r => r.ProjectId == projectSkunk))
            {
                ticketsSkunk.ForEach(t => context.Tickets.Add(t));
                context.SaveChanges();
            }



            var ticketsOrion = new List <Ticket>
            {
                new Ticket
                {
                    Title            = "New Human Module for Future Mission To Mars",
                    Description      = "The Orion MPCV takes basic design elements from the Apollo Command Module that took astronauts to the moon, but its technology and capability are more advanced. It is designed to support long-duration deep space missions, with up to 21 days active crew time plus 6 months quiescent.[33] During the quiescent period crew life support would be provided by another module such as a Deep Space Habitat. The spacecraft's life support, propulsion, thermal protection and avionics systems are designed to be upgradeable as new technologies become available. The MPCV spacecraft includes both crew and service modules, and a spacecraft adaptor. The MPCVs crew module is larger than Apollos and can support more crew members for short or long-duration missions. The service module fuels and propels the spacecraft as well as storing oxygen and water for astronauts. The service modules structure is also being designed to provide locations to mount scientific experiments and cargo.",
                    Created          = System.DateTimeOffset.UtcNow,
                    ProjectId        = projectSeinfeld,
                    TicketTypeId     = typeBug,
                    TicketStatusId   = statusInProgress,
                    OwnerUserId      = userIdBill,
                    AssignedToUserId = userIdSatya,
                    TicketPriority   = priorityMedium,
                    TicketRead       = false
                },

                new Ticket {
                    Title            = "Project Mars",
                    Description      = "The exploration of Mars has taken place over hundreds of years, beginning in earnest with the invention and development of the telescope during the 1600s. Increasingly detailed views of the planet from Earth inspired speculation about its environment and possible life – even intelligent civilizations – that might be found there. Probes sent from Earth beginning in the late 20th century have yielded a dramatic increase in knowledge about the Martian system, focused primarily on understanding its geology and habitability potential. Engineering interplanetary journeys is very complicated, so the exploration of Mars has experienced a high failure rate, especially in earlier attempts. Roughly two-thirds of all spacecraft destined for Mars failed before completing their missions, and there are some that failed before their observations could begin. However, missions have also met with unexpected levels of success, such as the twin Mars Exploration Rovers operating for years beyond their original mission specifications.",
                    Created          = System.DateTimeOffset.Now,
                    ProjectId        = projectSeinfeld,
                    TicketTypeId     = typeUnknown,
                    TicketStatusId   = statusInProgress,
                    OwnerUserId      = userIdGina,
                    AssignedToUserId = userIdSatya,
                    TicketPriority   = priorityHigh,
                    TicketRead       = false
                }
            };



            if (!context.Tickets.Any(r => r.ProjectId == projectOrion))
            {
                ticketsOrion.ForEach(t => context.Tickets.Add(t));
                context.SaveChanges();
            }

            int ticketId       = context.Tickets.FirstOrDefault(u => u.Title == "Project Mars").Id;
            var ticketsHistory = new List <TicketHistory>
            {
                new TicketHistory
                {
                    TicketId          = ticketId,
                    ProjectName       = "Orion",
                    OldProjectName    = "Apollo 13",
                    TicketTypeName    = "In Progress",
                    OldTicketTypeName = "Bug"
                },

                new TicketHistory
                {
                    TicketId              = ticketId,
                    TicketPriorityName    = "High",
                    OldTicketPriorityName = "Low",
                    TicketTypeName        = "In Progress",
                    OldTicketTypeName     = "Bug"
                }
            };

            if (!context.Tickets.Any(u => u.Title == "Project Mars"))
            {
                ticketsHistory.ForEach(h => context.TicketHistories.Add(h));
                context.SaveChanges();
            }
        }
Пример #47
0
        public async Task <ActionResult> RegisterAsClient(RegisterClientViewModel model)
        {
            if (ModelState.IsValid)
            {
                string username = ConfigurationManager.AppSettings["CompanyCheckAPIKey"];
                string password = "";
                var    encoded  = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", username, password)));

                JToken token = null;

                using (var client = new HttpClient())
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encoded);

                    string address = "https://api.companieshouse.gov.uk";
                    string comName = "/search/companies?q=" + model.CompanyName;

                    string newUri = address + comName;
                    Uri    uri    = new Uri(newUri);

                    HttpResponseMessage response = await client.GetAsync(uri);

                    if (response.IsSuccessStatusCode)
                    {
                        string textResult = await response.Content.ReadAsStringAsync();

                        token = JObject.Parse(textResult);
                    }
                    else
                    {
                        return(View(model));
                    }
                }

                var    companyNumbers = token.SelectTokens("items[*].company_number");
                string companyNumber  = "";

                foreach (string cn in companyNumbers)
                {
                    if (model.CompanyRegNum == cn)
                    {
                        companyNumber = cn;
                    }
                }

                if (companyNumber != model.CompanyRegNum)
                {
                    return(View(model));
                }
                else
                {
                    var user = new ApplicationUser {
                        UserName = model.Email, Email = model.Email
                    };
                    user.CompanyName   = model.CompanyName;
                    user.CompanyRegNum = model.CompanyRegNum;

                    var result = await UserManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        // Comment the following line to prevent log in until the user is confirmed.

                        UserManager.AddToRole(user.Id, "Client");
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        //string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");

                        // Uncomment to debug locally
                        // TempData["ViewBagLink"] = callbackUrl;

                        ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
                                          + "before you can log in.";

                        //return View("Info");
                        return(RedirectToAction("Index", "Home"));
                    }
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #48
0
        protected override void Seed(MSWD.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" }
            //    );
            //

            /*seed cities*/
            context.Cities.AddOrUpdate(
                c => c.Name,
                new City {
                Name = "Makati", DateCreated = DateTime.UtcNow.AddHours(8)
            },
                new City {
                Name = "Mandaluyong", DateCreated = DateTime.UtcNow.AddHours(8)
            }
                );

            context.SaveChanges();

            int makati_city      = context.Cities.FirstOrDefault(c => c.Name == "Makati").CityId;
            int mandaluyong_city = context.Cities.FirstOrDefault(c => c.Name == "Mandaluyong").CityId;

            /*seed roles*/
            var roleStore   = new RoleStore <IdentityRole>(context);
            var roleManager = new RoleManager <IdentityRole>(roleStore);

            if (!context.Roles.Any(r => r.Name == "Social Worker"))
            {
                var role = new IdentityRole {
                    Name = "Social Worker"
                };
                roleManager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name == "OIC"))
            {
                var role = new IdentityRole {
                    Name = "OIC"
                };
                roleManager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name == "Client"))
            {
                var role = new IdentityRole {
                    Name = "Client"
                };
                roleManager.Create(role);
            }

            /*seed accounts*/
            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new UserManager <ApplicationUser>(userStore);

            userManager.UserValidator = new UserValidator <ApplicationUser>(userManager)
            {
                AllowOnlyAlphanumericUserNames = false,
            };

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var user = new ApplicationUser
                {
                    CityId         = makati_city,
                    GivenName      = "Makati Social Worker 1",
                    MiddleName     = "",
                    LastName       = "Test",
                    UserName       = "******",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                    IsDisabled     = false
                };
                userManager.Create(user, "Testing@123");
                userManager.AddToRole(user.Id, "Social Worker");
            }
        }
Пример #49
0
        protected override void Seed(LearnVisualStudioAdmin.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" }
            //    );
            //

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

            // TODO: Change this hardcoded admin password!!!
            // Remember: Passwords must be at least 6 characters.

            var user = userManager.FindByEmail("*****@*****.**");

            if (user == null)
            {
                user = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                var result = userManager.Create(user, "YourPasswordHere");
                if (!result.Succeeded)
                {
                    throw new Exception("Cannot create default admin account!");
                }
            }

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

            var admin = roleManager.FindByName("Administrator");

            if (admin == null)
            {
                admin = new IdentityRole("Administrator");
                var result = roleManager.Create(admin);
                if (!result.Succeeded)
                {
                    throw new Exception("Cannot create the Administrator role.");
                }
            }

            var author = roleManager.FindByName("Author");

            if (author == null)
            {
                author = new IdentityRole("Author");
                var result = roleManager.Create(author);
                if (!result.Succeeded)
                {
                    throw new Exception("Cannot create the Author role.");
                }
            }

            var lifetime = roleManager.FindByName("Lifetime");

            if (lifetime == null)
            {
                lifetime = new IdentityRole("Lifetime");
                var result = roleManager.Create(lifetime);
                if (!result.Succeeded)
                {
                    throw new Exception("Cannot create the Lifetime role.");
                }
            }


            var oneyear = roleManager.FindByName("1Year");

            if (oneyear == null)
            {
                oneyear = new IdentityRole("1Year");
                var result = roleManager.Create(oneyear);
                if (!result.Succeeded)
                {
                    throw new Exception("Cannot create the 1Year role.");
                }
            }

            var free = roleManager.FindByName("Free");

            if (free == null)
            {
                free = new IdentityRole("Free");
                var result = roleManager.Create(free);
                if (!result.Succeeded)
                {
                    throw new Exception("Cannot create the Free role.");
                }
            }

            if (user.Roles.FirstOrDefault(r => r.RoleId.ToString() == admin.Id.ToString()) == null)
            {
                userManager.AddToRole(user.Id, "Administrator");
            }
        }
Пример #50
0
        protected override void Seed(ApplicationDbContext context)
        {
            byte[] AfrikaImage = GetResourceImage("Topo.Images.topoAfrika.png");
            string AfrikaMap   = GetResourceString("Topo.Images.TopoAfrikaMap.html");

            byte[] SovjetUnieImage = GetResourceImage("Topo.Images.topoSoftjetunie.png");
            string SovjetUnieMap   = "<map id='map' name='map'><area alt='C:A:Turkmenistan:' href='' coords='223,453,244,482' shape='rect'><area alt='C:B:Tadzjikistan:' href='' coords='301,472,320,488' shape='rect'><area alt='C:C:Kirgizië:' href='' coords='346,454,379,466' shape='rect'><area alt='C:D:Oezbekistan:' href='' coords='244,420,268,449' shape='rect'><area alt='B:E:moldavië:' href='' coords='64,234,78,246' shape='rect'><area alt='B:F:Estland:' href='' coords='152,164,163,173' shape='rect'><area alt='B:G:Litouwen:' href='' coords='114,162,126,173' shape='rect'><area alt='B:H:Letland:' href='' coords='124,146,135,164' shape='rect'><area alt='B:I:Georgië:' href='' coords='104,340,115,352' shape='rect'><area alt='B:J:Armenië:' href='' coords='117,374,124,393' shape='rect'><area alt='B:K:Azerbeidzjan:' href='' coords='129,376,140,390' shape='rect'><area alt='A:L:Kazachstan:' href='' coords='276,356,332,408' shape='rect'><area alt='A:M:Rusland:' href='' coords='381,234,444,286' shape='rect'><area alt='A:N:Oekraïne:' href='' coords='114,264,136,285' shape='rect'><area alt='A:O:Wit-Rusland:' href='' coords='106,210,132,227' shape='rect'><area alt='C:1:Riga:' href='' coords='132,167,149,186' shape='rect'><area alt='B:2:Nizjni Novgorod:' href='' coords='200,239,220,256' shape='rect'><area alt='A:3:Kiev:' href='' coords='80,224,111,244' shape='rect'><area alt='B:4:Samara:' href='' coords='213,277,238,299' shape='rect'><area alt='C:5:Norilsk:' href='' coords='447,200,470,228' shape='rect'><area alt='B:6:Tbilisi:' href='' coords='115,352,132,369' shape='rect'><area alt='B:7:Erevan:' href='' coords='90,369,112,384' shape='rect'><area alt='A:8:Moskou:' href='' coords='166,226,190,246' shape='rect'><area alt='C:9:Novosibirsk:' href='' coords='405,317,432,340' shape='rect'><area alt='B:10:Jekaterinburg:' href='' coords='286,280,319,297' shape='rect'><area alt='B:11:Perm:' href='' coords='266,258,298,276' shape='rect'><area alt='C:12:Tasjkent:' href='' coords='280,431,302,455' shape='rect'><area alt='B:13:Minsk:' href='' coords='100,195,134,208' shape='rect'><area alt='C:14:Vilnius:' href='' coords='102,175,131,186' shape='rect'><area alt='B:15:Bakoe:' href='' coords='140,390,156,410' shape='rect'><area alt='C:16:Tallinn:' href='' coords='151,140,165,161' shape='rect'><area alt='C:17:Bisjkek:' href='' coords='324,441,342,460' shape='rect'><area alt='C:18:Jakoetsk:' href='' coords='644,225,674,244' shape='rect'><area alt='C:19:Vladivostok:' href='' coords='764,370,785,393' shape='rect'><area alt='C:20:Irkoetsk:' href='' coords='529,354,560,369' shape='rect'><area alt='A:21:Alma Ata:' href='' coords='344,425,377,443' shape='rect'><area alt='C:22:Omsk:' href='' coords='346,310,372,335' shape='rect'><area alt='B:23:Odessa:' href='' coords='58,264,82,284' shape='rect'><area alt='C:24:Doesjanbe:' href='' coords='260,462,286,473' shape='rect'><area alt='A:25:St. Petersburg:' href='' coords='168,172,190,192' shape='rect'><area alt='C:26:Asjchabad:' href='' coords='195,432,225,451' shape='rect'><area alt='C:27:Chisinau:' href='' coords='44,245,64,259'><area alt='B:a:Barentszzee:' href='' coords='308,122,323,138' shape='rect'><area alt='A:b:Kaspische Zee:' href='' coords='153,350,171,370' shape='rect'><area alt='B:c:Lena:' href='' coords='595,258,623,282' shape='rect'><area alt='A:d:Oeral:' href='' coords='197,324,217,343' shape='rect'><area alt='A:e:Ob:' href='' coords='341,239,366,256' shape='rect'><area alt='B:f:Aralmeer:' href='' coords='232,384,250,398' shape='rect'><area alt='C:g:Don:' href='' coords='147,262,160,280' shape='rect'><area alt='B:h:Jenisej:' href='' coords='449,242,469,265' shape='rect'><area alt='C:i:Kolyma:' href='' coords='681,128,706,150' shape='rect'><area alt='B:j:Baikalmeer:' href='' coords='575,330,590,359' shape='rect'><area alt='C:k:Zee van Ochotsk:' href='' coords='764,226,800,254' shape='rect'><area alt='A:l:Zwarte Zee:' href='' coords='63,306,95,332' shape='rect'><area alt='C:m:Irtysj:' href='' coords='355,292,381,309' shape='rect'><area alt='A:n:Wolga:' href='' coords='188,283,208,301' shape='rect'><area alt='A:o:Noordelijke IJszee:' href='' coords='396,9,560,105' shape='rect'><area alt='A:I:Kaukasus:' href='' coords='131,317,152,340' shape='rect'><area alt='B:II:Nova Zembla:' href='' coords='348,103,405,150' shape='rect'></map>";

            byte[] ZuidwestAzie    = GetResourceImage("Topo.Images.ZuidwestAzie.png");
            string ZuidwestAzieMap = GetResourceString("Topo.Images.ZuidwestAzieMap.html");

            byte[] Azie    = GetResourceImage("Topo.Images.Azie.png");
            string AzieMap = GetResourceString("Topo.Images.AzieMap.html");
            var    Kaarten = new List <TopoKaart>
            {
                new TopoKaart {
                    Categorie = Categorieen.Wereld,
                    Title     = "Afrika",
                    Image     = AfrikaImage,
                    Map       = AfrikaMap
                },
                new TopoKaart {
                    Categorie = Categorieen.Wereld,
                    Title     = "Voormalig Sovjet-unie",
                    Image     = SovjetUnieImage,
                    Map       = SovjetUnieMap
                },
                new TopoKaart {
                    Categorie = Categorieen.Wereld,
                    Title     = "Zuid-West Azië",
                    Image     = ZuidwestAzie,
                    Map       = ZuidwestAzieMap
                },
                new TopoKaart {
                    Categorie = Categorieen.Wereld,
                    Title     = "kaart Wereld - Azië (Noord-Azië, Centraal-Azië, Verre Oosten, Oost-Azië, Zuidoost-Azië, Zuid-Azië, Zuidwest-Azië)",
                    Image     = Azie,
                    Map       = AzieMap
                }
            };

            Kaarten.ForEach(s => context.Kaarten.AddOrUpdate(k => k.Title, s));

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

                manager.Create(role);
            }

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

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

            context.SaveChanges();
        }
        protected override void Seed(ApplicationDbContext context)
        {
            // DEFAULT ROLE CREATION
            var roleManager = new RoleManager <IdentityRole>(
                new RoleStore <IdentityRole>(context));
            ApplicationDbContext db = new ApplicationDbContext();

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

            // DEFAULT USER CREATION
            var userManager = new UserManager <ApplicationUser>(
                new UserStore <ApplicationUser>(context));

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser {
                    UserName       = "******",
                    FirstName      = "Casey",
                    LastName       = "Jones",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                }, "CoderFoundry1!");
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser {
                    UserName       = "******",
                    FirstName      = "Mark",
                    LastName       = "Jaang",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                }, "Budgeter8**");
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser {
                    UserName       = "******",
                    FirstName      = "Ryan",
                    LastName       = "Chapman",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                }, "Budgeter8**");
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser {
                    UserName       = "******",
                    FirstName      = "Demo",
                    LastName       = "Head",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                }, "Budgeter8**");
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser {
                    UserName       = "******",
                    FirstName      = "Demo",
                    LastName       = "Adult",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                }, "Budgeter8**");
            }
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser {
                    UserName       = "******",
                    FirstName      = "Demo",
                    LastName       = "Member",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                }, "Budgeter8**");
            }


            // ASSIGNMENT OF ROLES TO EACH INITIAL USER

            //Casey Jones
            var userID = userManager.FindByEmail("*****@*****.**").Id;

            userManager.AddToRole(userID, "Head");
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Adult");
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Member");


            //Mark Jaang
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Head");
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Adult");
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Member");

            //Ryan Chapman
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Head");
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Adult");
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Member");

            // ASSIGNMENT OF DEMO USERS FOR EACH ROLE

            //DemoHead
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Head");
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Adult");
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Member");
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "DemoAccount");

            //DemoAdult
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Adult");
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Member");
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "DemoAccount");

            //DemoMember
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "Member");
            userID = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(userID, "DemoAccount");


            //ACCOUNT TYPE/CATEGORY SEEDING
            if (!context.AccountCategories.Any(p => p.Category == "Savings"))
            {
                var ac = new AccountCategory();
                ac.Category = "Savings";
                context.AccountCategories.Add(ac);
            }
            if (!context.AccountCategories.Any(p => p.Category == "Checking"))
            {
                var ac = new AccountCategory();
                ac.Category = "Checking";
                context.AccountCategories.Add(ac);
            }
            if (!context.AccountCategories.Any(p => p.Category == "Mortgage"))
            {
                var ac = new AccountCategory();
                ac.Category = "Mortgage";
                context.AccountCategories.Add(ac);
            }
            if (!context.AccountCategories.Any(p => p.Category == "Credit Card"))
            {
                var ac = new AccountCategory();
                ac.Category = "Credit Card";
                context.AccountCategories.Add(ac);
            }
            if (!context.AccountCategories.Any(p => p.Category == "Investment"))
            {
                var ac = new AccountCategory();
                ac.Category = "Investment";
                context.AccountCategories.Add(ac);
            }
            if (!context.AccountCategories.Any(p => p.Category == "Retirement"))
            {
                var ac = new AccountCategory();
                ac.Category = "Retirement";
                context.AccountCategories.Add(ac);
            }
            if (!context.AccountCategories.Any(p => p.Category == "Student Loan"))
            {
                var ac = new AccountCategory();
                ac.Category = "Student Loan";
                context.AccountCategories.Add(ac);
            }
            if (!context.AccountCategories.Any(p => p.Category == "Loan"))
            {
                var ac = new AccountCategory();
                ac.Category = "Loan";
                context.AccountCategories.Add(ac);
            }


            //EXPENSE TYPE/CATEGORY SEEDING
            if (!context.ExpenseCategories.Any(p => p.Category == "Utilities"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Utilities";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Mobile Devices"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Mobile Devices";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Rent"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Rent";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Mortgage"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Mortgage";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Credit Card Payment"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Credit Card Payment";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Insurance"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Insurance";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Daycare"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Daycare";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Student Loan Payment"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Student Loan Payment";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Loan Payment"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Loan Payment";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Tuition"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Tuition";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "School Supplies"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "School Supplies";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Taxes"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Taxes";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Investment"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Investment";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Retirement Contribution"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Retirement Contribution";
                context.ExpenseCategories.Add(ec);
            }

            if (!context.ExpenseCategories.Any(p => p.Category == "Child Support Payment"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Child Support Payment";
                context.ExpenseCategories.Add(ec);
            }
            if (!context.ExpenseCategories.Any(p => p.Category == "Alimony Payment"))
            {
                var ec = new ExpenseCategory();
                ec.Category = "Alimony Payment";
                context.ExpenseCategories.Add(ec);
            }

            //INCOME TYPE/CATEGORY SEEDING
            if (!context.IncomeCategories.Any(p => p.Category == "Paycheck"))
            {
                var ic = new IncomeCategory();
                ic.Category = "Paycheck";
                context.IncomeCategories.Add(ic);
            }
            if (!context.IncomeCategories.Any(p => p.Category == "Investment Return"))
            {
                var ic = new IncomeCategory();
                ic.Category = "Investment Return";
                context.IncomeCategories.Add(ic);
            }
            if (!context.IncomeCategories.Any(p => p.Category == "Retirement Benefit"))
            {
                var ic = new IncomeCategory();
                ic.Category = "Retirement Benefit";
                context.IncomeCategories.Add(ic);
            }
            if (!context.IncomeCategories.Any(p => p.Category == "Loan Dispursement"))
            {
                var ic = new IncomeCategory();
                ic.Category = "Loan Dispursement";
                context.IncomeCategories.Add(ic);
            }
            if (!context.IncomeCategories.Any(p => p.Category == "Unemployment"))
            {
                var ic = new IncomeCategory();
                ic.Category = "Unemployment";
                context.IncomeCategories.Add(ic);
            }
            if (!context.IncomeCategories.Any(p => p.Category == "Child Support"))
            {
                var ic = new IncomeCategory();
                ic.Category = "Child Support";
                context.IncomeCategories.Add(ic);
            }
            if (!context.IncomeCategories.Any(p => p.Category == "Alimony"))
            {
                var ic = new IncomeCategory();
                ic.Category = "Alimony";
                context.IncomeCategories.Add(ic);
            }
            if (!context.IncomeCategories.Any(p => p.Category == "Social Security"))
            {
                var ic = new IncomeCategory();
                ic.Category = "Social Security";
                context.IncomeCategories.Add(ic);
            }
            if (!context.IncomeCategories.Any(p => p.Category == "Tax Return"))
            {
                var ic = new IncomeCategory();
                ic.Category = "Tax Return";
                context.IncomeCategories.Add(ic);
            }
            if (!context.IncomeCategories.Any(p => p.Category == "Student Loan"))
            {
                var ic = new IncomeCategory();
                ic.Category = "Student Loan";
                context.IncomeCategories.Add(ic);
            }
            if (!context.IncomeCategories.Any(p => p.Category == "Reverse Mortgage"))
            {
                var ic = new IncomeCategory();
                ic.Category = "Reverse Mortgage";
                context.IncomeCategories.Add(ic);
            }

            // TRANSACTION TYPE/CATEGORY SEEDING
            // Expenses
            if (!context.TransactionCategories.Any(p => p.Category == "Gas"))
            {
                var tc = new TransactionCategory();
                tc.Category             = "Gas";
                tc.BudgetPlanCategoryId = db.BudgetPlanCategories.First(b => b.Category == "Transportation" && b.HouseholdId == null).Id;
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Food"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Food";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Utilities"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Utilities";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Mobile Devices"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Mobile Devices";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Rent"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Rent";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Mortgage"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Mortgage";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Credit Card Payment"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Credit Card Payment";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Insurance"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Insurance";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Daycare"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Daycare";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Student Loan Payment"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Student Loan Payment";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Loan Payment"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Loan Payment";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Tuition"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Tuition";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "School Supplies"))
            {
                var tc = new TransactionCategory();
                tc.Category = "School Supplies";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Taxes"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Taxes";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Investment"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Investment";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Child Support Payment"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Child Support Payment";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Alimony Payment"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Alimony Payment";
                context.TransactionCategories.Add(tc);
            }
            // Incomes
            if (!context.TransactionCategories.Any(p => p.Category == "Paycheck"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Paycheck";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Investment Return"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Investment Return";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Retirement"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Retirement";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Loan Dispursement"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Loan Dispursement";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Unemployment"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Unemployment";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Child Support"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Child Support";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Alimony"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Alimony";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Social Security"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Social Security";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Tax Return"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Tax Return";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Student Loan Dispursement"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Student Loan Dispursement";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Reverse Mortgage"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Reverse Mortgage";
                context.TransactionCategories.Add(tc);
            }
            // Other
            if (!context.TransactionCategories.Any(p => p.Category == "Clothing"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Clothing";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Home Repair/Maintenance"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Home Repair/Maintenance";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Auto Repair/Maintenance"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Auto Repair/Maintenance";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Money Transfer"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Money Transfer";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Travel/Vacation"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Travel/Vacation";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Pharmacy"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Pharmacy";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Healthcare"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Healthcare";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Restaurant"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Restaurant";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Pet Care"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Pet Care";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Entertainment"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Entertainment";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Gift"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Gift";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Charity"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Charity";
                context.TransactionCategories.Add(tc);
            }
            if (!context.TransactionCategories.Any(p => p.Category == "Hobby"))
            {
                var tc = new TransactionCategory();
                tc.Category = "Hobby";
                context.TransactionCategories.Add(tc);
            }

            // BUDGETPLAN CATEGORIES - !!!! DO *NOT* *NOT* *NOT* CHANGE THE ORDER OF THESE !!!!
            if (!context.BudgetPlanCategories.Any(p => p.Category == "Housing"))
            {
                var bpc = new BudgetPlanCategory();
                bpc.Category = "Housing";
                context.BudgetPlanCategories.Add(bpc);
            }
            if (!context.BudgetPlanCategories.Any(p => p.Category == "Transportation"))
            {
                var bpc = new BudgetPlanCategory();
                bpc.Category = "Transportation";
                context.BudgetPlanCategories.Add(bpc);
            }
            if (!context.BudgetPlanCategories.Any(p => p.Category == "Food"))
            {
                var bpc = new BudgetPlanCategory();
                bpc.Category = "Food";
                context.BudgetPlanCategories.Add(bpc);
            }
            if (!context.BudgetPlanCategories.Any(p => p.Category == "Entertainment"))
            {
                var bpc = new BudgetPlanCategory();
                bpc.Category = "Entertainment";
                context.BudgetPlanCategories.Add(bpc);
            }
            if (!context.BudgetPlanCategories.Any(p => p.Category == "Savings"))
            {
                var bpc = new BudgetPlanCategory();
                bpc.Category = "Savings";
                context.BudgetPlanCategories.Add(bpc);
            }
            if (!context.BudgetPlanCategories.Any(p => p.Category == "Debt"))
            {
                var bpc = new BudgetPlanCategory();
                bpc.Category = "Debt";
                context.BudgetPlanCategories.Add(bpc);
            }
            if (!context.BudgetPlanCategories.Any(p => p.Category == "Healthcare"))
            {
                var bpc = new BudgetPlanCategory();
                bpc.Category = "Healthcare";
                context.BudgetPlanCategories.Add(bpc);
            }
            if (!context.BudgetPlanCategories.Any(p => p.Category == "Education"))
            {
                var bpc = new BudgetPlanCategory();
                bpc.Category = "Education";
                context.BudgetPlanCategories.Add(bpc);
            }
            if (!context.BudgetPlanCategories.Any(p => p.Category == "Personal"))
            {
                var bpc = new BudgetPlanCategory();
                bpc.Category = "Personal";
                context.BudgetPlanCategories.Add(bpc);
            }
            if (!context.BudgetPlanCategories.Any(p => p.Category == "Childcare"))
            {
                var bpc = new BudgetPlanCategory();
                bpc.Category = "Childcare";
                context.BudgetPlanCategories.Add(bpc);
            }
            if (!context.BudgetPlanCategories.Any(p => p.Category == "Miscellaneous"))
            {
                var bpc = new BudgetPlanCategory();
                bpc.Category = "Miscellaneous";
                context.BudgetPlanCategories.Add(bpc);
            }

            // FREQUENCY CATEGORIES
            if (!context.FrequencyCategories.Any(p => p.Frequency == "Monthly"))
            {
                var fc = new FrequencyCategory();
                fc.Frequency = "Monthly";
                context.FrequencyCategories.Add(fc);
            }
            if (!context.FrequencyCategories.Any(p => p.Frequency == "Annually"))
            {
                var fc = new FrequencyCategory();
                fc.Frequency = "Annually";
                context.FrequencyCategories.Add(fc);
            }
            if (!context.FrequencyCategories.Any(p => p.Frequency == "Weekly"))
            {
                var fc = new FrequencyCategory();
                fc.Frequency = "Weekly";
                context.FrequencyCategories.Add(fc);
            }
            if (!context.FrequencyCategories.Any(p => p.Frequency == "Biweekly "))
            {
                var fc = new FrequencyCategory();
                fc.Frequency = "Biweekly";
                context.FrequencyCategories.Add(fc);
            }
            if (!context.FrequencyCategories.Any(p => p.Frequency == "Bimonthly"))
            {
                var fc = new FrequencyCategory();
                fc.Frequency = "Bimonthly";
                context.FrequencyCategories.Add(fc);
            }
        }
Пример #52
0
        private void createRolesandUsersandCategories()
        {
            ApplicationDbContext context = new ApplicationDbContext();
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

            if (context.Categories.Where(c => c.Nom == "Sport").Any() == false)
            {
                var Categorie = new Categorie();
                Categorie.Nom = "Sport";
                Categorie.Id  = Guid.NewGuid();
                context.Categories.Add(Categorie);
                context.SaveChanges();
            }
            if (context.Categories.Where(c => c.Nom == "Economie").Any() == false)
            {
                var Categorie = new Categorie();
                Categorie.Nom = "Economie";
                Categorie.Id  = Guid.NewGuid();
                context.Categories.Add(Categorie);
                context.SaveChanges();
            }
            if (context.Categories.Where(c => c.Nom == "Politique").Any() == false)
            {
                var Categorie = new Categorie();
                Categorie.Nom = "Politique";
                Categorie.Id  = Guid.NewGuid();
                context.Categories.Add(Categorie);
                context.SaveChanges();
            }
            if (context.Categories.Where(c => c.Nom == "Santé").Any() == false)
            {
                var Categorie = new Categorie();
                Categorie.Nom = "Santé";
                Categorie.Id  = Guid.NewGuid();
                context.Categories.Add(Categorie);
                context.SaveChanges();
            }


            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.Email    = "*****@*****.**";
                var cat = context.Categories.Where(c => c.Nom == "Politique").First();
                user.CategorieId = cat.Id;

                string userPWD = "Admin72@";

                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("Default"))
            {
                // first we create Admin rool
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Default";
                roleManager.Create(role);

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

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

                string userPWD = "Default72@";
                var    cat     = context.Categories.Where(c => c.Nom == "Politique").First();
                user.CategorieId = cat.Id;

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

                //Add default User to Role Admin
                if (chkUser.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, "Default");
                }
            }
        }
Пример #53
0
        public virtual ApplicationIdentityResult AddToRole(int userId, string role)
        {
            var identityResult = _userManager.AddToRole(userId, role);

            return(identityResult.ToApplicationIdentityResult());
        }
Пример #54
0
        public bool AddUserToRole(string userId, string roleName)
        {
            var result = userManager.AddToRole(userId, roleName);

            return(result.Succeeded);
        }
Пример #55
0
        public async Task <ActionResult> Save(FormCollection form)
        {
            //KLUDGED but frickin works
            //TO DO: Need to improve this

            var    member = _context.Members.ToList();
            string UserName;
            string CanAddTasks;
            string CanReassignTasks;
            string CanSendEmails;
            string CanChangeSettings;

            foreach (var m in member)
            {
                UserName          = form["member.UserName-" + m.ApplicationUserId].ToString();
                CanAddTasks       = form["CanAddTasks-" + m.ApplicationUserId].ToString();
                CanReassignTasks  = form["CanReassignTasks-" + m.ApplicationUserId].ToString();
                CanSendEmails     = form["CanSendEmails-" + m.ApplicationUserId].ToString();
                CanChangeSettings = form["CanChangeSettings-" + m.ApplicationUserId].ToString();

                var user = await UserManager.FindByNameAsync(UserName);

                if (CanAddTasks.IndexOf("on") > -1)
                {
                    UserManager.AddToRole(user.Id, "CanAddTasks");
                }
                else
                {
                    UserManager.RemoveFromRole(user.Id, "CanAddTasks");
                }

                if (CanReassignTasks.IndexOf("on") > -1)
                {
                    UserManager.AddToRole(user.Id, "CanReassignTasks");
                }
                else
                {
                    UserManager.RemoveFromRole(user.Id, "CanReassignTasks");
                }

                if (CanSendEmails.IndexOf("on") > -1)
                {
                    UserManager.AddToRole(user.Id, "CanSendEmails");
                }
                else
                {
                    UserManager.RemoveFromRole(user.Id, "CanSendEmails");
                }

                if (CanChangeSettings.IndexOf("on") > -1)
                {
                    UserManager.AddToRole(user.Id, "CanChangeSettings");
                }
                else
                {
                    UserManager.RemoveFromRole(user.Id, "CanChangeSettings");
                }
            }

            TempData["Msg"] = "User permissions successfully updated!";

            return(RedirectToAction("Index", "Admin"));
        }
        protected override void Seed(ApplicationDbContext context)
        {
            var RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            string[]       roleNames = { "Manager", "Accountant", "Employee" };
            IdentityResult roleResult;

            foreach (var roleName in roleNames)
            {
                if (!RoleManager.RoleExists(roleName))
                {
                    roleResult = RoleManager.Create(new IdentityRole(roleName));
                }
            }
            var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(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.
            //

            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userStore    = new UserStore <ApplicationUser>(context);
                var userManager  = new UserManager <ApplicationUser>(userStore);
                var userToInsert = new ApplicationUser {
                    Email = "*****@*****.**", PhoneNumber = "0797697898", UserName = "******"
                };
                userManager.Create(userToInsert, "Password@123");
                UserManager.AddToRole(userToInsert.Id, "Manager");
            }

            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userStore    = new UserStore <ApplicationUser>(context);
                var userManager  = new UserManager <ApplicationUser>(userStore);
                var userToInsert = new ApplicationUser {
                    Email = "*****@*****.**", PhoneNumber = "0797697898", UserName = "******"
                };
                userManager.Create(userToInsert, "Password@123");
                UserManager.AddToRole(userToInsert.Id, "Accountant");
            }

            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var             userStore    = new UserStore <ApplicationUser>(context);
                var             userManager  = new UserManager <ApplicationUser>(userStore);
                ApplicationUser currentUser  = context.Users.FirstOrDefault(x => x.Email == "*****@*****.**");
                var             userToInsert = new ApplicationUser {
                    Email = "*****@*****.**", PhoneNumber = "0797697898", UserName = "******", SuperVisorId = currentUser.Id
                };
                userManager.Create(userToInsert, "Password@123");
                UserManager.AddToRole(userToInsert.Id, "Employee");
            }

            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var             userStore    = new UserStore <ApplicationUser>(context);
                var             userManager  = new UserManager <ApplicationUser>(userStore);
                ApplicationUser currentUser  = context.Users.FirstOrDefault(x => x.Email == "*****@*****.**");
                var             userToInsert = new ApplicationUser {
                    Email = "*****@*****.**", PhoneNumber = "0797697898", UserName = "******", SuperVisorId = currentUser.Id
                };
                userManager.Create(userToInsert, "Password@123");
                UserManager.AddToRole(userToInsert.Id, "Employee");
            }

            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var             userStore    = new UserStore <ApplicationUser>(context);
                var             userManager  = new UserManager <ApplicationUser>(userStore);
                ApplicationUser currentUser  = context.Users.FirstOrDefault(x => x.Email == "*****@*****.**");
                var             userToInsert = new ApplicationUser {
                    Email = "*****@*****.**", PhoneNumber = "0797697898", UserName = "******", SuperVisorId = currentUser.Id
                };
                userManager.Create(userToInsert, "Password@123");
                UserManager.AddToRole(userToInsert.Id, "Employee");
            }
        }
        protected override void Seed(WebApplication2.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 == "View"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "View"
                };

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

                manager.Create(role);
            }

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******"
                };
                manager.Create(user, "Admin@123456");
                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 = "******"
                };
                manager.Create(user, "Crazy123");
                manager.AddToRole(user.Id, "Configuration");
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******"
                };
                manager.Create(user, "Crazy123");
                manager.AddToRole(user.Id, "View");
            }
        }
Пример #58
0
        public void CreateUsers(Models.ApplicationDbContext context)
        {
            if (!context.Roles.Any(r => r.Name == "Admin"))
            {
                var store   = new RoleStore <IdentityRole>(context);
                var manager = new RoleManager <IdentityRole>(store);
                var role    = new IdentityRole {
                    Name = "Admin"
                };

                manager.Create(role);
            }

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

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

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

                manager.Create(role);
            }

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

                manager.Create(user, "P@ssw0rd");
                manager.AddToRole(user.Id, "Manager");
            }

            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(u => u.UserName == "*****@*****.**"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };

                manager.Create(user, "P@ssw0rd");
                manager.AddToRole(user.Id, "User");
            }
        }
Пример #59
0
        protected override void Seed(ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
            context.Database.ExecuteSqlCommand("sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'");
            context.Database.ExecuteSqlCommand("sp_MSForEachTable 'IF OBJECT_ID(''?'') NOT IN (ISNULL(OBJECT_ID(''[dbo].[__MigrationHistory]''),0)) DELETE FROM ?'");
            context.Database.ExecuteSqlCommand("EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'");
            /*Roles*/
            string[] roles = { "Admin", "Manager", "Developer", "Submitter" };
            foreach (var RoleName in roles)
            {
                if (!context.Roles.Any(r => r.Name == RoleName))/*Developer Role*/
                {
                    var store   = new RoleStore <IdentityRole>(context);
                    var manager = new RoleManager <IdentityRole>(store);
                    var role    = new IdentityRole {
                        Name = RoleName
                    };
                    manager.Create(role);
                }
            }

            /*Users*/
            var appUsers = new List <ApplicationUser>();

            string[] Users = { "*****@*****.**",
                               "*****@*****.**",  "*****@*****.**",
                               "*****@*****.**","*****@*****.**",
                               "*****@*****.**","*****@*****.**" };
            foreach (var usr in Users)
            {
                var             PasswordHash = new PasswordHasher();
                ApplicationUser user;
                if (usr.StartsWith("sub"))
                {
                    user = new Submitter
                    {
                        UserName     = usr,
                        Email        = usr,
                        PasswordHash = PasswordHash.HashPassword("123456"),
                        Tickets      = new HashSet <Ticket>()
                    };
                }
                else if (usr.StartsWith("dev"))
                {
                    user = new Developer
                    {
                        UserName     = usr,
                        Email        = usr,
                        PasswordHash = PasswordHash.HashPassword("123456")
                    };
                }
                else
                {
                    user = new ApplicationUser
                    {
                        UserName     = usr,
                        Email        = usr,
                        PasswordHash = PasswordHash.HashPassword("123456")
                    };
                }

                if (!context.Users.Any(u => u.UserName == usr))
                {
                    var store   = new UserStore <ApplicationUser>(context);
                    var manager = new UserManager <ApplicationUser>(store);
                    manager.Create(user);
                    if (usr.StartsWith("admin"))
                    {
                        manager.AddToRole(user.Id, "Admin");
                    }
                    else if (usr.StartsWith("manager"))
                    {
                        manager.AddToRole(user.Id, "Manager");
                    }
                    else if (usr.StartsWith("developer"))
                    {
                        manager.AddToRole(user.Id, "Developer");
                    }
                    else if (usr.StartsWith("submitter"))
                    {
                        manager.AddToRole(user.Id, "Submitter");
                    }
                    appUsers.Add(user);
                }
            }
            if (appUsers.Count == 0)
            {
                appUsers = context.Users.ToList();
            }

            TicketProperty[] ticketProperties =
            {
                new TicketProperty {
                    Id = 1, Name = "Normal"
                },
                new TicketProperty {
                    Id = 2, Name = "Property 2"
                },
                new TicketProperty {
                    Id = 3, Name = "Urgent"
                },
            };
            TicketType[] ticketTypes =
            {
                new TicketType {
                    Id = 1, Name = "Request"
                },
                new TicketType {
                    Id = 2, Name = "Incident"
                },
                new TicketType {
                    Id = 3, Name = "Question"
                },
            };
            TicketStatus[] ticketStatuses =
            {
                new TicketStatus {
                    Id = 1, Name = "Assigned"
                },
                new TicketStatus {
                    Id = 2, Name = "Unassigned"
                },
                new TicketStatus {
                    Id = 3, Name = "Completed"
                },
            };
            context.Properties.AddOrUpdate(t => t.Name, ticketProperties);
            context.Types.AddOrUpdate(t => t.Name, ticketTypes);
            context.Statuses.AddOrUpdate(t => t.Name, ticketStatuses);

            Ticket[] tickets =
            {
                new Ticket()
                {
                    Id               = 1,
                    Title            = "ticket 1",
                    OwnerId          = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    ProjectId        = 1,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 1,
                    TicketTypeId     = 1,
                    TicketStatusId   = 1,
                },
                new Ticket()
                {
                    Id               = 2,
                    Title            = "ticket 2",
                    OwnerId          = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    ProjectId        = 1,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 1,
                    TicketTypeId     = 1,
                    TicketStatusId   = 1,
                },
                new Ticket()
                {
                    Id               = 3,
                    Title            = "ticket 3",
                    OwnerId          = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    ProjectId        = 1,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 1,
                    TicketTypeId     = 2,
                    TicketStatusId   = 1,
                },
                new Ticket()
                {
                    Id               = 4,
                    Title            = "ticket 4",
                    OwnerId          = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    ProjectId        = 1,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 2,
                    TicketTypeId     = 1,
                    TicketStatusId   = 3,
                },
                new Ticket()
                {
                    Id               = 5,
                    Title            = "ticket 5",
                    OwnerId          = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    ProjectId        = 1,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 2,
                    TicketTypeId     = 2,
                    TicketStatusId   = 2,
                },
                new Ticket()
                {
                    Id      = 6,
                    Title   = "ticket 6",
                    OwnerId = appUsers.Find(i => i.UserName == "*****@*****.**").Id,

                    ProjectId        = 2,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 1,
                    TicketTypeId     = 1,
                    TicketStatusId   = 1,
                },
                new Ticket()
                {
                    Id      = 7,
                    Title   = "ticket 7",
                    OwnerId = appUsers.Find(i => i.UserName == "*****@*****.**").Id,

                    ProjectId        = 2,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 1,
                    TicketTypeId     = 1,
                    TicketStatusId   = 1,
                },
                new Ticket()
                {
                    Id      = 8,
                    Title   = "ticket 8",
                    OwnerId = appUsers.Find(i => i.UserName == "*****@*****.**").Id,

                    ProjectId        = 2,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 1,
                    TicketTypeId     = 1,
                    TicketStatusId   = 1,
                },
                new Ticket()
                {
                    Id      = 9,
                    Title   = "ticket 9",
                    OwnerId = appUsers.Find(i => i.UserName == "*****@*****.**").Id,

                    ProjectId        = 2,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 1,
                    TicketTypeId     = 1,
                    TicketStatusId   = 1,
                },
                new Ticket()
                {
                    Id      = 10,
                    Title   = "ticket 10",
                    OwnerId = appUsers.Find(i => i.UserName == "*****@*****.**").Id,

                    ProjectId        = 2,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 1,
                    TicketTypeId     = 1,
                    TicketStatusId   = 1,
                },
                new Ticket()
                {
                    Id      = 11,
                    Title   = "ticket 11",
                    OwnerId = appUsers.Find(i => i.UserName == "*****@*****.**").Id,

                    ProjectId        = 2,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 1,
                    TicketTypeId     = 1,
                    TicketStatusId   = 1,
                },
                new Ticket()
                {
                    Id      = 12,
                    Title   = "ticket 12",
                    OwnerId = appUsers.Find(i => i.UserName == "*****@*****.**").Id,

                    ProjectId        = 2,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 1,
                    TicketTypeId     = 1,
                    TicketStatusId   = 1,
                },
                new Ticket()
                {
                    Id      = 13,
                    Title   = "ticket 13",
                    OwnerId = appUsers.Find(i => i.UserName == "*****@*****.**").Id,

                    ProjectId        = 2,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 1,
                    TicketTypeId     = 1,
                    TicketStatusId   = 1,
                },
                new Ticket()
                {
                    Id      = 14,
                    Title   = "ticket 14",
                    OwnerId = appUsers.Find(i => i.UserName == "*****@*****.**").Id,

                    ProjectId        = 2,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 3,
                    TicketTypeId     = 1,
                    TicketStatusId   = 2,
                },
                new Ticket()
                {
                    Id      = 15,
                    Title   = "ticket 15",
                    OwnerId = appUsers.Find(i => i.UserName == "*****@*****.**").Id,

                    ProjectId        = 2,
                    AssignedUserId   = appUsers.Find(i => i.UserName == "*****@*****.**").Id,
                    Created          = DateTime.Now,
                    Updated          = DateTime.Now,
                    TicketPropertyId = 2,
                    TicketTypeId     = 2,
                    TicketStatusId   = 3,
                }
            };

            Project[] projects =
            {
                new Project
                {
                    Id         = 1,
                    Title      = "Bug Track Project 1",
                    IsArchived = false,
                    //      Tickets= tickets.Where(i=>i.ProjectId==1).ToList(),
                    ApplicationUsers = appUsers.Where(i => i.UserName.StartsWith("admin") ||
                                                      i.UserName.StartsWith("manager1")).ToList()
                },
                new Project
                {
                    Id         = 2,
                    Title      = "Bug Track Project 2",
                    IsArchived = false,
                    //  Tickets= tickets.Where(i=>i.ProjectId==2).ToList(),
                    ApplicationUsers = appUsers.Where(i => i.UserName.StartsWith("admin") ||
                                                      i.UserName.StartsWith("manager2")).ToList()
                }
            };
            context.Projects.AddOrUpdate(t => t.Title, projects);

            context.Tickets.AddOrUpdate(t => t.Title, tickets);
        }
Пример #60
0
        protected override void Seed(CmChoi_BugTracker.Models.ApplicationDbContext context)
        {
            #region Roles 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 <CmChoi_BugTracker.Models.ApplicationUser>(
                new UserStore <CmChoi_BugTracker.Models.ApplicationUser>(context));


            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new CmChoi_BugTracker.Models.ApplicationUser
                {
                    UserName    = "******",
                    DisplayName = "The Admin",
                    Email       = "*****@*****.**",
                    FirstName   = "Caleb",
                    LastName    = "Choi",
                    AvatarUrl   = "/Uploads/Default-avatar.jpg"
                }, "Abc&123!");
            }


            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new CmChoi_BugTracker.Models.ApplicationUser
                {
                    UserName    = "******",
                    DisplayName = "PmErika",
                    Email       = "*****@*****.**",
                    FirstName   = "Erika",
                    LastName    = "Pm",
                    AvatarUrl   = "/Uploads/Default-avatar1.png"
                }, "Abc&123!");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new CmChoi_BugTracker.Models.ApplicationUser
                {
                    UserName    = "******",
                    DisplayName = "DevNaomi",
                    Email       = "*****@*****.**",
                    FirstName   = "Naomi",
                    LastName    = "Dev",
                    AvatarUrl   = "/Uploads/Default-avatar.jpg"
                }, "Abc&123!");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new CmChoi_BugTracker.Models.ApplicationUser
                {
                    UserName    = "******",
                    DisplayName = "SubRuth",
                    Email       = "*****@*****.**",
                    FirstName   = "Ruth",
                    LastName    = "Sub",
                    AvatarUrl   = "/Uploads/Default-avatar1.png"
                }, "Abc&123!");
            }

            //Introduce my Demo Users...
            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Demo",
                    LastName    = "Admin",
                    DisplayName = "The Admin",
                    AvatarUrl   = "/Uploads/Default-avatar.jpg"
                }, WebConfigurationManager.AppSettings["DemoUserPassword"]);
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Demo",
                    LastName    = "Project Manager",
                    DisplayName = "The PM",
                    AvatarUrl   = "/Uploads/Default-avatar1.png"
                }, WebConfigurationManager.AppSettings["DemoUserPassword"]);
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Demo",
                    LastName    = "Developer",
                    DisplayName = "The Dev",
                    AvatarUrl   = "/Uploads/Default-avatar.jpg"
                }, WebConfigurationManager.AppSettings["DemoUserPassword"]);
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                userManager.Create(new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Demo",
                    LastName    = "Submitter",
                    DisplayName = "The Sub",
                    AvatarUrl   = "/Uploads/Default-avatar1.png"
                }, WebConfigurationManager.AppSettings["DemoUserPassword"]);
            }
            #endregion


            #region Role Assignment
            var adminId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(adminId, "Admin");

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

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

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

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

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


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

            subId = userManager.FindByEmail("*****@*****.**").Id;
            userManager.AddToRole(subId, "Submitter");
            #endregion


            #region Project Creation
            context.Projects.AddOrUpdate(
                p => p.Name,
                new Project {
                Name = "Spock IT Blog", Description = "This is the Spock Blog project that is now out in the wild.", Created = DateTime.Now
            },
                new Project {
                Name = "Spock Portfolio", Description = "This is the Portfolio project that is now out in the wild.", Created = DateTime.Now
            },
                new Project {
                Name = "Spock BugTracker", Description = "This is the Spock BugTracker project that is now out in the wild.", Created = DateTime.Now
            }
                );

            context.SaveChanges();
            #endregion

            #region Project Assignment
            var blogProjectId       = context.Projects.FirstOrDefault(p => p.Name == "Spock IT Blog").Id;
            var bugTrackerProjectId = context.Projects.FirstOrDefault(p => p.Name == "Spock BugTracker").Id;

            var projectHelper = new ProjectsHelper();

            //Assign all three users to the Blog project
            projectHelper.AddUserToProject(pmId, blogProjectId);
            projectHelper.AddUserToProject(devId, blogProjectId);
            projectHelper.AddUserToProject(subId, blogProjectId);

            //Assign all three users to the Blog project
            projectHelper.AddUserToProject(pmId, bugTrackerProjectId);
            projectHelper.AddUserToProject(devId, bugTrackerProjectId);
            projectHelper.AddUserToProject(subId, bugTrackerProjectId);
            #endregion

            #region Priority, Status & Type creation (required FK's for a Ticket)
            context.TicketPriorities.AddOrUpdate(
                t => t.Name,
                new TicketPriority {
                Name = "Immediate", Description = "Highest priority level requiring immediate action"
            },
                new TicketPriority {
                Name = "High", Description = "A high priority level requiring quick action"
            },
                new TicketPriority {
                Name = "Medium", Description = ""
            },
                new TicketPriority {
                Name = "Low", Description = ""
            },
                new TicketPriority {
                Name = "None", Description = ""
            }
                );

            context.TicketStatuses.AddOrUpdate(
                t => t.Name,
                new TicketStatus {
                Name = "New / UnAssigned", Description = ""
            },
                new TicketStatus {
                Name = "UnAssigned", Description = ""
            },
                new TicketStatus {
                Name = "New / Assigned", Description = ""
            },
                new TicketStatus {
                Name = "Assigned", Description = ""
            },
                new TicketStatus {
                Name = "In Progress", Description = ""
            },
                new TicketStatus {
                Name = "Completed", Description = ""
            },
                new TicketStatus {
                Name = "Archived", Description = ""
            }
                );

            context.TicketTypes.AddOrUpdate(
                t => t.Name,
                new TicketType {
                Name = "Bug", Description = "An error has occurred that resulted in either the application crashing or the user seeing error information"
            },
                new TicketType {
                Name = "Defect", Description = "An error has occurred that resulted in either a miscalculation or an in correct workflow"
            },
                new TicketType {
                Name = "Feature Request", Description = "A client has called in asking for new functionality in an existing application"
            },
                new TicketType {
                Name = "Documentation Request", Description = "A client has called in asking for new documentation to be created for the existing application"
            },
                new TicketType {
                Name = "Training Request", Description = "A client has called in asking to schedule a training session"
            },
                new TicketType {
                Name = "Complaint", Description = "A client has called in to make a general complaint about our application"
            },
                new TicketType {
                Name = "Other", Description = "A call has been received that requires follow up but is outside the usual parameters for a request"
            }
                );

            context.SaveChanges();
            #endregion

            #region Ticket creation
            context.Tickets.AddOrUpdate(
                p => p.Title,
                //1 unassigned Bug on the Blog project
                //1 assigned Defect on the Blog project
                new Ticket
            {
                ProjectId        = blogProjectId,
                OwnerUserId      = subId,
                Title            = "Seeded Ticket #1",
                Description      = "Testing a seeded Ticket",
                Created          = DateTime.Now,
                TicketPriorityId = context.TicketPriorities.FirstOrDefault(t => t.Name == "Medium").Id,
                TicketStatusId   = context.TicketStatuses.FirstOrDefault(t => t.Name == "New / UnAssigned").Id,
                TicketTypeId     = context.TicketTypes.FirstOrDefault(t => t.Name == "Bug").Id,
            },
                new Ticket
            {
                ProjectId        = blogProjectId,
                OwnerUserId      = subId,
                AssignedToUserId = devId,
                Title            = "Seeded Ticket #2",
                Description      = "Testing a seeded Ticket",
                Created          = DateTime.Now,
                TicketPriorityId = context.TicketPriorities.FirstOrDefault(t => t.Name == "Medium").Id,
                TicketStatusId   = context.TicketStatuses.FirstOrDefault(t => t.Name == "New / Assigned").Id,
                TicketTypeId     = context.TicketTypes.FirstOrDefault(t => t.Name == "Defect").Id,
            },

                //1 unassigned Bug on the BugTracker
                //1 assigned Defect on the BugTracker
                //1 unassigned Bug on the Blog project
                //1 assigned Defect on the Blog project
                new Ticket
            {
                ProjectId        = bugTrackerProjectId,
                OwnerUserId      = subId,
                Title            = "Seeded Ticket #3",
                Description      = "Testing a seeded Ticket",
                Created          = DateTime.Now,
                TicketPriorityId = context.TicketPriorities.FirstOrDefault(t => t.Name == "Medium").Id,
                TicketStatusId   = context.TicketStatuses.FirstOrDefault(t => t.Name == "New / UnAssigned").Id,
                TicketTypeId     = context.TicketTypes.FirstOrDefault(t => t.Name == "Bug").Id,
            },
                new Ticket
            {
                ProjectId        = bugTrackerProjectId,
                OwnerUserId      = subId,
                AssignedToUserId = devId,
                Title            = "Seeded Ticket #4",
                Description      = "Testing a seeded Ticket",
                Created          = DateTime.Now,
                TicketPriorityId = context.TicketPriorities.FirstOrDefault(t => t.Name == "Medium").Id,
                TicketStatusId   = context.TicketStatuses.FirstOrDefault(t => t.Name == "New / Assigned").Id,
                TicketTypeId     = context.TicketTypes.FirstOrDefault(t => t.Name == "Defect").Id,
            });

            #endregion
        }