public static async Task<IdentityResult> AddUserToRole(string userId, string roleName)
            {
                var userManager = new UserManager<PlatformUser>(
                    new UserStore<PlatformUser>(new PlatformUserIdentityDbContext()));

                //Allows for use of email address as username:
                userManager.UserValidator = new UserValidator<PlatformUser>(userManager) { AllowOnlyAlphanumericUserNames = false };

                var result = await userManager.AddToRoleAsync(userId, roleName);

                return result;
        }
        public ActionResult Promote(string id)
        {
            var store = new UserStore<User>(this.Data.Context);
            var manager = new UserManager<User>(store);

            manager.AddToRoleAsync(id, GlobalConstants.AdminRole);

            this.Notify(GlobalConstants.PromoteUser, NotificationType.success);

            return this.RedirectToAction("Manage");
        }
        public async Task ClaimsIdentityTest()
        {
            var db = UnitTestHelper.CreateDefaultDb();
            var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
            var role = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
            var user = new IdentityUser("Hao");
            UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
            UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Admin")));
            UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Local")));
            UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Admin"));
            UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Local"));
            Claim[] userClaims =
            {
                new Claim("Whatever", "Value"),
                new Claim("Whatever2", "Value2")
            };
            foreach (var c in userClaims)
            {
                UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
            }

            var identity = await manager.CreateIdentityAsync(user, "test");
            var claimsFactory = manager.ClaimsIdentityFactory as ClaimsIdentityFactory<IdentityUser, string>;
            Assert.NotNull(claimsFactory);
            var claims = identity.Claims;
            Assert.NotNull(claims);
            Assert.True(
                claims.Any(c => c.Type == claimsFactory.UserNameClaimType && c.Value == user.UserName));
            Assert.True(claims.Any(c => c.Type == claimsFactory.UserIdClaimType && c.Value == user.Id));
            Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Admin"));
            Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Local"));
            Assert.True(
                claims.Any(
                    c =>
                        c.Type == ClaimsIdentityFactory<IdentityUser>.IdentityProviderClaimType &&
                        c.Value == ClaimsIdentityFactory<IdentityUser>.DefaultIdentityProviderClaimValue));
            foreach (var cl in userClaims)
            {
                Assert.True(claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
            }
        }
 private static async System.Threading.Tasks.Task CreateUserIfNotExist(UserManager<ApplicationUser> userManager, string email, string password, string role, string loginProvider = null, string providerKey = null)
 {
     var user = await userManager.FindByEmailAsync(email);
     if (user == null)
     {
         user = new ApplicationUser { UserName = email, Email = email };
         var result = await userManager.CreateAsync(user, password);
         if (!result.Succeeded)
         {
             throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray()));
         }
         await userManager.AddToRoleAsync(user, role);
         if (loginProvider != null && providerKey != null)
         {
             await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, ""));
         }
     }
 }
Example #5
0
 private static async Task<ApplicationUser> CreateUserIfNotExist(UserManager<ApplicationUser> userManager, ApplicationUser user, string password, string role, string loginProvider = null, string providerKey = null)
 {
     //Debugger.Launch();
     user.EmailConfirmed = true;
     user.Email = user.Email ?? user.UserName;
     if (await userManager.FindByEmailAsync(user.Email) == null)
     {
         var result = await userManager.CreateAsync(user, password);
         if (!result.Succeeded)
         {
             throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray()));
         }
         await userManager.AddToRoleAsync(user, role);
         if (loginProvider != null && providerKey != null)
         {
             await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, ""));
         }
     }
     return user;
 }
Example #6
0
        private async void Seed()
        {
            const string roleName = "administrator";
            const string userName = "[email protected]";
            var userContext = new ApplicationDbContext();
            var roleStore = new RoleStore<IdentityRole>(userContext);
            var roleManager = new RoleManager<IdentityRole>(roleStore);

            if (roleManager.RoleExists(roleName)) return;
            await roleManager.CreateAsync(new IdentityRole(roleName));
            var userStore = new UserStore<ApplicationUser>(userContext);
            var userManager = new UserManager<ApplicationUser>(userStore);
            var admin = new ApplicationUser() {UserName = userName};
            await userManager.CreateAsync(admin, "Koekoek!IsNummer1");
            await userManager.AddToRoleAsync(admin.Id, roleName);

            var pandContext = new ExclimmoContext();
            pandContext.SeedPanden();

        }
