Esempio n. 1
0
             public ActionResult Registration(Models.UserModel user)
             {
                 if (ModelState.IsValid)
                 {
                     using (var db= new MusicStoreContext())
                     {

                         var crypto = new SimpleCrypto.PBKDF2();
                         var encrypPass = crypto.Compute(user.Password);
                         var sysUser = db.User.Create();

                         sysUser.Email = user.Email;
                         sysUser.Password = encrypPass;
                         sysUser.PasswordSalt = crypto.Salt;

                         db.User.Add(sysUser);
                         db.SaveChanges();

                         return RedirectToAction("List", "Product");

                     }

                 }

                 return View(user);
             }
Esempio n. 2
0
 public StoreController(
     IGenreService genreService,
     MusicStoreContext dbContext,
     IOptions <AppSettings> options)
 {
     _genreService = genreService;
     _dbContext    = dbContext;
     _appSettings  = options.Value;
 }
Esempio n. 3
0
 public List <ArtistDTO> GetAllEnabled()
 {
     using (MusicStoreContext db = new MusicStoreContext())
     {
         List <Artists> records = new List <Artists>();
         records = db.Artists.Where(x => x.Enable == true).ToList();
         return(_mapper.Map <List <ArtistDTO> >(records));
     }
 }
Esempio n. 4
0
 public List <ArtistDTO> GetAll()
 {
     using (MusicStoreContext db = new MusicStoreContext())
     {
         List <Artists> records = new List <Artists>();
         records = db.Artists.ToList();
         return(_mapper.Map <List <ArtistDTO> >(records));
     }
 }
        private static void PopulateData(MusicStoreContext context)
        {
            var genres = Enumerable.Range(1, 10).Select(n => new Genre {
                GenreId = n
            });

            context.AddRange(genres);
            context.SaveChanges();
        }
Esempio n. 6
0
 private async Task <List <Album> > GetTopSellingAlbumsAsync(MusicStoreContext dbContext, int count)
 {
     // Group the order details by album and return
     // the albums with the highest count
     return(await dbContext.Albums
            .OrderByDescending(a => a.OrderDetails.Count)
            .Take(count)
            .ToListAsync());
 }
Esempio n. 7
0
 public AlbumController(
     IOptions <AppSettings> options,
     [FromServices] IDistributedCache cache,
     [FromServices] MusicStoreContext dbContext
     )
 {
     _appSettings = options.Value;
     _cache       = cache;
     _dbContext   = dbContext;
 }
 public ManageController(MusicStoreContext dbContext, ILogger <ManageController> logger
                         // ,UserManager<ApplicationUser> userManager,
                         // SignInManager<ApplicationUser> signInManager
                         )
 {
     DbContext = dbContext;
     _logger   = logger;
     // UserManager = userManager;
     // SignInManager = signInManager;
 }
Esempio n. 9
0
        private async Task <List <Album> > GetTopSellingAlbumsAsync(MusicStoreContext dbContext, int count)
        {
            // Group the order details by album and return
            // the albums with the highest count

            // TODO [EF] We don't query related data as yet, so the OrderByDescending isn't doing anything
            return(await dbContext.Albums
                   .OrderByDescending(a => a.OrderDetails.Count())
                   .Take(count)
                   .ToListAsync());
        }
