示例#1
0
        public async Task <IActionResult> Create([FromBody] User user)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(user);
                    await _context.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }

            return(Ok(user));
        }
示例#2
0
        public async Task <IActionResult> CheckOrCreate(string phone)
        {
            //TBD 做手机号的格式认证
            var user = await _userContext.Users.SingleOrDefaultAsync(u => u.Phone == phone);

            if (user == null)
            {
                user = new AppUser()
                {
                    Phone = phone
                };
                _userContext.Add(user);
                await _userContext.SaveChangesAsync();
            }

            return(Ok(new { UserId = user.Id, user.Name, user.Company, user.Title, user.Avatar }));
        }
        public async Task <IActionResult> Patch([FromBody] JsonPatchDocument <Model.AppUser> patch)
        {
            /*
             *         {
             *             "op":"replace",
             *             "path":"/Company",
             *             "value":"adminA"
             *         }
             */
            var user = await _userContext.Users.SingleOrDefaultAsync(u => u.Id == UserIdentity.UserId);

            patch.ApplyTo(user);


            foreach (var property in user?.Properties)
            {
                _userContext.Entry(property).State = EntityState.Detached;
            }

            var originProperties = await _userContext.UserProperty.AsNoTracking().Where(u => u.AppUserId == UserIdentity.UserId).ToListAsync();

            //合并,去重
            var allProperties = originProperties.Union(user.Properties).Distinct();
            //这里的意思是strList1中哪些是strList2中没有的,并将获得的差值存放在strList3(即: strList1中有, strList2中没有)
            var removedProperties = originProperties.Except(user.Properties);
            var newProperties     = allProperties.Except(originProperties);

            foreach (var property in removedProperties)
            {
                _userContext.Remove(property);
            }
            foreach (var item in newProperties)
            {
                _userContext.Add(item);
            }
            using (var transaction = _userContext.Database.BeginTransaction())
            {
                _userContext.Users.Update(user);
                await _userContext.SaveChangesAsync();

                //发布用户变更消息
                RaiseUserprofileChanagedEvent(user);
                transaction.Commit();
            }
            return(Json(user));
        }
示例#4
0
        public async Task CreateRequestForCommandAsync <T>(Guid id)
        {
            var exists = await ExistAsync(id);

            var request = exists ?
                          throw new UserDomainException($"Request with {id} already exists") :
                                new ClientRequest()
                                {
                                    Id   = id,
                                    Name = typeof(T).Name,
                                    Time = DateTime.UtcNow
                                };

            _context.Add(request);

            await _context.SaveChangesAsync();
        }
示例#5
0
        public IActionResult reg(Person person, string ConfirmPass)
        {
            if (ModelState.IsValid && ConfirmPass == person.Password)
            {
                PasswordHasher <Person> Hasher = new PasswordHasher <Person>();
                person.Password = Hasher.HashPassword(person, person.Password);
                _context.Add(person);
                _context.SaveChanges();


                return(View("Account", person));
            }
            else
            {
                return(View("Index"));
            }
        }
示例#6
0
 public async Task<IActionResult> Post(User user)
 {
     Random rnd = new Random();
     int img = rnd.Next(0, 70);
     user.Image = $"https://i.pravatar.cc/300?img={img}";
     var validate = _userValidator.Validate(user);
     if (validate.IsValid)
     {
         var slave = await _user.User.FirstOrDefaultAsync(x => x.EMail == user.EMail || x.DocumentNumber == user.DocumentNumber);
         if (slave != null)
             return BadRequest(new { message = "Usuario ya existe." });
         _user.Add(user);
         _user.SaveChanges();
         return StatusCode(200);
     }
     return BadRequest(new { message = validate.Errors });
 }
        public async Task <IActionResult> Create([Bind("userId,name,password,Email,phnNumber")] UserLogIn userLogIn)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userLogIn);


                var studentsList = await _context.StudentsLists
                                   .FirstOrDefaultAsync(m => m.studentname == userLogIn.name);


                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(userLogIn));
        }