Example #7
0
        public async Task<ActionResult> AddUserToRole(AddUserToRoleViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (var ctx = new ApplicationDbContext())
                {
                    var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ctx));
                    var identityResult = await userManager.AddToRoleAsync(model.UserId, model.RoleName);

                    if (identityResult.Succeeded)
                    {
                        TempData["Message"] = "User added to role succesfully";
                    }
                    else
                    {
                        // TODO: add errors to TempData
                    }
                }
            }

            return RedirectToAction("EditMembers", "Roles", new { Id = model.RoleName});
        }
        public async Task<IHttpActionResult> UpdateRuoloUtente(UpdateRuoloUtenteModel Model)
        {
            if (Model == null || !ModelState.IsValid)
                return BadRequest(ModelState);

            using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
            {
                var utente = await userManager.FindByNameAsync(Model.Username);
                if (utente == null)
                    return NotFound();

                if (Model.NuovoStato)
                {
                    await userManager.AddToRoleAsync(utente.Id, Model.Ruolo);
                }
                else
                {
                    await userManager.RemoveFromRoleAsync(utente.Id, Model.Ruolo);
                }
            }

            return Ok();
        }
Example #9
0
		public async Task EnsureDatabaseAsync()
		{
			await MigrateDatabaseAsync(ServiceProvider);
			_userManager = ServiceProvider.GetService<UserManager<ApplicationUser>>();
			var roleManager = ServiceProvider.GetService<RoleManager<IdentityRole>>();
			await EnsureUsersAsync(false);
			Context = ServiceProvider.GetRequiredService<ApplicationDbContext>();
			//var userStore = new UserStore<ApplicationUser>(context);
			////var roleManager = new RoleManager<IdentityRole>();
			//var userManager = new UserManager<ApplicationUser>(
			//	, );
			EnsureDatabaseExists();
			Context.Database.EnsureCreated();
			// Add Mvc.Client to the known applications.
			_productsCrud = new CrudBase<Product, int>(
				Context, Context.Products, p => p.ProductId);
			_ordersCrud = new CrudBase<Order, int>(
				Context, Context.Orders, p => p.Id);
			var customersCrud = new CrudBase<Customer, int>(
				Context, Context.Customers, p => p.CustomerId);

			//Action<string, double, int?, DateTime?, string> prod = (name, price, customerId, dateCreated, cratedByUserId) =>
			//{
			//	productId = Prod(productsCrud, productId, name, price, customerId, dateCreated, cratedByUserId);
			//};
			Action<string, string, string> cust = (guid, firstName, lastName) =>
			{
				customersCrud.EnsureEntity(
					guid, customer =>
					{
						customer.FirstName = firstName;
						customer.LastName = lastName;
					});
			};

			cust("6c13ec25-b9cf-4c99-87e7-13a45a034342", "Harry", "Whitburn");
			cust("0e941f32-8ae1-4eae-875a-f748bae3ce2a", "Nick", "Lawden");
			cust("134bd420-f64a-40db-bbe4-0b9a9ff3eb01", "Emil", "Roijer");
			Context.SaveChanges();
			Prod("00d5c0b0-738d-41ff-86d4-dca84da1d4d5", "Apple number1", 10, null, null);
			Prod("cd4c554d-3ca2-49aa-9286-08abacba3fa0", "Apple number1", 10, 1, null, "1");
			Prod("d100c753-3335-439c-88db-b8d9b6c09cc8", "Orange number1", 20, null, null);
			Prod("da93b8a4-4378-4ce0-918e-653f1bd4acaf", "Peanut butter number1", 25, 2, null);
			Prod("fe208521-4a77-4b09-94c2-2f08a4dd8872", "xApple number2", 10, 1, null);
			Prod("844fbc16-3d77-4421-9498-aa65300bc789", "xOrange number2", 20, 2, null);
			Prod("78509968-0073-4c57-8774-ec0d58ea7ff3", "xPeanut butter number2", 25, 2, null);
			Prod("18b8c4e7-48a2-40c7-bea8-1d1879bf852e", "xApple number2", 10, 1, null);
			Prod("e5ab744c-441c-447b-ae92-055b1bce5541", "xOrange number2", 20, 2, null);
			Prod("3a5476b1-7dd8-40b0-a6ce-b6bd3127da6f", "xPeanut butter number2", 25, 2, null);
			Prod("633a125c-1fe2-4f06-859d-a8d8fd52eb11", "xApple number2", 10, 1, null);
			Prod("27eea6ff-c4aa-44a0-84fe-32b0e13beec4", "xOrange number2", 20, 2, null);
			Prod("dcdc6836-3b44-41c5-8ade-792e39ce2112", "xPeanut butter number2", 25, 2, null);
			Prod("fdc3139d-8585-4b34-b815-13598bf55791", "xApple number2", 10, 1, null);
			Prod("46b058b2-dd55-4741-9ee0-99c63c4bd94a", "xOrange number2", 20, 2, null);
			Prod("11c0e3e5-c5d7-4ff5-ba6c-a54b77f91d1b", "xPeanut butter number2", 25, 2, null);
			Prod("796b6b1d-2d6d-413c-bcab-2659c0fdf02f", "Apple number3", 10, 1, null);
			Prod("5f928f2f-bc1b-4e73-a0d8-20c36f817342", "Orange number3", 20, 2, null);
			Prod("f4fa623d-f412-4b68-8a26-17cfa16cb0a0", "Peanut butter number3", 25, 2, null);
			Prod("8f81d6ab-4c8f-4800-aea0-3cb1ca116fc6", "Apple number4", 10, 1, null);
			Prod("f2b8032f-c8ac-406f-8038-939201771901", "Orange number4", 20, 2, null);
			Prod("dc872dbf-956c-43aa-aba4-e75395af7d83", "Peanut butter number4", 25, 2, null);
			Prod("4ca16ce0-1466-4ba6-a69b-5465ed0a4b1d", "Apple number5", 10, 1, null);
			Prod("66cc487b-2eb1-470b-98c8-03ee913d860e", "Orange number5", 20, 2, null);
			Prod("e77e6589-1dba-4c8b-97b1-1564056ddf10", "Peanut butter number5", 25, 2, null);
			Prod("183946f3-41a9-4140-a1cb-b328e3a778d1", "Apple number6", 10, 1, null);
			Prod("2995edec-ec1b-42ed-aa97-1e68a9ef765c", "Orange number6", 20, 2, null);
			Prod("a78204ae-169a-4d30-936b-034cda5abd0f", "Peanut butter number6", 25, 2, null);
			Context.SaveChanges();
			Order("31d57282-4824-4441-9bd0-49588b952728", "First order", 1);
			Order("fc41cc01-6dc3-4ca5-88a4-c4a463cd6316", "Second order", 1);
			Order("f1379562-c779-43bc-a507-71a8506ca8c9", "Third order", 1);
			Context.SaveChanges();
			await EnsureUsersAsync(true);
			await roleManager.CreateAsync(new IdentityRole("Admin"));
			await roleManager.CreateAsync(new IdentityRole("User"));
			await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("1"), "Admin");
			await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("1"), "User");
			await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("2"), "User");
		}
        public async Task<ActionResult>  Create(RegisterViewModel userViewModel, string RoleId, [Bind(Include="Name")] ApplicationUser kUser, string[] selectedKPIs)
        {
          
            if(selectedKPIs != null)
            {
                kUser.KPIs = new List<KPI>();
                foreach(var kpi in selectedKPIs){
                    var kpiToAdd = context.KPIs.Find(int.Parse(kpi));
                    kUser.KPIs.Add(kpiToAdd);

                }
            }
            
            if (ModelState.IsValid)
            {
                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                var userinfo = new MyUserInfo()
                {
                    FirstName = userViewModel.FirstName,
                    LastName = userViewModel.LastName
                };
                var user = new ApplicationUser();
                user.UserName = userViewModel.UserName;
                user.Email = userViewModel.Email;
                user.MyUserInfo = userinfo;
                var adminresult =  UserManager.Create(user, userViewModel.Password);
         
                context.Users.Add(user);
                context.SaveChanges();
              
    
                //Add User Admin to Role Admin
                if (adminresult.Succeeded)
                {
                    if (!String.IsNullOrEmpty(RoleId))
                    {
                        //Find Role Admin
                        var role = await RoleManager.FindByIdAsync(RoleId);
                        var result = await UserManager.AddToRoleAsync(user.Id, role.Name);
                        if (!result.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First().ToString());
                            ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Id", "Name");
                            return View();
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First().ToString());
                    ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name");
                    return View();

                }
                return RedirectToAction("Index");
            }
            else
            {
                ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name");
                return View();
            }
        }