Esempio n. 10
0
 public ShoppingCartController(
     IAlbumService albumService,
     IShoppingCartService shoppingCartService,
     MusicStoreContext dbContext,
     ILogger <ShoppingCartController> logger)
 {
     _albumService        = albumService;
     _shoppingCartService = shoppingCartService;
     _dbContext           = dbContext;
     _logger = logger;
 }
        public void Music_store_project_to_mapped_entity()
        {
            var serviceProvider
                = new ServiceCollection()
                    .AddEntityFramework()
                    .AddInMemoryDatabase()
                    .ServiceCollection()
                    .BuildServiceProvider();

            var optionsBuilder = new DbContextOptionsBuilder();
            optionsBuilder.UseInMemoryDatabase();

            using (var db = new MusicStoreContext(serviceProvider, optionsBuilder.Options))
            {
                var albums = GetAlbums("~/Images/placeholder.png", Genres, Artists);

                db.Genres.AddRange(Genres.Values);
                db.Artists.AddRange(Artists.Values);
                db.Albums.AddRange(albums);

                db.SaveChanges();
            }

            using (var db = new MusicStoreContext(serviceProvider, optionsBuilder.Options))
            {
                var q = from album in db.Albums
                    join genre in db.Genres on album.GenreId equals genre.GenreId
                    join artist in db.Artists on album.ArtistId equals artist.ArtistId
                    select new Album
                        {
                            ArtistId = album.ArtistId,
                            AlbumArtUrl = album.AlbumArtUrl,
                            AlbumId = album.AlbumId,
                            GenreId = album.GenreId,
                            Price = album.Price,
                            Title = album.Title,
                            Artist = new Artist
                                {
                                    ArtistId = album.ArtistId,
                                    Name = artist.Name
                                },
                            Genre = new Genre
                                {
                                    GenreId = album.GenreId,
                                    Name = genre.Name
                                }
                        };

                var albums = q.ToList();

                Assert.Equal(462, albums.Count);
            }
        }
Esempio n. 12
0
        private static string EnterSong(RequestConsumer reqConsumer, string controller)
        {
            Console.WriteLine("Enter title: ");
            string title = Console.ReadLine();

            Console.WriteLine("Enter genre(optional): ");
            string genre = Console.ReadLine();

            Console.WriteLine("Enter release date(optional): ");
            DateTime?releaseDate = null;

            try
            {
                releaseDate = DateTime.Parse(Console.ReadLine());
            }
            catch (FormatException ex)
            {
            }

            MusicStoreContext db = new MusicStoreContext();

            Console.WriteLine("Artist Name(optional): ");
            string artistName = Console.ReadLine();

            var artist = (from a in db.Artists
                          where a.Name == artistName
                          select a
                          ).FirstOrDefault();

            Song newSong = new Song()
            {
                Title = title,
                Genre = genre,
                Year  = releaseDate
            };

            newSong.Artist = CreateArtistObject(artist.ArtistId, artist.Name, artist.Country, artist.DateOfBirth);

            Console.WriteLine("As Json(1) Or XML(2)? ");
            string choice = Console.ReadLine();

            if (choice == "1")
            {
                var sent = reqConsumer.CreateAsJson <Song>(newSong, controller);
                return(sent);
            }
            else
            {
                var sent = reqConsumer.CreateAsXML <Song>(newSong, controller);
                return(sent);
            }
        }
Esempio n. 13
0
 public RegisterModel(
     UserManager <IdentityUser> userManager,
     SignInManager <IdentityUser> signInManager,
     ILogger <RegisterModel> logger,
     IEmailSender emailSender,
     MusicStoreContext context)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _logger        = logger;
     _emailSender   = emailSender;
     _context       = context;
 }
        public async Task <IEnumerable <Album> > Albums()
        {
            // For demonstration create individual instance
            var ctxt = new MusicStoreContext();

            var result = await ctxt.Albums
                         .Include(ctx => ctx.Tracks)
                         .Include(ctx => ctx.Artist)
                         .OrderBy(alb => alb.Title)
                         .ToListAsync();

            return(result);
        }
        /// <summary>
        /// This method gets all albums from the database
        /// </summary>
        private void GetAllAlbums()
        {
            using (MusicStoreContext dataSource = new MusicStoreContext())
            {
                //Query the Album Table using EF and LINQ
                var albums = (from allAlbums in dataSource.Albums
                              select allAlbums);

                AlbamDataList.DataSource = albums.ToList();

                // bind the result to the Album GridView
                AlbamDataList.DataBind();
            }
        }
Esempio n. 16
0
            public async Task <object> Complete(MusicStoreContext context, int id)
            {
                var userName = "******";

                var isValid = await context.Orders.AnyAsync(
                    o => o.OrderId == id && o.Username == userName);

                if (isValid)
                {
                    return(id);
                }

                return("Error");
            }
