public Task <Unit> Handle(UpdateTrackCommand request, CancellationToken cancellationToken)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            async Task <Unit> UpdateTrackAsync()
            {
                var trackFromDb = await _context
                                  .Tracks
                                  .AsNoTracking()
                                  .FirstOrDefaultAsync(e => e.Id == request.TrackId);

                if (trackFromDb == null)
                {
                    throw new EntityNotFoundException($"A track having id '{request.TrackId}' could not be found");
                }

                trackFromDb.AlbumId      = request.AlbumId;
                trackFromDb.Bytes        = request.AlbumId;
                trackFromDb.Composer     = request.Composer;
                trackFromDb.GenreId      = request.GenreId;
                trackFromDb.MediaTypeId  = request.MediaTypeId;
                trackFromDb.Milliseconds = request.Milliseconds;
                trackFromDb.Name         = request.Name;
                trackFromDb.UnitPrice    = request.Price;

                var entriesSaved = await _context.SaveChangesAsync(cancellationToken);

                return(Unit.Value);
            }

            return(UpdateTrackAsync());
        }
        private async Task <Unit> DeletePlaylistAsync(int playlistId, CancellationToken cancellationToken)
        {
            var playlist = await _context
                           .Playlists
                           .FirstOrDefaultAsync(playlist => playlist.Id == playlistId);

            if (playlist == null)
            {
                throw new EntityNotFoundException($"A playlist having id '{playlistId}' could not be found");
            }

            var playlistTracks = await _context
                                 .PlaylistTracks
                                 .Where(e => e.PlaylistId == playlistId)
                                 .ToListAsync();

            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Suppress))
            {
                _context.PlaylistTracks.RemoveRange(playlistTracks);
                _context.Playlists.Remove(playlist);

                var entries = await _context.SaveChangesAsync(cancellationToken);

                if (entries != (playlistTracks.Count + 1))
                {
                    throw new DbUpdateException($"Something went wrong while attempting to remove playlist having id '{playlistId}'");
                }

                scope.Complete();
            }

            return(Unit.Value);
        }
        public Task <Unit> Handle(DeleteTrackCommand request, CancellationToken cancellationToken)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            async Task <Unit> Handle()
            {
                var track = await _context
                            .Tracks
                            .AsNoTracking()
                            .FirstOrDefaultAsync(track => track.Id == request.TrackId);

                if (track == null)
                {
                    throw new DbUpdateException($"Delete track failed. A track having id '{request.TrackId}' could not be found");
                }

                _context.Tracks.Remove(track);
                await _context.SaveChangesAsync(cancellationToken);

                return(Unit.Value);
            }

            return(Handle());
        }
        private async Task <Unit> UpdatePlaylistAsync(UpdatePlaylistCommand request, CancellationToken cancellationToken)
        {
            var playlistFromDb = await _context
                                 .Playlists
                                 .FirstOrDefaultAsync(e => e.Id == request.PlaylistId);

            if (playlistFromDb == null)
            {
                throw new EntityNotFoundException($"A playlist having id '{request.PlaylistId}' could not be found");
            }

            var currentPlaylistTracks = await _context
                                        .PlaylistTracks
                                        .Where(pt => pt.PlaylistId == playlistFromDb.Id)
                                        .ToListAsync();

            var newPlaylistTracks = (await NormalizeTrackIds(request.TrackIds))
                                    .Select(trackId => new PlaylistTrack {
                PlaylistId = playlistFromDb.Id, TrackId = trackId
            });

            _context.PlaylistTracks.RemoveRange(currentPlaylistTracks);
            _context.PlaylistTracks.AddRange(newPlaylistTracks);
            playlistFromDb.Name = request.Name;

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
        public async Task <Unit> Handle(ProductDeleteCommand request, CancellationToken cancellationToken)
        {
            var product = await _context.Products.FindAsync(request.ProductId);

            product.Delete();
            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
        public async Task <Unit> Handle(ProductUpdateCommand request, CancellationToken cancellationToken)
        {
            var product = await _context.Products.FindAsync(new object[] { request.ProductId }, cancellationToken);

            product.Update(request.Name, request.Description);
            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
        public async Task <Guid> Handle(ProductCreateCommand request, CancellationToken cancellationToken)
        {
            var product = new Product(request.Name, request.Description);

            _context.Products.Add(product);
            await _context.SaveChangesAsync(cancellationToken);

            _eventBusManager.Publish(_mapper.Map <ProductViewDto>(product), "catalog.product-created");
            return(product.Id);
        }
        public async Task <long> Handle(UpsertProductCommand request, CancellationToken cancellationToken)
        {
            Product entity;

            if (request.Id.HasValue)
            {
                entity = await _context.Products.FindAsync(request.Id.Value);

                if (entity == null)
                {
                    throw new NotFoundException(nameof(Product), request.Id, _context, cancellationToken);
                }
            }
            else
            {
                entity = new Product();

                _context.Products.Add(entity);
            }

            entity.Name                      = request.Name;
            entity.Description               = request.Description;
            entity.Price                     = request.Price;
            entity.OldPrice                  = request.OldPrice;
            entity.NewPrice                  = request.NewPrice;
            entity.StockQuantity             = request.StockQuantity;
            entity.MinStockQuantity          = request.MinStockQuantity;
            entity.DisplayStockQuantity      = request.DisplayStockQuantity;
            entity.NotifyForQuantityBelow    = request.NotifyForQuantityBelow;
            entity.OrderMinimumQuantity      = request.OrderMinimumQuantity;
            entity.OrderMaximumQuantity      = request.OrderMaximumQuantity;
            entity.MarkAsNew                 = request.MarkAsNew;
            entity.MarkAsNewStartDateTimeUtc = request.MarkAsNewStartDateTimeUtc;
            entity.MarkAsNewEndDateTimeUtc   = request.MarkAsNewEndDateTimeUtc;
            entity.Weight                    = request.Weight;
            entity.Length                    = request.Length;
            entity.Width                     = request.Width;
            entity.Height                    = request.Height;
            entity.AvailableStartDateTimeUtc = request.AvailableStartDateTimeUtc;
            entity.AvailableEndDateTimeUtc   = request.AvailableEndDateTimeUtc;
            entity.Viewed                    = request.Viewed;

            await _context.SaveChangesAsync(cancellationToken);

            await _mediator.Publish(new UpsertProductNotification {
                ProductId = entity.ProductId
                , Name    = entity.Name
                , Action  = request.Id.HasValue ? "Edición" : "Creación"
            }
                                    , cancellationToken);

            return(entity.ProductId);
        }
Beispiel #9
0
        public static Task Send(string accion, string message, ICatalogDbContext _context, CancellationToken cancellationToken)
        {
            _context.Audits.Add(new Audit {
                Date    = DateTime.Now,
                Action  = accion,
                IsError = true,
                Message = message
            });

            _context.SaveChangesAsync(cancellationToken);

            return(Task.CompletedTask);
        }
Beispiel #10
0
    public async Task <int> Handle(RegisterBrandCommand command, CancellationToken cancellationToken)
    {
        if (await _context.Brands.AnyAsync(c => c.Name == command.Name, cancellationToken))
        {
            throw new Exception("Brand with the same name already exists.");
        }
        var brand = new Brand {
            Detail = command.Detail, Name = command.Name
        };
        await _context.Brands.AddAsync(brand, cancellationToken);

        await _context.SaveChangesAsync(cancellationToken);

        return(brand.Id);
    }
Beispiel #11
0
        private async Task <Unit> DeleteTracksFromPlaylistAsync(
            int playlistId,
            IReadOnlyCollection <int> trackIds,
            CancellationToken cancellationToken)
        {
            var validTrackIds = await ValidateTrackIds(playlistId, trackIds);

            var playlistTracksFromDb = await _context
                                       .PlaylistTracks
                                       .Where(playlist => playlist.PlaylistId == playlistId && validTrackIds.Contains(playlist.TrackId))
                                       .ToListAsync();

            _context.PlaylistTracks.RemoveRange(playlistTracksFromDb);
            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
Beispiel #12
0
        public async Task Process(TRequest request, CancellationToken cancellationToken)
        {
            var name = typeof(TRequest).Name;

            _logger.LogInformation("Catálogo --> Solicitud: {Name} {@Request}",
                                   name, request);

            _context.Audits.Add(new Audit {
                Date    = DateTime.Now,
                Action  = name,
                IsError = false,
                Message = $"Se ha llamado a la accion con los siguientes parámetros: \n {request.ToString()}"
            });

            await _context.SaveChangesAsync(cancellationToken);

            return;
        }
        public Task <TrackFromCreate> Handle(CreateTrackCommand request, CancellationToken cancellationToken)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var track = _mapper.Map <Track>(request);

            _context.Tracks.Add(track);

            async Task <TrackFromCreate> AddTrackAsync()
            {
                await _context.SaveChangesAsync(cancellationToken);

                return(_mapper.Map <TrackFromCreate>(track));
            }

            return(AddTrackAsync());
        }
        private async Task <Unit> AddTracksToPlaylistAsync(
            int playlistId,
            IReadOnlyCollection <int> trackIds,
            CancellationToken cancellationToken)
        {
            var playlistFromDb = await _context
                                 .Playlists
                                 .FirstOrDefaultAsync(e => e.Id == playlistId);

            if (playlistFromDb == null)
            {
                throw new EntityNotFoundException($"A playlist having id '{playlistId}' could not be found");
            }

            var newTrackIds = trackIds
                              .Distinct()
                              .OrderBy(trackId => trackId)
                              .ToList();

            var existingTrackIds = await _context
                                   .PlaylistTracks
                                   .AsNoTracking()
                                   .Where(pt => pt.PlaylistId == playlistId && newTrackIds.Contains(pt.TrackId))
                                   .Select(pt => pt.TrackId)
                                   .ToListAsync();

            var tracksForAdd = newTrackIds
                               .Except(existingTrackIds)
                               .Select(trackId => new PlaylistTrack {
                PlaylistId = playlistId, TrackId = trackId
            })
                               .ToList();

            if (tracksForAdd.Any())
            {
                _context.PlaylistTracks.AddRange(tracksForAdd);
                await _context.SaveChangesAsync(cancellationToken);
            }

            return(Unit.Value);
        }
        private async Task <PlaylistFromCreate> CreatePlaylistAsync(CreatePlaylistCommand request, CancellationToken cancellationToken)
        {
            var trackIds = await NormalizeTrackIds(request.TrackIds);

            var playlist = _mapper.Map <Playlist>(request);

            trackIds.ForEach(trackId => playlist.PlaylistTracks.Add(new PlaylistTrack {
                TrackId = trackId
            }));

            _context.Playlists.Add(playlist);

            var entriesSaved = await _context.SaveChangesAsync(cancellationToken);

            var expectedEntriesSaved = trackIds.Count + 1;

            if (entriesSaved != expectedEntriesSaved)
            {
                throw new DbUpdateException($"While adding a new playlist, received '{entriesSaved}' saved entries, but expected '{expectedEntriesSaved}'");
            }

            return(_mapper.Map <PlaylistFromCreate>(playlist));
        }