示例#8
0
        public IActionResult AddUser([FromServices] UserContext dbcontext, string name, string email, string gender, string date, string days, string addReq)
        {
            User addUser = new User()
            {
                Id             = Guid.NewGuid().ToString(),
                Name           = name,
                Email          = email,
                Gender         = gender,
                RegisteredDate = date,
                SelectedDays   = days,
                AddRequest     = addReq
            };

            dbcontext.Add(addUser);
            dbcontext.SaveChanges();

            return(RedirectToAction("RegisteredList", "Home"));
        }
 public IActionResult newUser(User newUser)
 {
     if (ModelState.IsValid)
     {
         PasswordHasher <User> Hasher = new PasswordHasher <User>();
         newUser.Password         = Hasher.HashPassword(newUser, newUser.Password);
         newUser.confirm_password = Hasher.HashPassword(newUser, newUser.confirm_password);
         _context.Add(newUser);
         _context.SaveChanges();
         Console.WriteLine("Form Accepted.");
         return(RedirectToAction("Index"));
     }
     else
     {
         Console.WriteLine("Form was not Accepted.");
         return(View("Index"));
     }
 }
 public IActionResult Create(Register user)
 {
     if (ModelState.IsValid)
     {
         bool EmailMatch = _context.Users.Where(x => x.Email == user.Email).Any();
         if (EmailMatch)
         {
             ModelState.AddModelError("Email", "Registered user with email " + user.Email + " already exists.");
             return(View("Index"));
         }
         User NewUser = new User(user);
         _context.Add(NewUser);
         _context.SaveChanges();
         HttpContext.Session.SetInt32("UserId", NewUser.UserId);
         return(RedirectToAction("Index", "Idea"));
     }
     return(View("Index"));
 }
示例#11
0
        public async Task <IActionResult> AdicionarOuEditar([Bind("Id,Nome,Cpf,Telefone")] Usuario usuario)
        {
            if (ModelState.IsValid)
            {
                if (usuario.Id == 0)
                {
                    _context.Add(usuario);
                }
                else
                {
                    _context.Update(usuario);
                }
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(usuario));
        }
        public void Given_A_UserRepository_When_I_Call_DeleteUser_Then_A_User_Should_Be_Deleted()
        {
            // Arrange
            var user    = _fixture.Create <User>();
            var options = new DbContextOptionsBuilder <UserContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;
            var context         = new UserContext(options);
            var usersRepository = new UsersRepository(context, _propertyMappingService);

            context.Add(user);
            // Act
            usersRepository.DeleteUser(user);
            usersRepository.Save();

            // Assert
            Assert.Equal(0, context.Users.Count());
        }
示例#13
0
        public async Task <IActionResult> AddOrEdit([Bind("UserId,FullName,RFIDCode,Access,Department")] User user)
        {
            if (ModelState.IsValid)
            {
                if (user.UserId == 0)
                {
                    _context.Add(user);
                }
                else
                {
                    _context.Update(user);
                }
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(user));
        }
示例#14
0
        public async Task <IActionResult> Create(int?id, [Bind("Score,Description,Choice1,Choice2,Choice3,Choice4,CorrectChoiceID")] Problem problem)
        {
            if (id == null)
            {
                return(NotFound());
            }
            problem.SectionID = Convert.ToInt32(id);
            if (ModelState.IsValid)
            {
                _context.Add(problem);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Problems", "Sections", new { id = id }));
            }
            //ViewData["SectionID"] = new SelectList(_context.Sections, "ID", "ID", problem.SectionID);
            ViewData["SectionID"] = id;
            return(View(problem));
        }
示例#15
0
        public async Task <IActionResult> Patch([FromBody] JsonPatchDocument <AppUser> patch)
        {
            var user = await _userContext.Users.
                       SingleOrDefaultAsync(u => u.Id == UserIdentity.UserId);

            patch.ApplyTo(user);

            foreach (var property in user.Properties)
            {
                _userContext.Entry(property).State = EntityState.Detached;
            }

            var originProperties = await _userContext.UserProperties.AsNoTracking().
                                   Where(u => u.AppUserId == UserIdentity.UserId).ToListAsync(); //原有的

            var allProperties = originProperties.Union(user.Properties).Distinct();              //原有的和现在的并集去重

            var removedProperties = originProperties.Except(user.Properties);
            var newProperties     = allProperties.Except(originProperties);

            foreach (var property in removedProperties)
            {
                _userContext.Remove(property);
            }

            foreach (var property in newProperties)
            {
                _userContext.Add(property);
            }

            //事务
            using (var transaction = _userContext.Database.BeginTransaction())
            {
                //发布用户变更的消息
                RaiseUserprofileChangedEvent(user);

                _userContext.Users.Update(user);
                _userContext.SaveChanges();

                transaction.Commit();
            }

            return(Json(user));
        }
