Example #1
0
        public async Task <IActionResult> RemoveFromCart([FromRoute] Guid?id, [FromServices] MusicStoreDbContext dbContext, CancellationToken cancellationToken = default)
        {
            if (!id.HasValue || id.Value == Guid.Empty)
            {
                return(BadRequest());
            }


            // Get the name of the album to display confirmation
            Cart cartRecord = await dbContext.Carts
                              .Include(x => x.Album)
                              .SingleAsync(item => item.RecordId == id.Value);

            string albumName = cartRecord.Album.Title;

            // Remove from cart
            int itemCount = await _shoppingCart.RemoveFromCart(id.Value, cancellationToken);

            cancellationToken.ThrowIfCancellationRequested();

            // Display the confirmation message
            var results = new ShoppingCartRemoveViewModel()
            {
                Message   = albumName + "has been removed from your shopping cart.",
                CartTotal = await _shoppingCart.GetTotal(),
                CartCount = await _shoppingCart.GetCount(),
                ItemCount = itemCount,
                DeleteId  = id.Value
            };

            return(Json(results));
        }
        private async Task PopulateDbAsync(MusicStoreDbContext db)
        {
            var firstSong = new Song {
                Id = 1, Name = SongName, Price = SongPrice, Duration = SongDuration, ArtistId = SongArtistId
            };
            var secondSong = new Song {
                Id = 2, Name = "SecondSong", Price = 2.5m, ArtistId = 2
            };
            var thirdSong = new Song {
                Id = 3, Name = "ThirdSong", Price = 9.5m, ArtistId = 3
            };

            var firstArtist = new Artist {
                Id = 1, Name = ArtistName
            };
            var secondArtist = new Artist {
                Id = 2, Name = ArtistName
            };
            var thirdArtist = new Artist {
                Id = 3, Name = ArtistName
            };

            firstArtist.Songs.Add(firstSong);

            await db.Songs.AddRangeAsync(firstSong, secondSong, thirdSong);

            await db.Artists.AddRangeAsync(firstArtist, secondArtist, thirdArtist);

            await db.SaveChangesAsync();
        }
Example #3
0
        public ArtistRepositoryTests()
        {
            // set up test data
            var options = new DbContextOptionsBuilder <MusicStoreDbContext>()
                          .UseInMemoryDatabase(databaseName: "test_db" + Guid.NewGuid().ToString())
                          .Options;

            this.db = new MusicStoreDbContext(options);
            foreach (string g in _validGenres)
            {
                this.db.Genres.Add(new DbGenre {
                    Name = g, CreatedUtc = DateTime.UtcNow
                });
            }
            var imageResource = new DbImageResource()
            {
                MimeType = "img/png",
                Data     = new byte[10]
            };

            db.ImageResources.Add(imageResource);

            db.SaveChanges();
            _validImageId = imageResource.Id;

            var loggerMock = new Mock <ILogger <ArtistController> >();

            this.repo = new ArtistRepository(this.db, new ArtistMapper());
        }
 public RoleManageController()
 {
     if (_context == null)
     {
         _context = new MusicStoreDbContext();
     }
     _role = new Repository <Role>(_context);
 }
 public UserManageController()
 {
     if (_context == null)
     {
         _context = new MusicStoreDbContext();
     }
     _user = new Repository <User>(_context);
 }
Example #6
0
        public CheckoutController(MusicStoreDbContext dbContext)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException("dbContext");
            }

            _dbContext = dbContext;
        }
 public LoginController()
 {
     if (_context == null)
     {
         _context = new MusicStoreDbContext();
     }
     _repository = new Repository <User>(_context);
     _role       = new Repository <Role>(_context);
     _car        = new Repository <ShoppingCart>(_context);
     _rule       = new Repository <Rule>(_context);
 }
Example #8
0
        public ShoppingCartController(
            MusicStoreDbContext dbContext,
            IMediator mediator)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException("dbContext");
            }

            _dbContext = dbContext;
            _mediator  = mediator;
        }
        public AlbumGroupRepositoryTests()
        {
            // set up test data
            var options = new DbContextOptionsBuilder <MusicStoreDbContext>()
                          .UseInMemoryDatabase(databaseName: "test_db" + Guid.NewGuid().ToString())
                          .Options;

            this.db = new MusicStoreDbContext(options);


            var loggerMock = new Mock <ILogger <ArtistController> >();

            this.repo = new AlbumGroupRepository(this.db, new AlbumGroupMapper());
        }
Example #10
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var db = new MusicStoreDbContext();

            var user = db.Users.FirstOrDefault(u => u.Email == (string)value);

            if (user == null)
            {
                return(ValidationResult.Success);
            }
            else
            {
                return(new ValidationResult("Mail already exists"));
            }
        }
