public ActionResult CreateUser(CreateUserViewModel newUser)
        {
            if(ModelState.IsValid){
                try {

                    _userService.CreateUser(newUser.Username, newUser.Password, newUser.UserRole);

                    if (Membership.ValidateUser(newUser.Username, newUser.Password))
                    {
                        _authentication.Login(_sessionManager.CurrentSession.CurrentSystemUser.Id.ToString(), false);
                        return RedirectToAction("Index", "Home");
                    }
                }
                catch (ArgumentException e) {
                    ModelState.AddModelError("", e.Message);
                }

            }
            return View(newUser);
        }
        public async Task <ActionResult> Register(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppUser user = new AppUser {
                    UserName = model.Name, Email = model.Email
                };
                IdentityResult result =
                    await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    UserManager.AddToRole(user.Id, "Users");
                    AccountInfoEvent($"Account wiht name:{user.UserName}; and id:{user.Id} has been successfuly registered");
                    return(View("SuccessfulRegistration", model));
                }
                else
                {
                    AddErrorsFromResult(result);
                }
            }
            return(View());
        }
Example #3
0
        public async Task <IActionResult> PostAsync([FromBody] CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                UserIdent user = new UserIdent {
                    Email = model.Email, UserName = model.Email, Year = model.Year
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    return(Ok(result));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(null);
        }
Example #4
0
        public async Task <IActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = new ApplicationUser {
                    Email = model.Email, UserName = model.Email, NickName = model.NickName, FirstName = model.FirstName
                };
                var result = await _um.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
Example #5
0
        public async Task <IActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {   //define the type of creation
                if (string.IsNullOrEmpty(model.CreatedBy))
                {
                    model.TypeOfCreation = TypeOfCreation.ByApp;
                }
                var result = await _service.AuthService.Register(model);

                if (!result)
                {
                    return(BadRequest(new ResponseBase {
                        Code = CodeResponse.DbError, Message = "Ocurrio un error intente de nuevo"
                    }));
                }
                return(Created(nameof(UserController.FindByUserName), new
                {
                    User = _mapper.Map <UserViewModel>(await _service.UserService.GetByUserName(model.UserName))
                }));
            }
            return(BadRequest(ModelState));
        }
 public bool UserCreation(CreateUserViewModel CreateUserViewModel)
 {
     using (SqlConnection tConnection = new SqlConnection(ConnectionString))
     {
         int IsAdmin;
         if (CreateUserViewModel.Admin == true)
         {
             IsAdmin = 1;
         }
         else
         {
             IsAdmin = 0;
         }
         SqlCommand tCommand = new SqlCommand("INSERT INTO [dbo].[Users] SELECT '" + CreateUserViewModel.Username + "', '" + CreateUserViewModel.Password + "', " + IsAdmin + ";", tConnection);
         tConnection.Open();
         int tRows = tCommand.ExecuteNonQuery();
         if (tRows > 0)
         {
             return(true);
         }
     }
     return(false);
 }
        public async Task <IActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = new User {
                    UserName = model.UserName, Email = model.Email, FullName = model.FullName, Birthday = model.Birthday, Adress = model.Adress
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
        public async Task <ActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName = model.Email,
                    Email    = model.Email
                };

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

                if (result.Succeeded)
                {
                    UserManager.AddToRole(user.Id, "User");

                    return(RedirectToAction("Index", "Account"));
                }
                AddErrors(result);
            }

            return(View(model));
        }
Example #9
0
        public async Task <IActionResult> Create([FromForm] CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                IdentityUser user = new IdentityUser {
                    UserName = model.UserName, Email = model.Email, PhoneNumber = model.Phone
                };
                var result = await _userManager.CreateAsync(user, model.Password).ConfigureAwait(true);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
Example #10
0
 public bool UpdateUser(CreateUserViewModel UpdateViewModel)
 {
     using (SqlConnection tConnection = new SqlConnection(ConnectionString))
     {
         int IsAdmin;
         if (UpdateViewModel.Admin == true)
         {
             IsAdmin = 1;
         }
         else
         {
             IsAdmin = 0;
         }
         SqlCommand tCommand = new SqlCommand("UPDATE [dbo].[Users] SET Username='******',Password='******',Admin='" + IsAdmin + "';", tConnection);
         tConnection.Open();
         int tRows = tCommand.ExecuteNonQuery();
         if (tRows > 0)
         {
             return(true);
         }
     }
     return(false);
 }
Example #11
0
        public IActionResult Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = new User();
                user.Name    = model.Name;
                user.Email   = model.Email;
                user.Address = model.Address;
                user.City    = model.City;
                user.Phone   = model.Phone;

                users.Add(user);
                int count = users.GetAll().Count();
                return(RedirectToAction("index"));
            }
            return(View());
            //public int ID { get; set; }
            //public string Name { get; set; }
            //public string Email { get; set; }
            //public string Address { get; set; }
            //public string City { get; set; }
            //public string Phone { get; set; }
        }