示例#16
0
        public async Task <IActionResult> Patch([FromBody] JsonPatchDocument <Models.AppUser> patch)//Json请求,需要加FromBody
        {
            var user = await _userContext.Users
                       // .Include(o=>o.Properties) 导致获取的修改前的Properties与修改后的Properties内容相同
                       .SingleOrDefaultAsync(u => u.Id == UserIdentity.UserId);

            patch.ApplyTo(user);

            foreach (var property in user?.Properties)
            {
                _userContext.Entry(property).State = EntityState.Detached;//全部设置为不跟踪,这种通过postman等传递过来的数据的状态不和EF的状态相关的
            }

            //var originProperties = user.Properties;//通过这种方法,导致获取的originProperties与修改后的内容相同

            var originProperties = await _userContext.UserProperties
                                   //.AsNoTracking() //不取消,将导致在调用Remove方法时,抛出异常(The instance of entity type 'UserProperty' cannot be tracked because another instance with the same key value for {'Key', 'AppUserId', 'Value'} is already being tracked.)
                                   .Where(u => u.AppUserId == UserIdentity.UserId).ToListAsync();

            var allProperties = originProperties.Union(user.Properties).Distinct();

            var removeProperties = originProperties.Except(user.Properties);
            //var newProperties = allProperties.Except(user.Properties);
            var newProperties = allProperties.Except(originProperties);

            foreach (var property in removeProperties)
            {
                //_userContext.Entry(property).State = EntityState.Deleted;

                _userContext.Remove(property);
            }

            foreach (var property in newProperties)
            {
                //_userContext.Entry(property).State = EntityState.Added;

                _userContext.Add(property);
            }

            _userContext.Users.Update(user);
            _userContext.SaveChanges();

            return(Json(user));
        }
示例#17
0
 public IActionResult CreateAuction(AuctionViewModel MyAuction)
 {
     if (ModelState.IsValid)
     {
         Auction NewAuction = new Auction {
             Name        = MyAuction.Name,
             Description = MyAuction.Description,
             StartingBid = MyAuction.StartingBid,
             EndDate     = MyAuction.EndDate,
             CreatorId   = (int)HttpContext.Session.GetInt32("CurId"),
             HighestBid  = MyAuction.StartingBid,
             BidderId    = (int)HttpContext.Session.GetInt32("CurId")
         };
         _context.Add(NewAuction);
         _context.SaveChanges();
         return(RedirectToAction("Dashboard"));
     }
     return(View("NewAuction"));
 }
        public void Given_A_UserRepository_When_I_Call_GetUser_Passing_A_userId_Then_A_User_Should_Be_Returned()
        {
            // Arrange
            var user    = _fixture.Create <User>();
            var options = new DbContextOptionsBuilder <UserContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;
            var context         = new UserContext(options);
            var usersRepository = new UsersRepository(context, _propertyMappingService);

            context.Add(user);
            context.SaveChanges();
            // Act

            var xd = usersRepository.GetUser(user.Id);

            // Assert
            Assert.True(xd.Id == user.Id);
        }
示例#19
0
        public void Setting_IsModified_should_not_be_dependent_on_other_properties()
        {
            Guid id;

            using (var context = new UserContext())
            {
                id = context.Add(
                    new User
                {
                    Name     = "A",
                    LongName = "B"
                }).Entity.Id;

                context.SaveChanges();
            }

            using (var context = new UserContext())
            {
                var user = context.Attach(
                    new User
                {
                    Id       = id,
                    Name     = "NewA",
                    LongName = "NewB"
                }).Entity;

                context.Entry(user).Property(x => x.Name).IsModified     = false;
                context.Entry(user).Property(x => x.LongName).IsModified = true;

                Assert.False(context.Entry(user).Property(x => x.Name).IsModified);
                Assert.True(context.Entry(user).Property(x => x.LongName).IsModified);

                context.SaveChanges();
            }

            using (var context = new UserContext())
            {
                var user = context.Find <User>(id);

                Assert.Equal("A", user.Name);
                Assert.Equal("NewB", user.LongName);
            }
        }
