public IHttpActionResult Post(UserAdminBindingModel entity) { _traceSource.TraceInformation("userscontroller post"); Guard.Against<ArgumentException>(entity == null, "entity cannot be empty"); Guard.Against<ArgumentException>(!string.IsNullOrEmpty(entity.Id), "entity.id must be empty"); Guard.Against<ArgumentException>(string.IsNullOrEmpty(entity.UserName), "entity.userName cannot be empty"); Guard.Against<ArgumentException>(string.IsNullOrEmpty(entity.Password), "entity.password cannot be empty"); var user = Map(entity); if (_userService.Exists(user.UserName)) return BadRequest(string.Format("user with name {0} already exists", user.UserName)); var result = _userService.CreateUser(user, entity.Password); // add the roles if(result.Succeeded && !string.IsNullOrEmpty(entity.Roles)) foreach(var role in entity.Roles.Split(' ')) _userService.AddUserToRole(user, role); else return BadRequest(string.Format("errors: {0}", string.Join(", ", result.Errors))); // set the other properties if (entity.ActiveFrom != null) user.ActiveFromDate = entity.ActiveFrom.Value; if (entity.ActiveTill != null) user.ActiveTillDate = entity.ActiveTill.Value; if (!string.IsNullOrEmpty(entity.Organization)) user.Organization = entity.Organization; _userService.UpdateUser(user); return Created("http://acme.com/users/" + user.Id, user); }
private User Map(UserAdminBindingModel source) { return new User { Id = !string.IsNullOrEmpty(source.Id) ? new Guid(source.Id) : Guid.Empty, UserName = source.UserName, Organization = source.Organization, Email = source.Email, Active = source.Active }; }
public IHttpActionResult Put(string id, UserAdminBindingModel entity) { _traceSource.TraceInformation("usersscontroller put"); Guard.Against<ArgumentException>(entity == null, "entity cannot be empty"); Guard.Against<ArgumentException>(string.IsNullOrEmpty(entity.Id) && string.IsNullOrEmpty(id), "entity.id or id must be set"); if (string.IsNullOrEmpty(entity.Id) && !string.IsNullOrEmpty(id)) entity.Id = id; if (!_context.Users.Has(entity.Id)) return StatusCode(HttpStatusCode.NotFound); var user = Map(entity); var entry = _context.Entry(user); if (entry.State == EntityState.Detached) { _context.Users.Attach(user); entry.State = EntityState.Modified; } _context.SaveChanges(); // update the password if it is provided if (!string.IsNullOrEmpty(entity.Password)) _userService.UpdatePassword(user.Id, entity.Password); // update the roles _userService.ClearUserRoles(user); foreach (var role in entity.Roles.NullToEmpty().Split(' ')) _userService.AddUserToRole(user, role); // update the other properties if (entity.ActiveFrom != null) user.ActiveFromDate = entity.ActiveFrom.Value; else user.ActiveFromDate = null; if (entity.ActiveTill != null) user.ActiveTillDate = entity.ActiveTill.Value; else user.ActiveTillDate = null; user.Organization = entity.Organization; _userService.UpdateUser(user); return Ok(user); }