Example #11
0
        public static void DatabaseInitData(ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            if (!dbContext.Users.Any())
            {
                var user = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" };
                var result = userManager.CreateAsync(user, "[email protected]");

                userManager.AddToRoleAsync(user, RoleNames.Admin);
            }
            if (!dbContext.Cities.Any())
            {
                dbContext.Cities.Add(new City {Name = "Рязань"});
                dbContext.Cities.Add(new City {Name = "Тула"});

                dbContext.SaveChanges();
            }

            if (!dbContext.TypesHousing.Any())
            {
                var houseTypes = new List<TypesHousing>
                {
                    new TypesHousing {Name = "1-к квартира"},
                    new TypesHousing {Name = "2-к квартира"},
                    new TypesHousing {Name = "3-к квартира"},
                    new TypesHousing {Name = "4-к квартира"},
                    new TypesHousing {Name = "5-к квартира"},
                    new TypesHousing {Name = "комната"},
                    new TypesHousing {Name = "коммуналка"}
                };


                var additionList = new string[]
                {
                    "Дом",
                    "Флигель",
                    "Гостинка",
                    "Малосемейка",
                    "Комната в общежитии",
                    "Койко-место",
                    "Коттедж",
                    "Особняк",
                    "Часть дома",
                    "Комната в секции"
                };

                foreach (var item in additionList)
                {
                    houseTypes.Add(new TypesHousing {Name = item });
                }

                foreach (var type in houseTypes)
                {
                    dbContext.TypesHousing.Add(type);
                }

                dbContext.SaveChanges();
            }

            if (!dbContext.Districts.Any())
            {
                var ryazan = dbContext.Cities.First(x => x.Id == 1);
                var tula = dbContext.Cities.First(x => x.Id == 2);
                var districs = new District[]
                    {
                        new District { Name = "Дашково Песочня", City = ryazan },
                         new District { Name = "Дягилево", City = ryazan},
                         new District { Name = "Кальное", City = ryazan},
                         new District { Name = "Канищево", City = ryazan},
                        new District { Name =  "Михайловское шоссе", City = ryazan},
                        new District { Name =  "Московский", City = ryazan},
                         new District { Name = "Недостоево", City = ryazan},
                         new District { Name = "Приокский", City = ryazan},
                        new District { Name =  "Роща", City = ryazan},
                        new District { Name =  "Рыбное", City = ryazan},
                        new District { Name =  "Рязанский р-н", City = ryazan},
                        new District { Name =  "Соколовка", City = ryazan},
                        new District { Name =  "Солотча", City = tula},
                        new District { Name =  "Центр", City = tula},
                        new District { Name =  "Шлаковый", City = tula},
                         new District { Name = "Южный", City = tula},
                         new District { Name = "Центральный р-н", City = tula},
                         new District { Name = "Советский р-н", City = tula},
                         new District { Name = "Привокзальный р-н", City = tula},
                         new District { Name = "Зареченский р-н", City = tula},
                        new District { Name =  "Пролетарский р-н", City = tula},
                        new District { Name =  "Тульская обл", City = tula}
                    };

                foreach (var district in districs)
                {
                    dbContext.Districts.Add(district);
                }

                dbContext.SaveChanges();
            }


            if (!dbContext.Streets.Any())
            {
                #region

                var streets = new Street[]
                {
                    new Street {Name = "1 Мая ул"},
                    new Street {Name = "1 Район ул"},
                    new Street {Name = "1-й Авиационный проезд"},
                    new Street {Name = "1-й Аллейный проезд"},
                    new Street {Name = "1-й Базарный проезд"},
                    new Street {Name = "1-й Дачный пер"},
                    new Street {Name = "1-й Крайний проезд"},
                    new Street {Name = "1-й Озерный пер"},
                    new Street {Name = "1-й Тракторный проезд"},
                    new Street {Name = "10 Линия ул"},
                    new Street {Name = "10 Район ул"},
                    new Street {Name = "11 Линия ул"},
                    new Street {Name = "11 Район ул"},
                    new Street {Name = "12 Линия ул"},
                    new Street {Name = "12 Район ул"},
                    new Street {Name = "14 Линия ул"},
                    new Street {Name = "1905 года пер"},
                    new Street {Name = "2 Бутырки ул"},
                    new Street {Name = "2 Линия ул"},
                    new Street {Name = "2 Район ул"},
                    new Street {Name = "2-й Авиационный проезд"},
                    new Street {Name = "2-й Аллейный проезд"},
                    new Street {Name = "2-й Базарный проезд"},
                    new Street {Name = "2-й Дачный пер"},
                    new Street {Name = "2-й Дягилевский проезд"},
                    new Street {Name = "2-й Крайний проезд"},
                    new Street {Name = "2-й Озерный пер"},
                    new Street {Name = "2-й Тракторный проезд"},
                    new Street {Name = "26 Бакинских Комиссаров пл"},
                    new Street {Name = "3 Бутырки ул"},
                    new Street {Name = "3 Линия ул"},
                    new Street {Name = "3 Район ул"},
                    new Street {Name = "3-й Авиационный проезд"},
                    new Street {Name = "3-й Аллейный проезд"},
                    new Street {Name = "3-й Базарный проезд"},
                    new Street {Name = "3-й Дачный пер"},
                    new Street {Name = "3-й Дягилевский проезд"},
                    new Street {Name = "3-й Озерный пер"},
                    new Street {Name = "3-й Тракторный проезд"},
                    new Street {Name = "3-й Усадебный проезд"},
                    new Street {Name = "4 Линия ул"},
                    new Street {Name = "4 Район ул"},
                    new Street {Name = "4-й Авиационный проезд"},
                    new Street {Name = "4-й Аллейный проезд"},
                    new Street {Name = "4-й Дачный пер"},
                    new Street {Name = "4-й Дягилевский проезд"},
                    new Street {Name = "4-й Озерный пер"},
                    new Street {Name = "4-й Озёрный пер"},
                    new Street {Name = "4-й Тракторный проезд"},
                    new Street {Name = "4-й Усадебный проезд"},
                    new Street {Name = "5 Линия ул"},
                    new Street {Name = "5 Район ул"},
                    new Street {Name = "5-й Авиационный проезд"},
                    new Street {Name = "5-й Аллейный проезд"},
                    new Street {Name = "5-й Дягилевский проезд"},
                    new Street {Name = "5-й Озерный пер"},
                    new Street {Name = "50-летия Октября пл"},
                    new Street {Name = "6 Линия ул"},
                    new Street {Name = "6-й Авиационный проезд"},
                    new Street {Name = "6-й Аллейный проезд"},
                    new Street {Name = "7 Линия ул"},
                    new Street {Name = "7 Район ул"},
                    new Street {Name = "7-й Авиационный проезд"},
                    new Street {Name = "7-й Аллейный проезд"},
                    new Street {Name = "8 Линия ул"},
                    new Street {Name = "8 Марта ул"},
                    new Street {Name = "8 Район ул"},
                    new Street {Name = "8-й Авиационный проезд"},
                    new Street {Name = "9 Линия пер"},
                    new Street {Name = "9 Линия ул"},
                    new Street {Name = "9 Район ул"},
                    new Street {Name = "Авиационная ул"},
                    new Street {Name = "Аллейная 8-й проезд"},
                    new Street {Name = "Аллейная ул"},
                    new Street {Name = "Бабушкина 1-й проезд"},
                    new Street {Name = "Бабушкина ул"},
                    new Street {Name = "Баженова пер"},
                    new Street {Name = "Баженова ул"},
                    new Street {Name = "Базарная ул"},
                    new Street {Name = "Бахмачеевская ул"},
                    new Street {Name = "Безбожная 1-я ул"},
                    new Street {Name = "Безбожная 2-я ул"},
                    new Street {Name = "Белинского проезд"},
                    new Street {Name = "Белинского ул"},
                    new Street {Name = "Белякова ул"},
                    new Street {Name = "Березняковская ул"},
                    new Street {Name = "Березовая ул"},
                    new Street {Name = "Библиотечная ул"},
                    new Street {Name = "Бирюзова ул"},
                    new Street {Name = "Боголюбова ул"},
                    new Street {Name = "Божатково мкр"},
                    new Street {Name = "Божатково п"},
                    new Street {Name = "Больничная (Солотча) ул"},
                    new Street {Name = "Большая (Шереметьево-Песочня) ул"},
                    new Street {Name = "Борки мкр"},
                    new Street {Name = "Братиславская ул"},
                    new Street {Name = "Бронная ул"},
                    new Street {Name = "Бульварный пер"},
                    new Street {Name = "Быстрецкая ул"},
                    new Street {Name = "Вагоны (Соколовка) тер"},
                    new Street {Name = "Введенская ул"},
                    new Street {Name = "Великанова ул"},
                    new Street {Name = "Верхняя ул"},
                    new Street {Name = "Весенняя (Канищево) ул"},
                    new Street {Name = "Весенняя ул"},
                    new Street {Name = "Ветеринарная ул"},
                    new Street {Name = "Вишневая ул"},
                    new Street {Name = "Вишневый (Канищево) пер"},
                    new Street {Name = "Владимирская (Солотча) ул"},
                    new Street {Name = "Вознесенская ул"},
                    new Street {Name = "Войкова пер"},
                    new Street {Name = "Вокзальная ул"},
                    new Street {Name = "Вольная (Солотча) ул"},
                    new Street {Name = "Восточная ул"},
                    new Street {Name = "Восточный промузел мкр"},
                    new Street {Name = "Высоковольтная ул"},
                    new Street {Name = "Гагарина (Соколовка) ул"},
                    new Street {Name = "Гагарина 1-й проезд"},
                    new Street {Name = "Гагарина 2-й проезд"},
                    new Street {Name = "Гагарина 3-й проезд"},
                    new Street {Name = "Гагарина 4-й проезд"},
                    new Street {Name = "Гагарина ул"},
                    new Street {Name = "Газетный пер"},
                    new Street {Name = "Гайдара (Солотча) ул"},
                    new Street {Name = "Гайдара ул"},
                    new Street {Name = "Гаражная ул"},
                    new Street {Name = "Гвардейская ул"},
                    new Street {Name = "Гоголя проезд"},
                    new Street {Name = "Гоголя ул"},
                    new Street {Name = "Голенчинская ул"},
                    new Street {Name = "Голенчинское ш"},
                    new Street {Name = "Горького ул"},
                    new Street {Name = "Гражданская 2-й пер"},
                    new Street {Name = "Гражданская ул"},
                    new Street {Name = "Гражданский 1-й проезд"},
                    new Street {Name = "Грибоедова проезд"},
                    new Street {Name = "Грибоедова ул"},
                    new Street {Name = "Дачная (Канищево) ул"},
                    new Street {Name = "Дачная (Соколовка) ул"},
                    new Street {Name = "Дачная (Солотча) ул"},
                    new Street {Name = "Дачная ул"},
                    new Street {Name = "Дашковская ул"},
                    new Street {Name = "Декабристов проезд"},
                    new Street {Name = "Декабристов ул"},
                    new Street {Name = "Дзержинского ул"},
                    new Street {Name = "Димитрова пл"},
                    new Street {Name = "Димитрова ул"},
                    new Street {Name = "Добролюбова 1-й проезд"},
                    new Street {Name = "Добролюбова 2-й проезд"},
                    new Street {Name = "Добролюбова 3-й проезд"},
                    new Street {Name = "Добролюбова 4-й проезд"},
                    new Street {Name = "Добролюбова 5-й проезд"},
                    new Street {Name = "Добролюбова 6-й проезд"},
                    new Street {Name = "Добролюбова ул"},
                    new Street {Name = "Дорожная (Канищево) ул"},
                    new Street {Name = "Дорожная (Соколовка) ул"},
                    new Street {Name = "Дорожный пер"},
                    new Street {Name = "Достоевского ул"},
                    new Street {Name = "Дружная ул"},
                    new Street {Name = "Дунай (Солотча) ул"},
                    new Street {Name = "Дягилево п"},
                    new Street {Name = "Дягилево ст"},
                    new Street {Name = "Дягилевская ул"},
                    new Street {Name = "Есенина ул"},
                    new Street {Name = "Железнодорожная (Соколовка) ул"},
                    new Street {Name = "Железнодорожная (Солотча) ул"},
                    new Street {Name = "Железнодорожная 1-я ул"},
                    new Street {Name = "Железнодорожная 2-я ул"},
                    new Street {Name = "Животноводческая ул"},
                    new Street {Name = "Животноводческий проезд"},
                    new Street {Name = "Забайкальская ул"},
                    new Street {Name = "Заводская проезд"},
                    new Street {Name = "Завражнова проезд"},
                    new Street {Name = "Загородная ул"},
                    new Street {Name = "Западная ул"},
                    new Street {Name = "Запрудная ул"},
                    new Street {Name = "Заречная ул"},
                    new Street {Name = "Затинная ул"},
                    new Street {Name = "Зафабричная ул"},
                    new Street {Name = "Земляничная ул"},
                    new Street {Name = "Земляничный 1-й проезд"},
                    new Street {Name = "Земляничный 2-й проезд"},
                    new Street {Name = "Земляничный пер"},
                    new Street {Name = "Зубковой ул"},
                    new Street {Name = "Индустриальный 1-й пер"},
                    new Street {Name = "Интернатская ул"},
                    new Street {Name = "Интернациональная ул"},
                    new Street {Name = "К.Маркса ул"},
                    new Street {Name = "Кальная ул"},
                    new Street {Name = "Кальновский туп"},
                    new Street {Name = "Кальное мкр"},
                    new Street {Name = "Кальной проезд"},
                    new Street {Name = "Канищево п"},
                    new Street {Name = "Карцево п"},
                    new Street {Name = "Карцево тер"},
                    new Street {Name = "Карьерная ул"},
                    new Street {Name = "Касимовский пер"},
                    new Street {Name = "Касимовское ш"},
                    new Street {Name = "Качевская ул"},
                    new Street {Name = "Каширина ул"},
                    new Street {Name = "Керамзавода ул"},
                    new Street {Name = "Керамические Выселки ул"},
                    new Street {Name = "Кирпичного завода ул"},
                    new Street {Name = "Коломенская ул"},
                    new Street {Name = "Коломенский 1-й проезд"},
                    new Street {Name = "Коломенский 2-й проезд"},
                    new Street {Name = "Коломенский 3-й проезд"},
                    new Street {Name = "Коломенский 4-й проезд"},
                    new Street {Name = "Коломенский 5-й проезд"},
                    new Street {Name = "Коломенский 6-й проезд"},
                    new Street {Name = "Колхозная (Канищево) ул"},
                    new Street {Name = "Колхозная (Семчино) ул"},
                    new Street {Name = "Колхозная ул"},
                    new Street {Name = "Колхозный проезд"},
                    new Street {Name = "Кольцова ул"},
                    new Street {Name = "Комбайновая ул"},
                    new Street {Name = "Коммунистический пер"},
                    new Street {Name = "Комсомольский пер"},
                    new Street {Name = "Коняева 1-й проезд"},
                    new Street {Name = "Коняева 2-й проезд"},
                    new Street {Name = "Коняева 3-й проезд"},
                    new Street {Name = "Коняева 4-й проезд"},
                    new Street {Name = "Коняева 5-й проезд"},
                    new Street {Name = "Коняева ул"},
                    new Street {Name = "Корнилова ул"},
                    new Street {Name = "Космодемьянской 1-й проезд"},
                    new Street {Name = "Космодемьянской ул"},
                    new Street {Name = "Космонавтов ул"},
                    new Street {Name = "Костычева ул"},
                    new Street {Name = "Котовского проезд"},
                    new Street {Name = "Котовского ул"},
                    new Street {Name = "Крайняя ул"},
                    new Street {Name = "Красная 1-я ул"},
                    new Street {Name = "Красная 2-я ул"},
                    new Street {Name = "Краснорядская ул"},
                    new Street {Name = "Кремлевский вал"},
                    new Street {Name = "Кремль ул"},
                    new Street {Name = "Крупской ул"},
                    new Street {Name = "Кудрявцева ул"},
                    new Street {Name = "Куйбышевское ш"},
                    new Street {Name = "Культуры ул"},
                    new Street {Name = "Кутузова ул"},
                    new Street {Name = "Л.Шевцовой ул"},
                    new Street {Name = "Лагерная ул"},
                    new Street {Name = "Лево-Лыбедска ул"},
                    new Street {Name = "Ленина пл"}
                };


                #endregion

                var cityList = dbContext.Cities.Select(x => x.Id).ToList();
                foreach (var street in streets)
                {
                    street.CityId = cityList[Random.Next(cityList.Count)];
                    dbContext.Streets.Add(street);
                }

                dbContext.SaveChanges();
            }

            if (!dbContext.Housing.Any())
            {
                for (int i = 0; i < 100; i++)
                {
                    dbContext.Housing.Add(CreateHousingRadnom(dbContext));
                    dbContext.SaveChanges();
                }
            }
        }