示例#20
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName  = model.UserName.ToLower(), Email = model.Email,
                    FirstName = model.FirstName, LastName = model.LastName
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    // Add a user to the default role, or any role you prefer here
                    await _userManager.AddToRoleAsync(user, "Member");

                    var profile = new UserProfile
                    {
                        UserId = user.Id
                    };

                    _userContext.Add(profile);
                    await _userContext.SaveChangesAsync();

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation("User created a new account with password.");
                    return(RedirectToLocal(returnUrl));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#21
0
        public IActionResult Create(User user)
        {
            // checks sanitization from Model
            if (ModelState.IsValid)
            {
                // Checks to see if there is a duplicate email address
                if (dbContext.Users.Any(u => u.Email == user.Email))
                {
                    // Manually adds a ModelState error to the Email field
                    ModelState.AddModelError("Email", "Email already in use!");
                    return(View("Register"));
                }
                else
                {
                    // Sets DateTime variable for DB addition
                    user.CreatedAt = DateTime.Now;
                    user.UpdatedAt = DateTime.Now;

                    // Hashes password
                    PasswordHasher <User> Hasher = new PasswordHasher <User>();
                    user.Password = Hasher.HashPassword(user, user.Password);

                    // Adds user to the DB.
                    dbContext.Add(user);
                    dbContext.SaveChanges();

                    // Creates 'Logged In' status, with security validation.
                    // Each route can now check to see if the User is logged in using
                    // session data to validate a query to the DB. If the email does
                    // not match the email for the user id, then session will be cleared.
                    HttpContext.Session.SetString("LoggedIn", "Yes");
                    HttpContext.Session.SetInt32("UserId", user.UserId);
                    HttpContext.Session.SetString("Email", user.Email);

                    return(RedirectToAction("Success"));
                }
            }
            else
            {
                return(View("Register"));
            }
        }
示例#22
0
        public void Setting_IsModified_is_not_reset_by_OriginalValues()
        {
            Guid id;

            using (var context = new UserContext())
            {
                id = context.Add(
                    new User
                {
                    Id       = Guid.NewGuid(),
                    Name     = "A",
                    LongName = "B"
                }).Entity.Id;

                context.SaveChanges();
            }

            using (var context = new UserContext())
            {
                var user = context.Update(
                    new User
                {
                    Id = id
                }).Entity;

                user.Name     = "A2";
                user.LongName = "B2";

                context.Entry(user).Property(x => x.Name).IsModified = false;
                Assert.False(context.Entry(user).Property(x => x.Name).IsModified);

                context.SaveChanges();
            }

            using (var context = new UserContext())
            {
                var user = context.Find <User>(id);

                Assert.Equal("A", user.Name);
                Assert.Equal("B2", user.LongName);
            }
        }
示例#23
0
        public RedirectToActionResult Register(User newUser)
        {
            if (ModelState.IsValid)
            {
                if (dbContext.Users.Any(u => u.Email == newUser.Email))
                {
                    ModelState.AddModelError("Email", "Email is already in use");
                    return(RedirectToAction("Index"));
                }

                PasswordHasher <User> Hasher = new PasswordHasher <User>();
                newUser.Password = Hasher.HashPassword(newUser, newUser.Password);
                dbContext.Add(newUser);
                dbContext.SaveChanges();
                HttpContext.Session.SetInt32("InSession", newUser.UserId);
                return(RedirectToAction("Success"));
            }

            return(RedirectToAction("Index"));
        }
示例#24
0
 public IActionResult ProccessRegister(User formData)
 {
     Console.WriteLine(new string('-', 80));
     if (ModelState.IsValid)
     {
         if (dbContext.Users.Any(u => u.Email == formData.Email))
         {
             ModelState.AddModelError("Email", "Email already in use!");
             return(View("Register"));
         }
         PasswordHasher <User> Hasher = new PasswordHasher <User>();
         formData.Password = Hasher.HashPassword(formData, formData.Password);
         dbContext.Add(formData);
         dbContext.SaveChanges();
         User registeredUser = dbContext.Users.FirstOrDefault(u => u.Email == formData.Email);
         HttpContext.Session.SetInt32("UserId", (int)registeredUser.UserId);
         return(RedirectToAction("Success"));
     }
     return(View("Register"));
 }
示例#25
0
        public async Task InsertAsync(User obj)
        {
            //var HasEmail = await EmailExists(obj);

            //if (HasEmail)
            // {
            //  throw new NotImplementException("Email já cadastrado");
            //}
            try
            {
                _context.Add(obj);
                await _context.SaveChangesAsync();
            }
            catch (NotImplementException)
            {
                throw new NotImplementException("Email existente, tente um novo email.");
            }

            // return NoContent();
        }