Example #12
0
        public async Task <IActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                IdentityUser user = new IdentityUser {
                    Email = model.Email, UserName = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(String.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
Example #13
0
        public async Task <IActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = new User {
                    Email = model.Email, UserName = model.Email, Year = model.Year, Famile = model.Famile, Name = model.Name, Phone = model.Phone, Address = model.Address, Papers = model.Papers, Policy = model.Policy
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
        public async Task <ActionResult> Create([Bind(Include = "UserName,FirstName,LastName,Email,Password,ConfirmPassword,Age")] CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var newUser = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, Age = model.Age
                };
                var result = await UserManager.CreateAsync(newUser);

                if (result.Succeeded)
                {
                    PasswordHasher ph = new PasswordHasher();
                    newUser.PasswordHash = ph.HashPassword(model.Password);
                    UserManager.AddToRole(newUser.Id, "Guest");

                    return(RedirectToAction("Index"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <ActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppUser user = new AppUser {
                    UserName = model.Name, Email = model.Email
                };
                IdentityResult result =
                    await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    AdminInfoEvent($"Account wiht name:{user.UserName}; and id:{user.Id} has been successfuly created");
                    return(RedirectToAction("Index"));
                }
                else
                {
                    AdminInfoEvent($"Account wiht name:{user?.UserName}; and id:{user?.Id} hasn't been successfuly created");
                    AddErrorsFromResult(result);
                }
            }
            return(View(model));
        }
Example #16
0
        public async Task <IActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = new User {
                    Email = model.Email, UserName = model.UserName, PhoneNumber = model.Phone
                };
                var result = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction("AllUsers", "Admin"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
Example #17
0
        public async Task <IActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userDto = mapper.Map <CreateUserViewModel, UserDTO>(model);
                var result  = await userServices.CreateUserAsync(userDto, model.Password);

                if (result.Succeeded)
                {
                    await userServices.AddToRoleAsync(userDto.Id);

                    return(RedirectToAction("Index"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
Example #18
0
        public async Task <ActionResult> Create(CreateUserViewModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                AppUser user = new AppUser
                {
                    UserName = model.Name,
                    Email    = model.Email
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    this.TempData["success"] = string.Format("Потребителя {0} беше създаден успешно.", model.Name);
                    return(RedirectToAction("Index"));
                }
                else
                {
                    AddErrorsFromResult(result);
                }
            }
            return(View(model));
        }
Example #19
0
        public int AddUserFromAdmin(CreateUserViewModel user)
        {
            User newUser = new User();

            newUser.Password     = PasswordHelper.EncodePasswordMd5(user.Password);
            newUser.UserName     = user.UserName;
            newUser.IsActive     = true;
            newUser.RegisterDate = DateTime.Now;
            newUser.ActiveCode   = NameGenerator.GenerateUniqCode();
            newUser.Email        = user.Email;
            //Save Image
            if (user.UserAvatar != null)
            {
                string imagePath = "";
                newUser.UserAvatar = NameGenerator.GenerateUniqCode() + Path.GetExtension(user.UserAvatar.FileName);
                imagePath          = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/UserAvatar", newUser.UserAvatar);
                using (var stream = new FileStream(imagePath, FileMode.Create))
                {
                    user.UserAvatar.CopyTo(stream);
                }
            }
            return(AddUser(newUser));
        }
Example #20
0
        public async Task <IActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = new ApplicationUser {
                    Email = model.Email, UserName = model.Email, FullName = model.FullName, PersonPhone = model.PersonPhone, RestaurantID = model.RestaurantID
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
Example #21
0
 public ActionResult Create()
 {
     try
     {
         SelectList rolesList = new SelectList(UserService.GetRoles());
         if (rolesList != null)
         {
             CreateUserViewModel model = new CreateUserViewModel {
                 Roles = rolesList
             };
             return(View(model));
         }
         else
         {
             throw new ArgumentException("Role list not found.");
         }
     }
     catch (Exception e)
     {
         ViewBag.ErrorInformation = e.Message;
         return(View("Error"));
     }
 }
Example #22
0
        public async Task <IActionResult> CreateUser(CreateUserViewModel model, [FromQuery] string returnurl)
        {
            if (!ModelState.IsValid)
            {
                return(ViewError(ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage)));
            }

            IdentityResult result = await _userManagerProvider.CreateUserAsync(model.Username, model.Password);

            if (result.Succeeded)
            {
                if (string.IsNullOrWhiteSpace(returnurl))
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(Redirect(returnurl));
                }
            }

            return(ViewError(result.Errors.Select(x => $"{x.Code} {x.Description}")));
        }
Example #23
0
        public async Task <IActionResult> Create([FromBody] CreateUserViewModel userViewModel)
        {
            try
            {
                var userDTO = _mapper.Map <UserDTO>(userViewModel);

                var userCreated = await _userService.Create(userDTO);

                return(Ok(new ResultViewModel {
                    Message = "Usuário criado com sucesso!",
                    Success = true,
                    Data = userCreated
                }));
            }
            catch (DomainException ex)
            {
                return(BadRequest(Responses.DomainErrorMessage(ex.Message, ex.Errors)));
            }
            catch (Exception)
            {
                return(StatusCode(500, Responses.ApplicationErrorMessage()));
            }
        }
Example #24
0
        public async Task <ActionResult> Register(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppUser user = new AppUser {
                    UserName = model.Name, PhoneNumber = model.PhoneNumber, Email = model.Email
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction("List", "Ad"));
                }
                else
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }
            return(View(model));
        }
Example #25
0
        public async Task <IActionResult> CreateUser(CreateUserViewModel vm)
        {
            if (ModelState.IsValid)
            {
                var newUser = new ApplicationUser()
                {
                    Nickname = vm.Nickname,
                    Email    = vm.Login,
                    UserName = vm.Login,
                };

                var result = await _userManager.CreateAsync(newUser, vm.Password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRolesAsync(newUser, vm.Roles);

                    return(RedirectToAction("Index"));
                }
            }

            return(RedirectToAction("Create", vm));
        }
Example #26
0
        public async Task <IActionResult> Create(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = new User()
                {
                    Name   = model.Name, FirstName = model.FirstName, LastName = model.LastName,
                    Gender = model.Gender, UserName = model.Email, Email = model.Email
                };
                if (model.Avatar != null)
                {
                    byte[] imageData = null;
                    // read the transferred file into a byte array
                    using (var binaryReader = new BinaryReader(model.Avatar.OpenReadStream()))
                    {
                        imageData = binaryReader.ReadBytes((int)model.Avatar.Length);
                    }
                    // setting a byte array
                    user.Avatar = imageData;
                }

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

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
        public static async Task ProcessRepositories(string jsondetails, int id)
        {
            var                 client = new HttpClient();
            DataSeed            obj    = new DataSeed();
            CreateUserViewModel obj1   = new CreateUserViewModel();

            obj1.encodingType = "UTF8";
            TagViewModel obj2 = new TagViewModel();

            obj2.type     = "PLAIN_TEXT";
            obj2.content  = jsondetails;
            obj1.document = obj2;

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            object query      = "";
            var    stringTask = await client.PostAsync("https://language.googleapis.com/v1/documents:analyzeSyntax?key=AIzaSyCLtrTyOeWbLLF6DqQVkP3VHa2y7yoToJE", new StringContent(JsonConvert.SerializeObject(obj1), Encoding.UTF8, "application/json"));

            var msg = stringTask.Content.ReadAsStringAsync().Result;

            //jsonToCSV(msg,id);

            Console.Write(msg);

            RootObject ao = JsonConvert.DeserializeObject <RootObject>(msg);

            foreach (var xyz in ao.tokens)
            {
                if (xyz.partOfSpeech.tag == "NOUN" || xyz.partOfSpeech.tag == "VERB" || xyz.partOfSpeech.tag == "ADJ")
                {
                    Console.WriteLine(xyz.text.content);
                    getsynonyms(xyz.text.content, id);
                }
            }
        }
Example #28
0
        public async Task <IActionResult> Create(CreateUserViewModel createUserViewModel)
        {
            try
            {
                string userRole = LocalStorageExtensions.Get(StorageType.Role);
                if (userRole == "Company")
                {
                    createUserViewModel.UserRole  = "Shop";
                    createUserViewModel.CompanyId = 0;
                }
                createUserViewModel.Picture   = createUserViewModel.base64Picture;
                createUserViewModel.CreatedBy = LocalStorageExtensions.Get(StorageType.UserId);

                string response = await APICallerExtensions.APICallAsync("User/Create", createUserViewModel, false, HttpContext.Session.GetObject(StorageType.Token).ToString());

                if (response.ToLower().Contains("exception:"))
                {
                    ModelState.AddModelError(string.Empty, response);
                    return(RedirectToAction(nameof(UserController.Index), "User"));
                }
                var content = JsonConvert.DeserializeObject <SingleResponse <CreateUserViewModel> >(response);
                if (!content.DidError)
                {
                    return(RedirectToAction(nameof(UserController.Index), "User"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, content.Message);
                    return(RedirectToAction(nameof(UserController.Index), "User"));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
                return(RedirectToAction(nameof(UserController.Index), "User"));
            }
        }
 public ActionResult Add(CreateUserViewModel newUser)
 {
     using (var db = new DataContext())
     {
         if (ModelState.IsValid)
         {
             var store   = new UserStore <User>(db);
             var manager = new ApplicationUserManager(store);
             var user    = new User
             {
                 UserName     = newUser.UserName,
                 Firstname    = newUser.Firstname,
                 Surname      = newUser.Surname,
                 Email        = newUser.Email,
                 Domain       = newUser.Domain,
                 PasswordHash = newUser.PasswordHash,
                 PhoneNumber  = newUser.PhoneNumber,
                 Experience   = newUser.Experience,
                 EmployedDate = newUser.EmployedDate,
                 Address      = newUser.Address
             };
             db.Users.Add(user);
             manager.Create(user, user.PasswordHash);
             manager.AddToRole(user.Id, newUser.SelectedRole);
             db.SaveChanges();
             TempData["Message"] = user.Firstname + " was successfully added!";
             TempData["Type"]    = "alert-success";
             return(RedirectToAction("Index"));
         }
         else
         {
             TempData["Message"] = "Something went wrong!";
             TempData["Type"]    = "alert-danger";
             return(RedirectToAction("Add"));
         }
     }
 }
Example #30
0
        public IActionResult SignUp(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppUser user = new AppUser
                {
                    Email    = model.Email,
                    UserName = model.Name
                };

                var result = userManager.CreateAsync(user, model.Password).Result;

                if (result.Succeeded)
                {
                    var result2 = userManager.AddToRoleAsync(user, "user").Result;
                    if (result2.Succeeded)
                    {
                        return(RedirectToAction("Login"));
                    }
                    else
                    {
                        foreach (var item in result2.Errors)
                        {
                            ModelState.AddModelError(item.Code, item.Description);
                        }
                    }
                }
                else
                {
                    foreach (var item in result.Errors)
                    {
                        ModelState.AddModelError(item.Code, item.Description);
                    }
                }
            }
            return(View(model));
        }
Example #31
0
        public async Task <IActionResult> SignUp(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                // creates a new appuser using the information provided
                // in the singup form
                AppUser user = new AppUser
                {
                    UserName = model.UserName,
                    Email    = model.Email
                };
                if (model.Name != null)
                {
                    user.Name = model.Name;
                }

                // Ties user to the password
                IdentityResult result =
                    await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // Adds the user to the Users role
                    await userManager.AddToRoleAsync(user, "Users");

                    return(RedirectToAction("Index"));
                }
                else
                {
                    foreach (IdentityError error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }
            return(View(model));
        }
Example #32
0
        public ActionResult CreateUser(CreateUserViewModel model)
        {
            // skillnaderna mellan en vymodel såsom LoginViewModel och en FormCollection
            //LoginViewModel Model = new LoginViewModel();
            //
            //if (!ModelState.IsValid)
            //{
            //    // här händer nåt
            //}
            //
            //var epost = Model.Email;
            //var password = Model.Password;
            //bool Remember = Model.RememberMe;
            //
            // med en vymodel så sköter MVC mycket själv.
            // t.ex. denna validering kan lätt ändras till en enkel
            // if (!ModelState.IsValid) {
            // så kontrollerar den ifall vymodel EJ är giltig och sedan får programmeraren
            // göra det som skall, t.ex. skicka tillbaka datat och felmedellandena ( som
            // även sköts av vymodelen )
            //epost = Collection["email"];
            //if (epost.Length > 9)
            //{
            //    // OK
            //}
            //password = Collection["password"];
            //if (password.Length > 9)
            //{
            //    // OK
            //}
            //if (Boolean.TryParse(Collection["RememberMe"], out Remember))
            //{
            //    // OK
            //}
            Menu(Home: true);
            SetBreadcrumbs(
                one: new MenyItem { Link = "~/Teacher/", Text = "Se alla kurser" });

            if (!ModelState.IsValid)
            {
                return View(model);
            }

            bool HasError = false;
            if (model.Password != model.ConfirmPassword)
            {
                ModelState.AddModelError("ConfirmPassword", "Det konfirmerande lösenordet är ej detsamma som lösenordet du har angett");
                HasError = true;
            }
            if (model.Role != "Teacher" && model.Role != "Student")
            {
                ModelState.AddModelError("Role", "Användare kan enbart vara av roll lärare eller elev");
                HasError = true;
            }
            if (HasError)
            {
                return View(model);
            }

            var uStore = new UserStore<User>(db);
            var uManager = new UserManager<User>(uStore);

            User user = new User { FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, UserName = model.Email };
            uManager.Create(user, model.Password);

            user = uManager.FindByName(model.Email);
            uManager.AddToRole(user.Id, model.Role);

            return Redirect("~/Teacher/");
        }
Example #33
0
        public async Task<ActionResult> Create(CreateUserViewModel userViewModel, params string[] selectedRoles)
        {
            if (ModelState.IsValid)
            {
                // 获取注册登录配置文件
                AccountSecurityConfig _accountSecurity = WebConfigurationManager.OpenWebConfiguration("~").GetSection("AccountSecurityConfig") as AccountSecurityConfig;
                
                var user = new ApplicationUser
                {
                    UserName = userViewModel.UserName,
                    Email = userViewModel.Email,
                    EmailConfirmed = userViewModel.EmailConfirmed,
                    PhoneNumber = userViewModel.PhoneNumber,
                    PhoneNumberConfirmed = userViewModel.PhoneNumberConfirmed,
                    Created = DateTime.Now,
                    LockoutEnabled = _accountSecurity.EnableLockout,
                    Credits = 0,
                    Money = 0.00M
                };
                var adminresult = await UserManager.CreateAsync(user, userViewModel.Password);
                //adminresult = await UserManager.SetLockoutEnabledAsync(user.Id, false);

                if (adminresult.Succeeded)
                {
                    if (selectedRoles != null)
                    {
                        string[] roles = new string[selectedRoles.Length];
                        for (int i = 0; i < selectedRoles.Length; i++)
                        {
                            roles[i] = (await RoleManager.FindByIdAsync(int.Parse(selectedRoles[i]))).Name;
                        }
                        var result = await UserManager.AddToRolesAsync(user.Id, roles);
                        if (!result.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First());
                            ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Id", "Name");
                            return View();
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First());
                    ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Id", "Name");
                    return View();
                }
                return RedirectToAction("Index");
            }
            ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Id", "Name");
            return View();
        }
Example #34
0
 public ActionResult Create(CreateUserViewModel model)
 {
     try
     {
         _adminService.CreateUser(model);
         return RedirectToAction("Index");
     }
     catch
     {
         ModelState.AddModelError(string.Empty, "Что-то пошло не так. Попробуйте ещё раз!");
         return View(model);
     }
 }