Example #12
0
        private async Task CreateAcount(ApplicationDbContext context, UserManager<ApplicationUser> userManager, string name, string surname, string email, string password, Configurations.Role role, Configurations.UserType userType)
        {

            if (context.Consumers.Any(x => x.Email == email) || context.Producers.Any(x => x.Email == email))
                return;
            User user;
            switch(userType)
            {
                case Configurations.UserType.Producer:
                    user = new Producer();
                    break;
                case Configurations.UserType.Consumer:
                    user = new Consumer();
                    break;
                default:
                    user = new Consumer();
                    break;
            }                
            user.Name = name;
            user.Surname = surname;
            user.Email = email;
            user.Avatar = Path.Combine(Configurations.UserAvatarStockagePath, Configurations.DefaultFileName);
            user.RegistrationDate = DateTime.Now;
            user.Enable = true;

            switch (userType)
            {
                case Configurations.UserType.Producer:
                    Producer producer = user as Producer;
                    producer.CompanyName = "La ferme de " + producer.Name;
		    producer.Latitude = 44.7354673;
		    producer.Longitude = 4.601407399999971;
                    context.Producers.Add(producer);
                    break;
                case Configurations.UserType.Consumer:
                    context.Consumers.Add(user as Consumer);
                    break;
                default:
                    context.Consumers.Add(user as Consumer);
                    break;
            }


#region Creating linked application data
            var appUser = new ApplicationUser { UserName = user.Email, Email = user.Email };
            appUser.User = user;

            var result = await userManager.CreateAsync(appUser, password);
            if (result.Succeeded)
            {
                //Add user role
                result = await userManager.AddToRoleAsync(appUser, role.ToString());
                //Add user type
                result = await userManager.AddToRoleAsync(appUser, userType.ToString());
            }
#endregion Creating linked application data

            context.SaveChanges();

        }
