// POST entries/{entryId}/update // Update the entry for the user. public async Task <ActionResult> UpdateEntry([FromBody] EntryDto entryDto) { var currentUser = await _userService.GetUserAsync(User); if (!(await IsValidEntry("UpdateEntry", currentUser, entryDto))) { return(new BadRequestResult()); } // Update any self assessments. var currentEntry = await _entryService.GetEntryAsync(currentUser, entryDto.Id); var removedSelfAssessments = currentEntry.AssessmentBundle .Where(p => !entryDto.AssessmentBundle.ContainsKey(p.Key)) .ToDictionary(p => p.Key, p => p.Value); // Remove any self assessments, we will get the latest self assessments back. var latestSelfAssessments = _selfAssessmentService.RemoveSelfAssessments( currentUser, entryDto.SkillSetId, removedSelfAssessments, entryDto); // Add all the self assessments, this will update any existing ones too. _selfAssessmentService.CreateSelfAssessments( currentUser, entryDto.SkillSetId, entryDto.AssessmentBundle, entryDto); // Update the entry. _entryService.UpdateEntry(currentUser, entryDto); return(Json(latestSelfAssessments)); }
public async Task <IActionResult> Post(string username, [FromBody] EntryDto dto) { var validationResult = await ValidateUser(username); if (validationResult != null) { return(validationResult); } if (dto.Amount == 0) { return(BadRequest("The Amount cannot be 0.")); } var userId = (await userManager.FindByNameAsync(username)).Id; //Convert Dto to Model Object var newEntry = dto.Convert(userId); //Add Entry and save the changes dbContext.Entries.Add(newEntry); await dbContext.SaveChangesAsync(); //Everything went Ok, prepare the Dto dto.Id = newEntry.Id; //Return location of the new Entry along with the Dto return(Created(Url.Action("Get", "Entries", new { username, dto.Id }), dto)); }
public async Task <IActionResult> Put(string username, int id, [FromBody] EntryDto dto) { var validationResult = await ValidateUser(username); if (validationResult != null) { return(validationResult); } if (dto.Amount == 0) { return(BadRequest("The Amount cannot be 0.")); } //Get Entry in the DB var entryInDb = await GetEntry(username, id); //Return NotFound if null if (entryInDb == null) { return(NotFound()); } //Make changes to the other Model properties and save changes entryInDb.Description = dto.Description; entryInDb.Amount = dto.Amount.Value; entryInDb.Date = dto.Date.Value; await dbContext.SaveChangesAsync(); return(Ok()); }
public async Task <ActionResult <IEnumerable <EntryDto> > > GetEntries() { var entries = await _repoWrapper.EntryRepository.FindAllAsync(); var entriesDto = new List <EntryDto>(); entries.ToList().ForEach(e => { var entryDto = new EntryDto { Id = e.Id, Amount = e.Amount.ToString(), Name = e.Name, Paid = e.Paid, Description = e.Description, Date = e.Date.ToShortDateString(), Type = e.Type }; var categories = _repoWrapper.CategoryRepository.FindByConditionAsync(c => c.Id == e.CategoryId); var category = categories.Result.FirstOrDefault(); entryDto.CategoryId = category.Id; entryDto.CategoryName = category.Name; entriesDto.Add(entryDto); }); return(Ok(entriesDto)); }
public async Task <ActionResult <EntryDto> > GetEntry(long id) { var entries = await _repoWrapper.EntryRepository.FindByConditionAsync(e => e.Id == id); var entry = entries.FirstOrDefault(); if (entry == null) { return(NotFound()); } var entryDto = new EntryDto { Id = entry.Id, Amount = entry.Amount.ToString(), Name = entry.Name, Paid = entry.Paid, Description = entry.Description, Date = entry.Date.ToShortDateString(), Type = entry.Type }; var categories = _repoWrapper.CategoryRepository.FindByConditionAsync(c => c.Id == entry.CategoryId); var category = categories.Result.FirstOrDefault(); entryDto.CategoryId = category.Id; entryDto.CategoryName = category.Name; return(Ok(entryDto)); }
public IHttpActionResult PostEntry(EntryDto entryDto) { if (!ModelState.IsValid) { return(BadRequest()); } //id gets set by db var entry = new Entry { Title = entryDto.Title, Body = entryDto.Body, DatePosted = DateTime.Now }; _context.Entries.Add(entry); _context.SaveChanges(); //get the id and datetime that was not passed in to dto entryDto.Id = entry.Id; entryDto.DatePosted = entry.DatePosted; Uri returnUri = new Uri(Request.RequestUri + "/" + entry.Id); //return 201 with GetEntry. must pass in dto for Created result return(Created(returnUri, entryDto)); }
public IHttpActionResult UpdateEntry(int id, EntryDto entryDto) { if (!ModelState.IsValid) { return(BadRequest()); } var entry = _context.Entries.SingleOrDefault(e => e.Id == id); if (entry == null) { return(NotFound()); } entry.Title = entryDto.Title; entry.Body = entryDto.Body; _context.SaveChanges(); var returnDto = new EntryDto { Id = entry.Id, Title = entry.Title, Body = entry.Body, DatePosted = entry.DatePosted }; return(Ok(returnDto)); }
public ReportDetailDto(EntryDto dto) { Id = dto.Id; Description = dto.Description; Amount = dto.Amount; Date = dto.Date; }
private void ValidateEntry(EntryDto entryDto) { if (ModelState.IsValidField("Duration") && entryDto.Duration <= 0) { ModelState.AddModelError("entryDto.Duration", "The Duration field value must be greater than '0'."); } }
private async Task <EntryDto> InsertValueAsync( string value, IMongoCollection <EntryDto> collection) { var record = new EntryDto(value); for (var attempt = 0; attempt < InsertMaxAttempts; attempt++) { try { await collection.InsertOneAsync(record); return(record); } catch (MongoException ex) { var duplicatedKeyError = ex.Message .Contains(DuplicatedKeyMongoMessageError); if (!duplicatedKeyError) { throw; } record.Key = Guid.NewGuid(); } catch (TimeoutException) { throw new RepositoryCustomException( RepositoryCustomError.TimeOutServer); } } throw new RepositoryCustomException( RepositoryCustomError.UnavailableKey); }
public async Task UpdateEntry() { // ARRANGE var service = this._fixture.Services.GetRequiredService <IDiaryEntryService>(); Entry entry = await service.SaveEntryAsync(new EntryModel { Description = "Old value", Timestamp = SimplerTime.UnixEpochStart.DropMilliseconds() }); var newData = new EntryDto { Description = "New value", Timestamp = DateTime.Now.DropMilliseconds() }; // ACT HttpResponseMessage response = await this._fixture.Client.PutAsync( $"/api/entries/{entry.Id}", new StringContent( JsonConvert.SerializeObject(newData), Encoding.UTF8, CommonMimeTypes.Json) ); response.EnsureSuccessStatusCode(); var responseString = await response.Content.ReadAsStringAsync(); var output = JsonConvert.DeserializeObject <EntryModel>(responseString); // ASSERT output.Timestamp.ShouldBeEquivalentTo(newData.Timestamp); output.Description.ShouldBeEquivalentTo(newData.Description); }
public async Task CreateEntry() { // ARRANGE var input = new EntryDto { Description = "Test", Timestamp = DateTime.Now.DropMilliseconds() }; // ACT HttpResponseMessage response = await this._fixture.Client.PostAsync( "/api/entries", new StringContent( JsonConvert.SerializeObject(input), Encoding.UTF8, CommonMimeTypes.Json) ); response.EnsureSuccessStatusCode(); var responseString = await response.Content.ReadAsStringAsync(); var output = JsonConvert.DeserializeObject <EntryModel>(responseString); // ASSERT output.Id.Should().BeGreaterThan(0); output.Timestamp.ShouldBeEquivalentTo(input.Timestamp); }
public async Task <EntryDto> Update(EntryDto entryDto) { var existingEntry = await _context.Entries.FindAsync(entryDto.Id); if (existingEntry == null) { throw new EntryNotFoundException($"Entry not found: {entryDto.Id}"); } bool didUpdate = false; if (ShouldUpdate(existingEntry.Title, entryDto.Title)) { existingEntry.Title = entryDto.Title; didUpdate = true; } if (ShouldUpdate(existingEntry.Body, entryDto.Body)) { existingEntry.Body = entryDto.Body; didUpdate = true; } if (didUpdate) { existingEntry.LastModified = DateTime.Now; _context.UpdateRange(existingEntry); await _context.SaveChangesAsync(); } return(new EntryDto(existingEntry)); bool ShouldUpdate(string originalValue, string newValue) => !string.IsNullOrEmpty(newValue) && originalValue != newValue; }
// POST entries/create // Creates a new entry for the user. public async Task <ActionResult> CreateEntry([FromBody] EntryDto entryDto) { var currentUser = await _userService.GetUserAsync(User); if (!(await IsValidEntry("CreateEntry", currentUser, entryDto))) { return(new BadRequestResult()); } // Create the entry. entryDto.When = new DateTime( entryDto.When.Year, entryDto.When.Month, entryDto.When.Day, entryDto.When.Hour, entryDto.When.Minute, entryDto.When.Second); // Remove the miliseconds. var newEntry = _entryService.CreateEntry(currentUser, entryDto); _selfAssessmentService.CreateSelfAssessments( currentUser, entryDto.SkillSetId, entryDto.AssessmentBundle, newEntry); return(Json(newEntry)); }
public async Task Put(EntryDto entryDto) { var entry = this.mapper.Map <Entry>(entryDto); entry.Change = DateTime.Now; await this.entriesService.UpdateAsync(entry); }
public async Task <IActionResult> New(EntryDto model, String saveAndClose) { EntryDto result = (await this._api.SaveEntry(model)).MapTo <EntryDto>(this._mapper); return(saveAndClose == null ? (IActionResult)this.View("Edit", result) : this.RedirectToAction(nameof(this.List))); }
public async Task <IActionResult> Edit([FromRoute] UInt32 id, EntryDto entry, String saveAndClose) { EntryDto model = (await this._api.SaveEntry(entry, id)).MapTo <EntryDto>(this._mapper); return(saveAndClose == null ? (IActionResult)this.View("Edit", model) : this.RedirectToAction(nameof(this.List))); }
public IActionResult New() { var model = new EntryDto { Timestamp = DateTime.Now }; return(this.View("Edit", model)); }
private void ValidateEntry(EntryDto entry) { // If there aren't any "Duration" field validation errors then make sure that the duration is greater than "0". if (ModelState.IsValidField("Duration") && entry.Duration <= 0) { ModelState.AddModelError("entry.Duration", // Web API is prefixing the field names with the parameter name, so we also do it "The Duration field value must be greater than '0'."); } }
public IHttpActionResult Put(int id, EntryDto entryDto) { if (!ModelState.IsValid) return BadRequest(ModelState); _entriesRepository.Update(entryDto.ToModel()); return StatusCode(System.Net.HttpStatusCode.NoContent); }
public IHttpActionResult Put(int id, EntryDto entry) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _entriesRepository.Add(entry.ToModel()); return(StatusCode(System.Net.HttpStatusCode.NoContent)); }
private async Task <bool> IsValidEntry(string caller, User currentUser, EntryDto entryDto) { if (entryDto.SkillSetId == 0) { _logger.LogInformation($"{caller} called with invalid SkillSetId of {entryDto.SkillSetId}"); return(false); } var skillSet = await _skillService.GetSkillSetAsync(entryDto.SkillSetId); if (skillSet == null) { _logger.LogInformation($"{caller} called with invalid SkillSetId of {entryDto.SkillSetId}"); return(false); } var existingEntry = entryDto.Id != Guid.Empty ? await _entryService.GetEntryAsync(currentUser, entryDto.Id) : null; if (entryDto.Id != Guid.Empty && existingEntry == null) { _logger.LogInformation($"{caller} called with EntryId of {entryDto.Id}"); return(false); } if (entryDto.Id != Guid.Empty && existingEntry.Author.Id != currentUser.Id) { _logger.LogInformation($"{caller} called with EntryId of {entryDto.Id} that was created by user {entryDto.Author.Id} but being edited by {currentUser.Id}"); return(false); } if (entryDto.EntryType != null) { var entryTypes = await _entryService.GetEntryTypesAsync(new[] { skillSet.Id }); if (entryDto.Id == Guid.Empty) { // this is a new entry, don't allow retired entry types. entryTypes = entryTypes.Where(t => t.Retired == false); } if (entryTypes.All(t => t.Id != entryDto.EntryType.Id)) { _logger.LogInformation($"{caller} called with invalid entry type of {entryDto.EntryType.Id}"); return(false); } } if (entryDto.When == DateTime.MinValue) { entryDto.When = DateTime.UtcNow; } if (string.IsNullOrWhiteSpace(entryDto.Title)) { entryDto.Title = "Untitled Entry"; } if (string.IsNullOrWhiteSpace(entryDto.Where)) { entryDto.Where = "Unknown"; } return(true); }
public async Task Post(EntryDto entryDto) { var entry = this.mapper.Map <Entry>(entryDto); entry.EntryId = Guid.NewGuid(); entry.CreationDate = DateTime.Now; entry.Change = DateTime.Now; await this.entriesService.AddAsync(entry); }
private void ValidateEntry(EntryDto entry) { // If there aren't any "Duration" field validation errors // then make sure that the duration is greater than "0". if (ModelState.IsValidField("Duration") && entry.Duration <= 0) { ModelState.AddModelError("entry.Duration", "The Duration field value must be greater than '0'."); } }
public static EntryModel FromDto(this EntryDto entryDto) { return(new EntryModel ( entryDto.Id, entryDto.Merchandise.FromDto(), entryDto.Amount, entryDto.BruttoPrice )); }
private void ValidateEntry(EntryDto entry) { // ensure "Duration" is valid // ensure "Duration" is greater than 0 if (ModelState.IsValidField("Duration") && entry.Duration <= 0) { ModelState.AddModelError("entry.Duration", "The Duration field value must be greater than 0."); } }
public async Task <IActionResult> CreateEntry(Guid topicId, [FromBody] EntryDto newEntry) { var result = await entryService.CreateEntry(User.Identity.Name, topicId, newEntry); if (result.IsSuccessed) { return(Ok(result.Data)); } throw result.Exception; }
public static Entry FromDto(this EntryDto entryDto) { return(new Entry { PageRef = entryDto.pageref, StartedDateTime = StringDateToDateTime(entryDto.startedDateTime), Request = entryDto.request.FromDto(), Response = entryDto.response.FromDto(), Cache = (entryDto.cache != null) ? entryDto.cache.FromDto() : null, Timings = entryDto.timings.FromDto(), Connection = (entryDto.connection != null) ? int.Parse(entryDto.connection) : 0 }); }
public IHttpActionResult Put(int id, EntryDto entryDto) { ValidateEntry(entryDto); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var entryModel = entryDto.ToModel(); _entriesRepository.Update(entryModel); return(StatusCode(System.Net.HttpStatusCode.NoContent)); }
public async Task <ActionResult> Update(EntryDto updatedEntry) { var result = await _service.Update(updatedEntry); if (result == null) { _logger.LogInformation($"Unable to update entry"); return(BadRequest()); } _logger.LogInformation($"Entry updated: {updatedEntry.Id}"); return(Ok(result)); }