Example #11
0
 public DatabaseSeeder(
     IConfiguration configuration,
     UserManager <DbUser> userManager,
     RoleManager <DbRole> roleManager,
     MusicStoreDbContext context,
     ILogger <DatabaseSeeder> logger,
     ConfigurationDbContext identityServerConfigContext,
     PersistedGrantDbContext identityServerPersistedGrantContext)
 {
     _configuration = configuration;
     _userManager   = userManager;
     _roleManager   = roleManager;
     _identityServerPersistedGrantContext = identityServerPersistedGrantContext;
     _identityServerConfigContext         = identityServerConfigContext;
     _context = context;
     _logger  = logger;
 }
        public GenreRepositoryTests()
        {
            var options = new DbContextOptionsBuilder <MusicStoreDbContext>()
                          .UseInMemoryDatabase(databaseName: "test_db" + Guid.NewGuid().ToString())
                          .Options;

            this.db = new MusicStoreDbContext(options);

            this.db.Genres.Add(new DbGenre()
            {
                Name = _existingGenreName, CreatedUtc = DateTime.UtcNow
            });
            this.db.SaveChanges();


            var loggerMock = new Mock <ILogger <ArtistController> >();

            this.repo = new GenreRepository(this.db);
        }
Example #13
0
 protected BaseService(MusicStoreDbContext dbContext,
                       SignInManager <MusicStoreUser> signIn)
 {
     this.DbContext = dbContext;
     this.SignIn    = signIn;
 }
Example #14
0
 public TrackRepository(MusicStoreDbContext context) : base(context)
 {
 }
Example #15
0
 public HomeController(MusicStoreDbContext dbContext) : base(dbContext)
 {
 }
Example #16
0
 public SqlGenreData(MusicStoreDbContext context)
 {
     _context = context;
 }
Example #17
0
 public AuthService(MusicStoreDbContext dbContext, JwtHelper jwtHelper, Encryptor encryptor)
 {
     _dbContext = dbContext;
     _jwtHelper = jwtHelper;
     _encryptor = encryptor;
 }
 public EFAlbumRepository(MusicStoreDbContext dbContext)
 {
     _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
 }
Example #19
0
 public TopSellingAlbumsHandler(MusicStoreDbContext dbContext)
 {
     _dbContext = dbContext;
 }
        //public ArtistRepository(MusicStoreDbContext context) : base(context) { }

        //public async Task<bool> ArtistExistsAsync(Guid id) => await _context.Artist.AnyAsync(a => a.Id == id.ToString());

        //public void CreateArtist(Artist artist) => Create(artist);

        //public void DeleteArtist(Artist artist)=> Delete(artist);

        //public async Task<IEnumerable<Artist>> GetAllArtistsAsync() => await GetAll().ToListAsync();

        //public async Task<Artist> GetArtistByIdAsync(Guid id) => await GetByCondition(a => a.Id == id.ToString()).FirstOrDefaultAsync();

        //public void UpdateArtist(Artist artist) => Update(artist);


        public ArtistRepository(MusicStoreDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }
 public AlbumRepository(MusicStoreDbContext context) : base(context)
 {
 }
Example #22
0
 public AdminSongService(MusicStoreDbContext db)
 {
     this.db = db;
 }
Example #23
0
 public StoreController(MusicStoreDbContext dbContext)
 {
     _dbContext = dbContext;
 }
 public ShoppingService(MusicStoreDbContext db)
 {
     this.db = db;
 }
        public async Task <IActionResult> RunMigrationPosted([FromQuery] string migrationName, [FromServices] MusicStoreDbContext context, [FromServices] IHostingEnvironment env, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (!_migrations.Contains(migrationName))
            {
                return(NoContent());
            }

            migrationName = _migrations.Single(x => x.Eq(migrationName));

            var file = env.ContentRootFileProvider.GetFileInfo(Path.Combine("wwwroot", "data", $"{migrationName}.json"));

            JArray array = null;

            if (file.Exists)
            {
                using (var stream = file.CreateReadStream())
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                        using (var jReader = new JsonTextReader(reader))
                        {
                            array = await JArray.LoadAsync(jReader, cancellationToken);
                        }
            }

            if (string.Compare("genres", migrationName, true) == 0)
            {
                List <Genre> genres = new List <Genre>();
                foreach (JObject item in array)
                {
                    string name = item.GetValue("name").Value <string>();

                    genres.Add(new Genre()
                    {
                        Name = name
                    });
                }
                await context.Genres.AddRangeAsync(genres);

                await context.SaveChangesAsync();
            }
            else if (string.Compare("artists", migrationName, true) == 0)
            {
                List <Artist> artists = new List <Artist>();
                foreach (JObject item in array)
                {
                    string name = item.GetValue("name").Value <string>();

                    artists.Add(new Artist()
                    {
                        Name = name
                    });
                }
                await context.Artists.AddRangeAsync(artists);

                await context.SaveChangesAsync();
            }
            else if (string.Compare("albums", migrationName, true) == 0)
            {
                Dictionary <string, Genre>  genres  = new Dictionary <string, Genre>();
                Dictionary <string, Artist> artists = new Dictionary <string, Artist>();
                List <Album> albums = new List <Album>();

                foreach (JObject item in array)
                {
                    string  name     = item.GetValue("name").Value <string>();
                    decimal price    = item.GetValue("price").Value <decimal>();
                    string  albumUrl = item.GetValue("albumArtUrl").Value <string>();
                    string  artist   = item.GetValue("artist").Value <string>();
                    string  genre    = item.GetValue("genre").Value <string>();

                    if (!genres.ContainsKey(genre))
                    {
                        var genDb = await context.Genres.FirstOrDefaultAsync(x => x.Name == genre);

                        genres.Add(genre, genDb);
                    }
                    if (!artists.ContainsKey(artist))
                    {
                        var artDb = await context.Artists.FirstOrDefaultAsync(x => x.Name == artist);

                        artists.Add(artist, artDb);
                    }


                    albums.Add(new Album
                    {
                        Title       = name,
                        Price       = price,
                        AlbumArtUrl = albumUrl,
                        Genre       = genres[genre],
                        Artist      = artists[artist]
                    });
                }
                await context.Albums.AddRangeAsync(albums);

                await context.SaveChangesAsync();
            }

            return(RedirectToAction(nameof(Index)));
        }