Example #13
0
        private async Task Seed(IUnitOfWork uow  , UserManager<ApplicationUser> usrMan, RoleManager<IdentityRole> _RoleManager)
        {

            var email = "[email protected]";
            var RoleName = "CustomerAdmin";
            var role = await _RoleManager.FindByNameAsync(RoleName);
            if (role == null)
            {
                role = new IdentityRole { Name = RoleName };
                await _RoleManager.CreateAsync(role);
            }

        RoleName = "superadmin";
            role = await _RoleManager.FindByNameAsync( RoleName );
            if ( role == null)
            {
                role = new IdentityRole { Name = "SuperAdmin" };
                await _RoleManager.CreateAsync(role);
            }
            
            var appUser = await usrMan.FindByEmailAsync(email);
            if (appUser != null)
            {
                var result = await usrMan.DeleteAsync(appUser);
            }
            else 
            {
                appUser = new ApplicationUser() { UserName = email, Email = email };
                var result2 = await usrMan.CreateAsync(appUser, "Shafiro2,");
                if (result2.Succeeded)
                {
                    await usrMan.AddToRoleAsync(appUser,  RoleName ); 
                    var hrmUser = new User()
                    {
                        UserID = "7310209296",
                        FirstName = "Gabriel",
                        LastName = "Tekin",
                        UserName = "gabtek",
                        UserCode = "tekgab",
                        PhoneNumber = "0702385537"
                    };
                    if (uow.UserRepository.GetEagerLoad( w => w.UserID.Equals( hrmUser.UserID, StringComparison.OrdinalIgnoreCase )).FirstOrDefault()   == null )
                    {
                        uow.UserRepository.Insert(hrmUser);
                        uow.Save();
                    }
                    
                }
                else
                {
                    var code = result2.Errors.FirstOrDefault().Code;
                }
            }

            } // method seed 
    protected void RoleCheckBox_CheckChanged(object sender, EventArgs e)
    {
        // Reference the CheckBox that raised this event
        CheckBox RoleCheckBox = sender as CheckBox;

        // Get the currently selected user and role
        string selectedUserName = UserList.SelectedValue;
        var um = new UserManager();
        var user = um.FindByName(selectedUserName);
        string roleName = RoleCheckBox.Text;

        // Determine if we need to add or remove the user from this role
        if (RoleCheckBox.Checked)
        {
            // Add the user to the role
            um.AddToRoleAsync(user.Id, roleName);

            // Display a status message
            ActionStatus.Text = string.Format("User {0} was added to role {1}.", selectedUserName, roleName);
        }
        else
        {
            // Remove the user from the role
            um.RemoveFromRoleAsync(user.Id, roleName);

            // Display a status message
            ActionStatus.Text = string.Format("User {0} was removed from role {1}.", selectedUserName, roleName);
        }

        // Refresh the "by role" interface
        DisplayUsersBelongingToRole();
    }
        /// <summary>
        /// remove all current permission for the given user and insert new given permissions. 
        /// </summary>
        /// <param name="newRoles">Accepts a list of RolesName type string</param>
        /// <param name="UserID">Accepts a 128 chr userID type string</param>
        /// <returns></returns>
        public async Task<string> EditbuildingUserPermission(List<string> newRoles, string UserID)
        {
            var result = "";
            var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            //get all roles for the current user
            List<string> AllRoles = UserManager.GetRoles(UserID).ToList();
            //delete all the roles
            foreach (var item in AllRoles)
            {
                await UserManager.RemoveFromRoleAsync(UserID, item);
            }
            //add new roles 
            foreach (var item in newRoles)
            {
                if (RoleManager.RoleExists(item))
                {
                    await UserManager.AddToRoleAsync(UserID, item);
                }
            }

            return result;

        }
        private static void AddUsersToRoles(UserManager<ApplicationUser> users, RoleManager<ApplicationRole> roleManager)
        {
            var admin = users.FindByEmailAsync("[email protected]").Result;
            var esthetician = users.FindByEmailAsync("[email protected]").Result;

            Task.FromResult(users.AddToRolesAsync(admin, new[] { "Admin", "Esthetician" }).Result);
            Task.FromResult(users.AddToRoleAsync(esthetician, "Esthetician").Result);
        }
        public async Task<ActionResult> AddUserToRole(string roleName)
        {
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            var roleStore = new RoleStore<IdentityRole>();
            var roleManager = new RoleManager<IdentityRole>(roleStore);

            var role = await roleManager.FindByNameAsync(roleName);

            if (role == null)
            {
                return View();
            }


            await userManager.AddToRoleAsync(User.Identity.GetUserId(), roleName);
   
            return RedirectToAction("index", "home");
        }
 private async Task AddUserToRoleAsync(ApplicationUser user, string role)
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
     var result = await userManager.AddToRoleAsync(user.Id, role);
 }
Example #19
-1
 private async static void InitializeUserAdmin(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
 {
     ApplicationUser admin = new ApplicationUser
     {
         UserName = "[email protected]",
         Email = "[email protected]",
         DateOfBirth = new DateTime(1990, 1, 1),
         EmailConfirmed = true
     };
     Thread.Sleep(2000);
     await userManager.CreateAsync(admin, "[email protected]"); //password must match constraints of 6 char min, case-change, min 1 number and non-letter character
     Thread.Sleep(2000);
     await userManager.AddToRoleAsync(admin, "admin");
     context.SaveChanges();
 }