Esempio n. 17
0
        public HomeController(
            IMusicRepository musicRepository,
            IUserRepository userRepository,
            IMusicRepository_ADONET musicRepository_adonet,
            IUserRepository_ADONET userRepository_ADONET,
            MusicStoreContext efContext)
        {
            _musicRepository = musicRepository;
            _userRepository  = userRepository;

            _musicRepository_adonet = musicRepository_adonet;
            _userRepository_ADONET  = userRepository_ADONET;

            _efContext = efContext;
        }
        static void Main()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<MusicStoreContext, Configuration>());
            
            MusicStoreContext context = new MusicStoreContext();

            Artist artist = new Artist()
            {
                Name = "Gosho",
                Country = "Bulgaria",
                DateOfBirth = new DateTime(2012, 5, 5)
            };

            context.Artists.Add(artist);
            context.SaveChanges();
        }
Esempio n. 19
0
        /// <summary>
        /// This Method gets the products data from the DataBase
        /// </summary>

        /*private void getMusicItem()
         * {
         *  using (MusicStoreContext dataSource = new MusicStoreContext())
         *  {
         *      //Query the Album Table using EF and LINQ
         *      var albums = (from allAlbums in dataSource.Albums
         *                      select allAlbums);
         *      // bind the result to the Album GridView
         *      MusicGridView.DataSource = albums.ToList();
         *
         *      ///MusicGridView.DataSource = albums.AsQueryable().OrderBy(SortString).ToList();
         *      MusicGridView.DataBind();
         *  }
         * }*/
        private void getMusicItem()
        {
            int GenreId = Convert.ToInt32(Request.QueryString["GenreId"]);

            using (MusicStoreContext dataSource = new MusicStoreContext())
            {
                //Query the Album Table using EF and LINQ
                var albums = (from allAlbums in dataSource.Albums where allAlbums.GenreId == GenreId
                              select allAlbums);
                // bind the result to the Album GridView
                AlbamDataList.DataSource = albums.ToList();

                ///MusicGridView.DataSource = albums.AsQueryable().OrderBy(SortString).ToList();
                AlbamDataList.DataBind();
            }
        }
Esempio n. 20
0
        public MusicStoreContext CreateMusicStoreContext()
        {
            if (_connection == null)
            {
                _connection = new SqliteConnection("DataSource=:memory:");
                _connection.Open();

                var options = CreateOptions();
                using (var context = new MusicStoreContext(options))
                {
                    context.Database.EnsureCreated();
                }
            }

            return(new MusicStoreContext(CreateOptions()));
        }
        public async Task <IActionResult> AddressAndPayment(
            [FromServices] MusicStoreContext dbContext,
            [FromForm] Order order,
            CancellationToken requestAborted)
        {
            if (!ModelState.IsValid)
            {
                return(View(order));
            }

            var formCollection = await HttpContext.Request.ReadFormAsync();

            try
            {
                if (string.Equals(formCollection["PromoCode"].FirstOrDefault(), PromoCode,
                                  StringComparison.OrdinalIgnoreCase) == false)
                {
                    return(View(order));
                }
                else
                {
                    order.Username  = HttpContext.User.Identity.Name;
                    order.OrderDate = DateTime.Now;

                    //Add the Order
                    dbContext.Orders.Add(order);

                    //Process the order
                    var cart = ShoppingCart.GetCart(dbContext, HttpContext);
                    await cart.CreateOrder(order);

                    _logger.LogInformation("User {userName} started checkout of {orderId}.", order.Username, order.OrderId);

                    // Save all changes
                    await dbContext.SaveChangesAsync(requestAborted);

                    return(RedirectToAction("Complete", new { id = order.OrderId }));
                }
            }

            catch (Exception ex)
            {
                _logger.LogError("Error occured while checkout.\r\n" + ex, order.Username, order.OrderId);
                //Invalid - redisplay with errors
                return(View(order));
            }
        }