Example #26
0
 public AdminArtistService(MusicStoreDbContext db)
 {
     this.db = db;
 }
Example #27
0
        public AlbumRepository_ListByAlbumGroupKeyTests()
        {
            // set up test data
            var options = new DbContextOptionsBuilder <MusicStoreDbContext>()
                          .UseInMemoryDatabase(databaseName: "test_db" + Guid.NewGuid().ToString())
                          .Options;

            this.db = new MusicStoreDbContext(options);
            foreach (string g in _validGenres)
            {
                this.db.Genres.Add(new DbGenre {
                    Name = g, CreatedUtc = DateTime.UtcNow
                });
            }
            var imageResource = new DbImageResource()
            {
                MimeType = "img/png",
                Data     = new byte[10]
            };
            var artist = new DbArtist
            {
                BioText       = "",
                CreatedUtc    = DateTime.UtcNow,
                Name          = "test artist",
                PublishStatus = DbPublishedStatus.PUBLISHED,
                UpdatedUtc    = DateTime.UtcNow
            };

            db.ImageResources.Add(imageResource);
            db.Artists.Add(artist);

            List <DbAlbum> testAlbums = new List <DbAlbum>();

            for (int i = 0; i < 10; i++)
            {
                testAlbums.Add(new DbAlbum
                {
                    Title         = "test_album_" + i,
                    CreatedUtc    = DateTime.UtcNow,
                    PublishStatus = DbPublishedStatus.PUBLISHED,
                    ReleaseDate   = DateTime.Now,
                    UpdatedUtc    = DateTime.UtcNow,
                    Artist        = new DbArtist
                    {
                        Name          = "test artist " + i,
                        PublishStatus = DbPublishedStatus.PUBLISHED,
                        CreatedUtc    = DateTime.UtcNow,
                        UpdatedUtc    = DateTime.UtcNow
                    }
                });
            }
            this.db.Albums.AddRange(testAlbums);

            var group = new DbAlbumGroup
            {
                CreatedUtc = DateTime.UtcNow,
                Key        = VALID_GROUP_KEY,
                Name       = "test group",
                UpdatedUtc = DateTime.UtcNow
            };

            db.AlbumGroups.Add(group);
            db.SaveChanges();
            _validImageId  = imageResource.Id;
            _validArtistId = artist.Id;
            _validGroupId  = group.Id;
            _validAlbumIds = testAlbums.Select(x => x.Id).ToArray();
            for (int i = 0; i < _validAlbumIds.Length; i++)
            {
                // insert all albums into the test group
                db.AlbumGroupListPositions.Add(new DbAlbumGroupAlbumPosition
                {
                    AlbumId       = _validAlbumIds[i],
                    GroupId       = _validGroupId,
                    CreatedUtc    = DateTime.UtcNow,
                    PositionIndex = i
                });
            }
            db.SaveChanges();

            var loggerMock = new Mock <ILogger <ArtistController> >();

            this.repo = new AlbumRepository(this.db, new AlbumMapper());
        }
 public ArtistRepository(MusicStoreDbContext context, ArtistMapper mapper)
 {
     _context = context;
     _mapper  = mapper;
 }
 public AlbumRepository(MusicStoreDbContext context, AlbumMapper mapper)
 {
     _context = context;
     _mapper  = mapper;
 }
 public AccountController(UserManager <User> userManager, SignInManager <User> signInManager, MusicStoreDbContext context)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _context       = context;
 }