private async Task ProcessPage(ShowIndexDto showIndexPage, CancellationToken cancellationToken) { foreach (var showId in showIndexPage.ShowIds) { if (cancellationToken.IsCancellationRequested) { return; } ShowDto show = await SafeExecute(() => dataProvider.GetShowCastAsync(showId)); if (show != null) { try { await AddShow(show); } catch (Exception e) { logger.LogError(e.ToString()); } } else { logger.LogWarning($"could not load show {showId}"); } } }
public async Task Post(ShowDto model) { var mapped = _mapper.Map <Show>(model); _repository.Show.Create(mapped); await _repository.SaveAsync(); }
public async Task <ShowDto> GetShowDataById(int showId, CancellationToken cancellationToken = default(CancellationToken)) { var jshow = await _jsonApiDataReader.GetJsonData <dynamic>( new Uri($"/shows/{showId}?embed=cast", UriKind.Relative), cancellationToken); var show = new ShowDto { Id = jshow.id, Name = jshow.name }; var embedded = jshow._embedded; if (embedded is null) { _logger.LogError($"No embedded data returned for show {showId}."); } else { var jcast = embedded.cast; if (jcast is null) { _logger.LogError($"No cast data found embedded for show {showId}."); } else { show.Cast.AddRange(GetCasts(jcast)); } } return(show); }
// PUT api/Shows/5 public ShowDto Put([FromBody] ShowDto show) { var updatedShow = show.ConvertFromDto(); ShowService.Update(updatedShow); return(updatedShow.ConvertToDto()); }
// POST api/Shows public ShowDto Post([FromBody] ShowDto show) { var newShow = show.ConvertFromDto(); ShowService.Add(newShow); return(newShow.ConvertToDto()); }
private IEnumerable <ShowDto> GetExpectedShows() { var show1 = new ShowDto { Id = 1, Name = "Matrix" }; var show2 = new ShowDto { Id = 2, Name = "Kill Bill" }; var actor1 = new ActorDto { Id = 1, Name = "Bill", Birthday = "1980-07-01" }; var actor2 = new ActorDto { Id = 3, Name = "Nick", Birthday = "1981-07-01" }; var actor3 = new ActorDto { Id = 2, Name = "Tom", Birthday = "1979-07-01" }; show1.Cast = new List <ActorDto>(); //show1.Cast = new List<ActorDto> { actor1 }; //show2.Cast = new List<ActorDto> { actor2, actor3 }; return(new List <ShowDto> { show1 }); }
private async Task AddShow(ShowDto show) { var addShowCommand = new AddShowCommand { Show = show }; await showCommandRepository.AddShowAsync(addShowCommand); }
public static Show ConvertFromDto(this ShowDto showDto) { var show = new Show(showDto.Id, showDto.Name, showDto.Description); //foreach (var contestDto in showDto.Contests) //show.Contests.Add(ConvertFromDto(contestDto)); return(show); }
public FavouritiesAction AddOrDelete(ShowDto show) { if (AddShow(show)) { return(FavouritiesAction.Add); } DeleteShow(show); return(FavouritiesAction.Delete); }
public NewShowViewModel(ICinemaService model) { _model = model ?? throw new ArgumentNullException(nameof(model)); NewShow = new ShowDto(); LoadData(); SendCommand = new DelegateCommand(param => AddNewShow()); CancelCommand = new DelegateCommand(param => OnCancel()); }
public bool AddShow(ShowDto show) { if (FavouritiesShowCollection.Any(x => x.Id == show.Id)) { return(false); } FavouritiesShowCollection.Add(show); SaveShowCollectionToSettings(); return(true); }
public async Task <IActionResult> LatestByPresenter(string handle, CancellationToken ct) { var show = await _context.Shows .Where(s => s.Presenter == handle) .OrderByDescending(s => s.Time) .Take(1) .FirstOrDefaultAsync(ct) .ConfigureAwait(false); return(show == null?NotFound() : Ok(ShowDto.FromShow(show))); }
public static Show MapToShow(ShowDto showDto, IList <CastDto> castDtos) { return(new Show { Id = showDto.Id, Name = showDto.Name, Cast = castDtos.Select(MapToCast) .OrderByDescending(x => x.Birthday.HasValue) .ThenByDescending(x => x.Birthday) .ToList() }); }
private async Task <IEnumerable <CastMember> > GetCastMembersAsync(ShowDto showDto) { _logger.LogInformation("Collecting casts for show " + showDto.Id); var cast = await _castCollector.GetCastAsync(showDto.Id); var castMembers = cast.Select(c => new CastMember { Id = c.Person.Id, BirthDay = c.Person.Birthday, Name = c.Person.Name }); return(castMembers); }
private ShowDto ConvertShow(Show localshow) { // TODO use mapper var coreshow = new ShowDto { Id = localshow.Id, Name = localshow.Name }; coreshow.CastMembers.AddRange(localshow.ShowCastMembers .Select(scm => scm.CastMember) .Select(cm => new CastMemberDto { Id = cm.Id, Name = cm.Name, Birthdate = cm.Birthdate })); return(coreshow); }
public async Task <ActionResult> Put(int id, [FromBody] ShowDto show) { var showToUpdate = await _repository.Show.GetShowAsync(id, false); if (showToUpdate == null) { return(NotFound()); } var mappedShow = _mapper.Map <Show>(show); _repository.Show.Update(mappedShow); await _repository.SaveAsync(); return(NoContent()); }
private async Task <int> AddOrUpdateWithoutSaveAsync(Show show) { int result = UpdatedStatus; var showDto = await _context.Shows.Include(c => c.Cast).FirstOrDefaultAsync(o => o.Id == show.Id); if (showDto == null) { result = CreatedStatus; showDto = new ShowDto(); await _context.Shows.AddAsync(showDto); } _mapper.Map(show, showDto); var toDelete = new List <CastDto>(); //remove deleted cast foreach (var deleted in showDto.Cast ?? Enumerable.Empty <CastDto>()) { if (!show.Cast?.Any(c => c.Id == deleted.Id) ?? true) { toDelete.Add(deleted); } } if (toDelete.Any()) { _context.Cast.RemoveRange(toDelete); } //update or add details show.Cast?.ToList().ForEach(cast => { if (showDto.Cast == null) { showDto.Cast = new List <CastDto>(); } var castDto = showDto.Cast.FirstOrDefault(d => d.Id == cast.Id); if (castDto == null) { castDto = new CastDto(); showDto.Cast.Add(castDto); } _mapper.Map(cast, castDto); }); return(result); }
public void AddNewShowTest() { var newShow = new ShowDto { movieId = _context.Movies.Single(o => o.Title == "TEST_MOVIE_2").Id, roomId = _context.Rooms.Single(o => o.RoomName == "TEST_ROOM").Id, StartTime = "2019-12-20 10:00:00" }; var controller = new ShowController(_context); var result = controller.NewShow(newShow); var objectResult = Assert.IsType <OkResult>(result); Assert.Equal(_showDTOs.Count + 1, _context.Shows.Count()); Assert.Equal(200, objectResult.StatusCode); }
private Show ConvertShow(ShowDto coreshow) { var modelshow = new Show { Id = coreshow.Id, Name = coreshow.Name }; modelshow.ShowCastMembers.AddRange(coreshow.CastMembers .Select(cm => new ShowCastMember { Show = modelshow, CastMember = new CastMember { Id = cm.Id, Name = cm.Name, Birthdate = cm.Birthdate } })); return(modelshow); }
public async Task <ShowDto> GetShowDataById(int showId, CancellationToken cancellationToken = default(CancellationToken)) { var jshow = await _jsonApiDataReader.GetJsonData <dynamic>( new Uri($"/shows/{showId}?embed=cast", UriKind.Relative), cancellationToken); var show = new ShowDto { Id = jshow.id, Name = jshow.name }; var embedded = jshow._embedded; if (embedded is null) { _logger.LogError($"No embedded data returned for show {showId}."); } else { var jcast = embedded.cast; if (jcast is null) { _logger.LogError($"No cast data found embedded for show {showId}."); } else { foreach (var container in jcast) { var person = container.person; var personDto = new PersonDto { Id = person.id, Name = person.name, Birthdate = person.birthday, }; show.Cast.Add(personDto); } } } return(show); }
public async Task <List <ShowDto> > GetShowsByPage(int pageNumber, CancellationToken cancellationToken = default(CancellationToken)) { var result = new List <ShowDto>(); var shows = await _jsonApiDataReader.GetJsonData <JArray>( new Uri($"/shows?page={pageNumber}", UriKind.Relative), cancellationToken); foreach (dynamic jshow in shows) { var show = new ShowDto { Id = jshow.id, Name = jshow.name }; result.Add(show); } _logger.LogInformation($"Getting {result.Count} Shows for pageNumber {pageNumber}"); return(result); }
/// <summary> /// Scrapes the shows by their initial. /// </summary> /// <param name="searchWord">The search word.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns> /// A list of shows. /// </returns> public async Task <List <ShowDto> > ScrapeShowsBySearch(string searchWord, CancellationToken cancellationToken = default) { // note: not documented, but apparently returns just the first 10 results var(status, json) = await this.apiRepository.RequestJsonForTvMaze( new Uri($"/search/shows?q={searchWord}", UriKind.Relative), cancellationToken) .ConfigureAwait(false); if (status != HttpStatusCode.OK) { // some error or 429 this.logger.LogWarning("Scraping shows for '{searchWord}' returned status {status}.", searchWord, status); return(null); } var result = new List <ShowDto>(); /* NOTE to reviewer: I could have created a tree of objects to deserialize this JSON into, * but that would be a tree per API call with no benefit to speed of execution, speed of development * or maintainability. A change in the API would in both cases force a rewrite. */ // read json var shows = JArray.Parse(json); foreach (dynamic showcontainer in shows) { var jshow = showcontainer.show; var show = new ShowDto { Id = jshow.id, Name = jshow.name, }; result.Add(show); } this.logger.LogInformation("Scraping for '{searchWord}' returned {resultCount} shows.", searchWord, result.Count); return(result); }
private async Task HandleShowDto( ShowDto showDto, bool reset, CancellationToken cancellationToken, Action <Show> showAddedAction) { var addShow = reset || await _dbContext.Show.AllAsync(x => x.Id != showDto.Id, cancellationToken); if (!addShow) { return; } var castDtos = await _client.ListCast(showDto.Id, cancellationToken); var show = ClientDtoMapper.MapToShow(showDto, castDtos); var showDbDto = DbDtoMapper.MapToShowDto(show); _dbContext.Show.Add(showDbDto); await _dbContext.SaveChangesAsync(cancellationToken); _dbContext.Entry(showDbDto).State = EntityState.Detached; showAddedAction?.Invoke(show); }
public bool DeleteShow(ShowDto show) { return(DeleteShow(show.Id)); }
public IActionResult NewShow([FromBody] ShowDto item) { try { if (ModelState.IsValid) { var selectedMovie = (_context.Movies.Where(o => o.Id == item.movieId)).FirstOrDefault(); var selectedRoom = (_context.Rooms.Where(o => o.Id == item.roomId)).FirstOrDefault(); if (selectedMovie == null || selectedRoom == null) { return(NotFound()); } var newShowStart = DateTime.Parse(item.StartTime); var newShowEnd = newShowStart + selectedMovie.Length + TimeSpan.FromMinutes(15); var showsToCheck = (_context.Shows.Where(o => o.RoomRefId == selectedRoom.Id)).ToList(); foreach (var show in showsToCheck) { var currentMovie = _context.Movies.FirstOrDefault(o => o.Id == show.MovieRefId); var showEnd = show.StartTime + currentMovie.Length + TimeSpan.FromMinutes(15); var invalidTime = (DateTime.Compare(show.StartTime, newShowStart) < 1 && DateTime.Compare(newShowStart, showEnd) < 1) || (DateTime.Compare(show.StartTime, newShowEnd) < 1 && DateTime.Compare(newShowEnd, showEnd) < 1); if (invalidTime) { return(BadRequest()); } } var newShow = new Show() { Movie = selectedMovie, Room = selectedRoom, StartTime = DateTime.Parse(item.StartTime) }; for (int i = 0; i < newShow.Room.NumOfRows; i++) { for (int j = 0; j < newShow.Room.NumOfCols; j++) { _context.Seats.Add( new Seat() { Row = i, Col = j, Room = newShow.Room, Show = newShow, State = State.Free }); } } _context.Shows.Add(newShow); _context.SaveChanges(); } else { return(BadRequest()); } } catch (DbUpdateConcurrencyException) { return(BadRequest()); } catch (DbUpdateException) { return(BadRequest()); } catch (Exception) { return(BadRequest()); } return(Ok()); }
public async Task <Boolean> SendNewShow(ShowDto newShowData) { HttpResponseMessage response = await _client.PostAsJsonAsync("api/Show/", newShowData); return(response.IsSuccessStatusCode); }
public async Task <IActionResult> Get(string presenter, string slug, CancellationToken ct) { var show = await _context.Shows.SingleOrDefaultAsync(s => s.Presenter == presenter && s.Slug == slug, ct).ConfigureAwait(false); return(show == null?NotFound() : Ok(ShowDto.FromShow(show))); }
public async Task <IActionResult> Start([FromBody] Show show, CancellationToken ct) { try { _context.Shows.Add(show); await _context.SaveChangesAsync(ct).ConfigureAwait(false); return(CreatedAtAction("Get", "Shows", new { presenter = show.Presenter, slug = show.Slug }, ShowDto.FromShow(show))); } catch (System.Exception ex) { _logger.LogError(EventIds.DatabaseError, ex, ex.Message); throw; } }
/// <summary> /// Deconstructs this to a show and status tuple. /// </summary> /// <param name="show">The show.</param> /// <param name="status">The status.</param> public void Deconstruct(out ShowDto show, out HttpStatusCode status) { show = this.Show; status = this.HttpStatus; }
/// <summary> /// Scrapes the single show by its identifier. /// </summary> /// <param name="showId">The show's identifier.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>A Task with Show and status code.</returns> public async Task <ScrapeResult> ScrapeSingleShowById(int showId, CancellationToken cancellationToken = default) { var sw = Stopwatch.StartNew(); var(status, json) = await this.apiRepository.RequestJsonForTvMaze( new Uri($"/shows/{showId}?embed=cast", UriKind.Relative), cancellationToken) .ConfigureAwait(false); sw.Stop(); this.logger.LogInformation("Getting info about show {ShowId} took {Elapsed} msec and returned status {HttpStatus}.", showId, sw.ElapsedMilliseconds, status); if (status == Constants.ServerTooBusy) { // too much, so back off this.logger.LogDebug("Server too busy to scrape #{ShowId}, backing off.", showId); return(new ScrapeResult { HttpStatus = status }); } if (status == HttpStatusCode.OK) { dynamic jshow = JObject.Parse(json); var show = new ShowDto { Id = jshow.id, Name = jshow.name, ImdbId = jshow.externals?.imdb, }; var embedded = jshow._embedded; if (embedded is null) { this.logger.LogError("Server didn't return the requested embedded data for show {ShowId}.", showId); } else { var jcast = embedded.cast; if (jcast is null) { this.logger.LogError("Server didn't return the requested cast in the embedded data for show {ShowId}.", showId); } else { foreach (var container in jcast) { var person = container.person; var member = new CastMemberDto { Id = person.id, Name = person.name, Birthdate = person.birthday, }; show.CastMembers.Add(member); } } } return(new ScrapeResult { Show = show, HttpStatus = status }); } return(new ScrapeResult { HttpStatus = status }); }