示例#26
0
        public long CreateUser(User user)
        {
            if (user.nick == "" || user.nick == null || user.password == "" || user.password == null)
            {
                return(-2);
            }
            IEnumerable <User> temp_u = context.users.Where(t_u => t_u.nick == user.nick);

            if (temp_u.Count() == 0)
            {
                mutex.WaitOne();
                context.Add(user);
                context.SaveChanges();
                var u = context.users.Where(t_u => t_u.nick == user.nick).First();
                mutex.ReleaseMutex();
                return(u.id);
            }
            //重名
            return(-1);
        }
    public static void Required_properties_validated_with_in_memory_database()
    {
        Console.WriteLine($">>>> Sample: {nameof(Required_properties_validated_with_in_memory_database)}");
        Console.WriteLine();

        using var context = new UserContext();

        context.Add(new User());

        try
        {
            context.SaveChanges();
        }
        catch (Exception e)
        {
            Console.WriteLine($"{e.GetType().FullName}: {e.Message}");
        }

        Console.WriteLine();
    }
 public IActionResult NewUser(LoginRegViewModel model)
 {
     if (ModelState.IsValid)
     {
         User user = new User()
         {
             FirstName = model.Register.FirstName,
             LastName  = model.Register.LastName,
             Email     = model.Register.Email
         };
         PasswordHasher <User> Hasher = new PasswordHasher <User>();
         user.Password = Hasher.HashPassword(user, model.Register.Password);
         _context.Add(user);
         _context.SaveChanges();
         User currUser = _context.Users.SingleOrDefault(p => p.Email == user.Email);
         HttpContext.Session.SetInt32("LoggedInUser", currUser.Id);
         return(RedirectToAction("Index", "Activity"));
     }
     return(View("Index"));
 }
示例#29
0
 public IActionResult Register(RegisterViewModel user)
 {
     if (ModelState.IsValid)
     {
         PasswordHasher <User> Hasher = new PasswordHasher <User>();
         User newUser = new User {
             FirstName = user.FirstName, LastName = user.LastName, Email = user.Email,
         };
         newUser.Password = Hasher.HashPassword(newUser, user.Password);
         _context.Add(newUser);
         _context.SaveChanges();
         User logUser = _context.Users.SingleOrDefault(u => u.Email == user.Email);
         HttpContext.Session.SetInt32("UserId", logUser.UserId);
         return(RedirectToAction("List", "Wedding"));
     }
     else
     {
         return(View("Register"));
     }
 }
示例#30
0
        public IActionResult RegisterUser(User MyUser, string ConfirmPassword)
        {
            System.Console.WriteLine("WE HIT REGISTERED USER FUNCTION IN CONTROLLER");
            if (MyUser.Password != ConfirmPassword)
            {
                System.Console.WriteLine("\n****************Passwords dont match****************\n\n");
                ViewBag.PasswordError = $"{MyUser.FirstName} I know this must be hard for you, but lets try writing matching passwords this time.";
                return(View("Index"));
            }

            if (ModelState.IsValid)
            {
                PasswordHasher <User> Hasher = new PasswordHasher <User>();
                MyUser.Password = Hasher.HashPassword(MyUser, MyUser.Password);
                User ExistingUser = _context.users.SingleOrDefault(u => u.Email == MyUser.Email);
                if (ExistingUser != null)
                {
                    System.Console.WriteLine(" *************EMAIL ALREADY IN USE**********************");
                    ViewBag.AlreadyInUseEmail = true;
                    // ViewBag.AlreadyInUseEmail = $"{MyUser.Email} is already in the Data base, YOU F**K!";
                    return(View("Index"));
                    // Yo dude Have you ever watched Mike Tyson Mysteries? Its really good show.
                }
                else
                {
                    MyUser.Wallet = 1000.00f;
                    _context.Add(MyUser);
                    _context.SaveChanges();
                    // grabs all reviews from database
                    User results = _context.users.SingleOrDefault(u => u.Email == MyUser.Email);
                    int  userid  = results.idUsers;
                    HttpContext.Session.SetInt32("logged_id", userid);
                    return(RedirectToAction("Success"));
                }
            }
            else
            {
                System.Console.WriteLine("There were errors adding user returned to index********************");
                return(View("Index"));
            }
        }