Esempio n. 22
0
        public async Task <AlbumViewModel> GetAlbumById(int id)
        {
            var album     = new AlbumViewModel();
            var db        = new MusicStoreContext();
            var exitAlbum = await _db.Album.FirstOrDefaultAsync(s => s.AlbumId == id);

            if (exitAlbum != null)
            {
                album.AlbumId    = exitAlbum.AlbumId;
                album.ArtistName = exitAlbum.ArtistName;
                album.Title      = exitAlbum.Title;
                album.GenreName  = exitAlbum.GenreName;
                album.Price      = exitAlbum.Price;
                album.PublicDate = exitAlbum.PublicDate;
            }
            return(album);
        }
        /// <summary>
        /// This method gets the album from the Database
        /// </summary>
        private void BindAlbum()
        {
            int albumId = Convert.ToInt32(Request.QueryString["AlbumId"]);

            using (MusicStoreContext db = new MusicStoreContext())
            {
                var album = (from oneAlbum in db.Albums
                             join artist in db.Artists
                             on oneAlbum.ArtistId equals artist.ArtistId
                             join genre in db.Genres
                             on oneAlbum.GenreId equals genre.GenreId
                             where oneAlbum.AlbumId == albumId
                             select new { AlbumArtUrl = oneAlbum.AlbumArtUrl, Title = oneAlbum.Title, Genre = genre.Name, Name = artist.Name, Price = oneAlbum.Price });

                AlbumDetailRepeater.DataSource = album.ToList();
                AlbumDetailRepeater.DataBind();
            }
        }
Esempio n. 24
0
        public long Delete(ArtistDTO entity)
        {
            using (MusicStoreContext db = new MusicStoreContext())
            {
                try
                {
                    var record = db.Artists.Where(x => x.ArtistID == entity.ArtistID).FirstOrDefault();

                    record.Enable = entity.Enable;
                    db.SaveChanges();
                    return(entity.ArtistID);
                }
                catch
                {
                    return(0);
                }
            }
        }
Esempio n. 25
0
        public long Insert(SongDTO entity)
        {
            using (MusicStoreContext db = new MusicStoreContext())
            {
                Songs record = _mapper.Map <Songs>(entity);

                try
                {
                    var tempObj = db.Songs.Add(record);
                    db.SaveChanges();
                    return(entity.SongID);
                }
                catch
                {
                    return(0);
                }
            }
        }
Esempio n. 26
0
        //
        // GET: /Checkout/Complete

        public async Task <IActionResult> Complete(
            [FromServices] MusicStoreContext dbContext,
            int id)
        {
            // Validate customer owns this order
            bool isValid = await dbContext.Orders.AnyAsync(
                o => o.OrderId == id &&
                o.Username == HttpContext.User.GetUserName());

            if (isValid)
            {
                return(View(id));
            }
            else
            {
                return(View("Error"));
            }
        }
Esempio n. 27
0
        public long Insert(ArtistDTO entity)
        {
            using (MusicStoreContext db = new MusicStoreContext())
            {
                Artists record = _mapper.Map <Artists>(entity);

                try
                {
                    var tempObj = db.Artists.Add(record);
                    db.SaveChanges();
                    return(tempObj.ArtistID);
                }
                catch
                {
                    return(0);
                }
            }
        }
        private static void PopulateData(MusicStoreContext context, string cartId, string albumTitle, int itemCount)
        {
            var album = new Album()
            {
                AlbumId = 1,
                Title   = albumTitle,
            };

            var cartItems = Enumerable.Range(1, itemCount).Select(n =>
                                                                  new CartItem()
            {
                AlbumId = 1,
                Album   = album,
                Count   = 1,
                CartId  = cartId,
            }).ToArray();

            context.AddRange(cartItems);
            context.SaveChanges();
        }
