public async Task <IActionResult> Index(SortFilterBirdIndexOptions options) { if (!ModelState.IsValid) { var errors = ModelStateErrorsExtensions.GetModelStateErrorMessages(ModelState); return(BadRequest(errors)); } if (options.Page == 0) { options.Page = 1; } try { var viewModel = new BirdIndexViewModel(); viewModel.AllBirdsDropDownList = await _context.Bird.ToListAsync(); viewModel.BirdsList = await _context.Bird.AsNoTracking().GetPaged(options.Page, pageSize); viewModel.ShowAll = options.ShowAll; viewModel.ShowInTable = options.ShowInTable; return(View(viewModel)); } catch (Exception ex) { return(NotFound()); } }
public async Task <IActionResult> CreateObservationAsync(ObservationAddDto model) { try { var requestingUser = await _userManager.FindByNameAsync(User.Identity.Name); if (requestingUser is null) { _logger.LogError(LoggingEvents.GetItem, "requesting user not found"); return(StatusCode(500, "requesting user not found")); } var observedBirdSpecies = await _birdRepository.GetBirdAsync(model.Bird.BirdId); if (observedBirdSpecies is null) { string message = $"Bird species with id '{model.BirdId}' was not found."; _logger.LogError(LoggingEvents.GetItem, message); return(StatusCode(500, message)); } // date from client model is already Utc.... // model.ObservationDateTime = model.ObservationDateTime.ToLocalTime(); // var x = model.ObservationDateTime; // var y = model.ObservationDateTime = model.ObservationDateTime.ToLocalTime(); // var z = model.ObservationDateTime = model.ObservationDateTime.ToUniversalTime(); var observation = _mapper.Map <ObservationAddDto, Observation>(model); DateTime createdDate = _systemClock.GetNow; observation.ApplicationUser = requestingUser; observation.Bird = observedBirdSpecies; observation.CreationDate = createdDate; observation.LastUpdateDate = createdDate; //rerun validation on observation model if (!TryValidateModel(observation, nameof(observation))) { _logger.LogError(LoggingEvents.UpdateItem, "Observation model state is invalid: " + ModelStateErrorsExtensions.GetModelStateErrorMessages(ModelState)); return(StatusCode(500, "observation ModelState is invalid")); } _observationPositionRepository.Add(observation.Position); _observationRepository.Add(observation); _observationNoteRepository.AddRange(observation.Notes); await _unitOfWork.CompleteAsync(); return(CreatedAtAction(nameof(CreateObservationAsync), _mapper.Map <Observation, ObservationDto>(observation))); } catch (Exception ex) { _logger.LogError(LoggingEvents.GetListNotFound, ex, "An error occurred creating an observation."); return(StatusCode(500, "an unexpected error occurred")); } }
public async Task <IActionResult> PutObservationAsync(int id, ObservationEditDto model) { try { if (id != model.ObservationId) { _logger.LogError(LoggingEvents.UpdateItem, $"Id '{id}' not equal to model id '{model.ObservationId}'"); return(BadRequest("An error occurred (id)")); } var observation = await _observationRepository.GetObservationAsync(id, false); if (observation is null) { string message = $"observation with id '{model.ObservationId}' was not found."; _logger.LogError(LoggingEvents.UpdateItem, message); return(StatusCode(500, message)); } var username = User.Identity.Name; if (username != observation.ApplicationUser.UserName) { return(Unauthorized("Requesting user is not allowed to edit this observation")); } // date from client model is already Utc.... // model.ObservationDateTime = model.ObservationDateTime.ToLocalTime(); // var x = model.ObservationDateTime; // var y = model.ObservationDateTime = model.ObservationDateTime.ToLocalTime(); // var z = model.ObservationDateTime = model.ObservationDateTime.ToUniversalTime(); _mapper.Map <ObservationEditDto, Observation>(model, observation); var bird = await _birdRepository.GetBirdAsync(model.Bird.BirdId); if (bird is null) { string message = $"The observed bird could not be found for observation with id '{model.ObservationId}'."; _logger.LogError(LoggingEvents.UpdateItem, message); return(StatusCode(500, message)); } observation.Bird = bird; var position = await _observationPositionRepository.SingleOrDefaultAsync(o => o.ObservationId == observation.ObservationId); if (position is null) { string message = $"The position could not be found for observation with id '{model.ObservationId}'."; _logger.LogError(LoggingEvents.UpdateItem, message); return(StatusCode(500, message)); } position.Latitude = model.Position.Latitude; position.Longitude = model.Position.Longitude; position.FormattedAddress = model.Position.FormattedAddress; position.ShortAddress = model.Position.ShortAddress; // ToDo: separate ObservationNotesController to handle this stuff. // ...need to redesign UI first... var notes = await _observationNoteRepository.FindAsync(x => x.Observation.ObservationId == id); var notesDeleted = ObservationNotesHelper.GetDeletedNotes(notes, model.Notes); if (notesDeleted.Any()) { _observationNoteRepository.RemoveRange(notesDeleted); } var notesAdded = ObservationNotesHelper.GetAddedNotes(model.Notes); if (notesAdded.Any()) { var added = _mapper.Map(notesAdded, new List <ObservationNote>()); added.ForEach(a => a.Observation = observation); _observationNoteRepository.AddRange(added); } // ToDo: is the condition necessary here? if (notes.Any()) { _mapper.Map <List <ObservationNoteDto>, IEnumerable <ObservationNote> >(model.Notes, notes); } observation.LastUpdateDate = _systemClock.GetNow; if (!TryValidateModel(observation, nameof(observation))) { _logger.LogError(LoggingEvents.UpdateItemNotFound, "Observation has an invalid model state: " + ModelStateErrorsExtensions.GetModelStateErrorMessages(ModelState), id); return(StatusCode(500, "observation ModelState is invalid")); } await _unitOfWork.CompleteAsync(); return(Ok(_mapper.Map <Observation, ObservationEditDto>(observation))); } catch (Exception ex) { _logger.LogError(LoggingEvents.UpdateItemNotFound, ex, "An error occurred updating (PUT) observation with id: {ID}", id); return(StatusCode(500, "an unexpected error occurred")); } }
public async Task <IActionResult> GetConfirmEmailAsync(string username, string code) { try { if (string.IsNullOrEmpty(username) || code == null) { _logger.LogError(LoggingEvents.GetItemNotFound, $"Null arguments passed to ConfirmEmailAsync: username = {username}; code = {code}."); return(BadRequest("An error occurred")); } var user = await _userManager.FindByNameAsync(username); if (user == null) { _logger.LogError(LoggingEvents.GetItemNotFound, $"User with username '{username}' not found"); return(NotFound("User not found")); } var result = await _userManager.ConfirmEmailAsync(user, code); if (!result.Succeeded) { ModelStateErrorsExtensions.AddIdentityErrors(ModelState, result); _logger.LogError(LoggingEvents.UpdateItemNotFound, "Invalid model state:" + ModelStateErrorsExtensions.GetModelStateErrorMessages(ModelState)); return(BadRequest("An error occurred")); } return(Redirect("/confirmed-email")); } catch (Exception ex) { _logger.LogError(LoggingEvents.UpdateItemNotFound, ex, "An error occurred in email confirmation."); return(BadRequest("An error occurred")); } }
public async Task <IActionResult> PostRegisterAsync([FromBody] RegisterViewModel model) { try { //if (!ModelState.IsValid) //{ // _logger.LogError(LoggingEvents.UpdateItemNotFound, "Invalid model state:" + ModelStateErrorsExtensions.GetModelStateErrorMessages(ModelState)); // return BadRequest(ModelState); //} var newUser = new ApplicationUser { UserName = model.UserName, Email = model.Email, DefaultLocationLatitude = 54.972237, DefaultLocationLongitude = -2.4608560000000352, Avatar = "https://img.icons8.com/color/96/000000/user.png", // "https://birderstorage.blob.core.windows.net/profile/default.png", RegistrationDate = _systemClock.GetNow }; var result = await _userManager.CreateAsync(newUser, model.Password); if (result.Succeeded) { var code = await _userManager.GenerateEmailConfirmationTokenAsync(newUser); var url = _urlService.GetConfirmEmailUrl(newUser.UserName, code); var templateData = new { username = newUser.UserName, url = url }; await _emailSender.SendTemplateEmail("d-882e4b133cae40268364c8a929e55ea9", newUser.Email, templateData); return(Ok()); //ToDo: Is this adequate? Created reponse? } ModelStateErrorsExtensions.AddIdentityErrors(ModelState, result); _logger.LogError(LoggingEvents.UpdateItemNotFound, "Invalid model state:" + ModelStateErrorsExtensions.GetModelStateErrorMessages(ModelState)); return(BadRequest(ModelState)); } catch (Exception ex) { _logger.LogError(LoggingEvents.UpdateItemNotFound, ex, "An error occurred in new user registration."); return(BadRequest("An error occurred")); } }
public async Task <IActionResult> PostResetPasswordAsync(ResetPasswordViewModel model) { try { var user = await _userManager.FindByEmailAsync(model.Email); if (user == null) { return(Ok()); // Don't reveal that the user does not exist } var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return(Ok()); } ModelStateErrorsExtensions.AddIdentityErrors(ModelState, result); _logger.LogError(LoggingEvents.UpdateItemNotFound, "Invalid model state:" + ModelStateErrorsExtensions.GetModelStateErrorMessages(ModelState)); return(BadRequest("An error occurred")); } catch (Exception ex) { _logger.LogError(LoggingEvents.UpdateItemNotFound, ex, "An error occurred in forgot password."); return(BadRequest("An error occurred")); } }