Esempio n. 29
0
        //
        // GET: /Home/
        public async Task <IActionResult> Index(
            [FromServices] MusicStoreContext dbContext,
            [FromServices] IDistributedCache cache)
        {
            // Get most popular albums
            var          cacheKey = "topselling";
            List <Album> albums   = null;
            //try get top selling albums from cache
            var cachedalbums = cache.Get(cacheKey);

            if (cachedalbums == null)
            {
                //Get albums from database
                albums = await GetTopSellingAlbumsAsync(dbContext, 6);

                if (albums != null && albums.Count > 0)
                {
                    if (_appSettings.CacheDbResults)
                    {
                        // Refresh it every 10 minutes.
                        cache.Set(
                            cacheKey,
                            Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(albums)),
                            new DistributedCacheEntryOptions()
                        {
                            AbsoluteExpiration =
                                DateTimeOffset.UtcNow.AddMinutes(10)
                        }
                            );
                    }
                }
            }
            else
            {
                //deserialize cached albums
                albums = JsonConvert.
                         DeserializeObject <List <Album> >(System.Text.Encoding.UTF8.GetString(cachedalbums));
            }
            return(View(albums));
        }
        public AlbumControllerTests()
        {
            //Configuring In Memory Store for Unit Tests
            var optionsBuilder = new DbContextOptionsBuilder <MusicStoreContext>();

            optionsBuilder.UseInMemoryDatabase();

            //Create Data Context
            _musicStoreContext = new MusicStoreContext(optionsBuilder.Options);

            //Mocking dependencies
            _appSettings = new AppSettings()
            {
                CacheDbResults = true
            };

            _options = new Mock <IOptions <AppSettings> >();
            _options.SetupGet(p => p.Value).Returns(_appSettings);

            _distributedCache = new Mock <IDistributedCache>();
            _albumController  = new AlbumController(_options.Object, _distributedCache.Object, _musicStoreContext);
        }
Esempio n. 31
0
        static void Main()
        {
            MusicStoreContext context = new MusicStoreContext();

            var album = new Album()
            {
                Title    = "Title",
                Year     = 2013,
                Producer = "Producer"
            };

            context.Albums.Add(album);
            context.SaveChanges();

            var query = from b in context.Albums
                        select b;

            foreach (var item in query)
            {
                Console.WriteLine(item.Title);
            }
        }
Esempio n. 32
0
        public static void SeedDatabaseOrder(MusicStoreContext db)
        {
            var _Order = new Order()
            {
                OrderGuid  = "12345",
                OrderDate  = DateTime.Now,
                UserName   = "******",
                FirstName  = "123345",
                LastName   = "12345",
                Address    = "123214",
                City       = "12345",
                State      = "1234",
                PostalCode = "1234",
                Country    = "123",
                Phone      = "1234",
                Email      = "1234",
                TotalPrice = 123
            };

            db.Order.Add(_Order);
            db.SaveChanges();
        }
Esempio n. 33
0
        public long Update(SongDTO entity)
        {
            using (MusicStoreContext db = new MusicStoreContext())
            {
                try
                {
                    var record = db.Songs.Where(x => x.SongID == entity.SongID).FirstOrDefault();

                    record.ArtistID     = entity.ArtistID;
                    record.Title        = entity.Title;
                    record.YearReleased = entity.YearReleased;
                    record.Enable       = entity.Enable;

                    db.SaveChanges();
                    return(entity.SongID);
                }
                catch
                {
                    return(0);
                }
            }
        }
 public AlbumsController()
 {
     var dbContext = new MusicStoreContext();
     this.albumRepository = new DbAlbumsRepository(dbContext);
 }
Esempio n. 35
0
             private bool isValid(string email, string password)
             {
                 var crypto = new SimpleCrypto.PBKDF2();

                 bool isValid = false;

                 using (var db = new MusicStoreContext())
                 {
                     var user = db.User.FirstOrDefault(u => u.Email == email);

                     if (user != null)
                     {
                         if (user.Password == crypto.Compute(password, user.PasswordSalt))
                         {
                             isValid = true;
                         }
                     }
                 }

                 return isValid;
             }
 public SongsController()
 {
     var context = new MusicStoreContext();
     this.songsRepository = new DbSongsRepository(context);
 }
 public ArtistsController()
 {
     var dbContext = new MusicStoreContext();
     this.artistRepository = new DbArtistsRepository(dbContext);
 }