Ejemplo n.º 1
0
        public async Task <IActionResult> OnPostRemoveAddressAsync(Guid addressId)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            try
            {
                var address = await _context.Addresses.FirstOrDefaultAsync(x => x.Id == addressId);

                var userAddress = await _context.UserAddresses
                                  .FirstOrDefaultAsync(x => x.AddressId == addressId && x.UserId == user.Id);

                _context.UserAddresses.Remove(userAddress);

                await _context.SaveChangesAsync();

                _context.Addresses.Remove(address);

                await _context.SaveChangesAsync();

                return(RedirectToPage("./Index"));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.InnerException);
            }

            return(Page());
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> OnPostAcceptAsync(string id)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            Friendships = await _context.Friendships
                          .Include(f => f.Receiver)
                          .Include(f => f.Sender)
                          .Where(x => x.ReceiverId == user.Id || x.SenderId == user.Id).ToListAsync();

            var friendship = Friendships.FirstOrDefault(x => x.ReceiverId == id || x.SenderId == id);

            friendship.RequestStatus = FriendStatusCode.Accepted;

            try
            {
                _context.Friendships.Update(friendship);
                await _context.SaveChangesAsync();

                StatusMessage = $"You have accepted their friend request.";
                return(RedirectToPage("Index"));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.InnerException);
            }

            StatusMessage = $"Error: Couldn't accept friend.";
            return(Page());
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Returns a cart by user. If no cart exists then a new one will be created.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static async Task <ShoppingCart> GetCartAsync(this TurboGamesContext context,
                                                             User user)
        {
            var cart = await context.Carts.Include(c => c.User).FirstOrDefaultAsync(c => c.User == user && !c.IsCheckedOut);

            if (cart == null)
            {
                cart = new ShoppingCart {
                    Id = Guid.NewGuid(), UserId = user.Id
                };

                try
                {
                    await context.Carts.AddAsync(cart);

                    await context.SaveChangesAsync();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.InnerException);

                    return(await Task.FromResult <ShoppingCart>(null));
                }
            }
            return(cart);
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> OnPostAsync(Guid?id)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            if (id == null)
            {
                return(RedirectToPage("/Admin/Games/Index"));
            }

            Game = await _context.Games.FindAsync(id);

            if (Game != null)
            {
                var userGames = _context.UserGames.Where(x => x.GameId == id);
                if (userGames != null)
                {
                    _context.UserGames.RemoveRange(userGames);
                }

                _context.Games.Remove(Game);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Returns a wishlist by user. If no wishlist exists then a new one will be created.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static async Task <Wishlist> GetWishlistAsync(this TurboGamesContext context,
                                                             User user)
        {
            var wishlist = await context.Wishlists.Include(c => c.User).FirstOrDefaultAsync(c => c.User == user && !c.AlreadyExists);

            if (wishlist == null)
            {
                wishlist = new Wishlist {
                    Id = Guid.NewGuid(), UserId = user.Id
                };

                try
                {
                    await context.Wishlists.AddAsync(wishlist);

                    await context.SaveChangesAsync();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.InnerException);

                    return(await Task.FromResult <Wishlist>(null));
                }
            }
            return(wishlist);
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.Attach(Event).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EventExists(Event.Id))
                {
                    return(RedirectToPage("/Admin/Events/Index"));
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("./Index"));
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> OnPostRegisterAsync(Guid eventId)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            var userEvent = await _context.UserEvents.FirstOrDefaultAsync(x => x.EventId == eventId);

            if (userEvent != null)
            {
                StatusMessage = $"Error: You have already registered for the '{_context.Events.FirstOrDefault(x => x.Id == userEvent.EventId).Title}' event.";
                return(RedirectToPage());
            }

            try
            {
                _context.UserEvents.Add(
                    new UserEvent
                {
                    EventId = eventId,
                    UserId  = user.Id
                }
                    );

                await _context.SaveChangesAsync();

                StatusMessage = $"You have registered for the '{_context.Events.FirstOrDefault(x => x.Id == eventId).Title}' event.";
                return(RedirectToPage("Index"));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.InnerException);
            }

            return(RedirectToPage());
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            try
            {
                await _context.Addresses.AddAsync(Address);

                await _context.SaveChangesAsync();

                await _context.UserAddresses.AddAsync(new UserAddress
                {
                    UserId    = user.Id,
                    AddressId = Address.Id
                });

                await _context.SaveChangesAsync();

                return(RedirectToPage("./Index"));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.InnerException);
            }

            return(Page());
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            if (!ModelState.IsValid)
            {
                SetDropdownLists();

                return(Page());
            }

            var game = new Game
            {
                Id          = Input.Id,
                Title       = Input.Title,
                Developer   = Input.Developer,
                Description = Input.Description,
                PlatformId  = Input.PlatformId,
                CategoryId  = Input.CategoryId,
                Price       = Input.Price
            };

            _context.Attach(game).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GameExists(game.Id))
                {
                    return(RedirectToPage("/Admin/Games/Index"));
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("./Index"));
        }
Ejemplo n.º 10
0
        public static async Task <bool> AddToWishlistAsync(this TurboGamesContext context, Wishlist wishlist, Game game)
        {
            try
            {
                await context.WishlistGames.AddAsync(new WishlistGame { WishlistId = wishlist.Id, GameId = game.Id });

                await context.SaveChangesAsync();

                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.InnerException);

                return(false);
            }
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Unable to save.");
                return(Page());
            }

            try
            {
                var payment = new Payment
                {
                    CardName           = Payment.CardName,
                    CardNumber         = Payment.CardNumber,
                    CardExpirationDate = Payment.CardExpirationDate,
                    CardCVC            = Payment.CardCVC
                };

                _context.Payments.Add(payment);

                user.PaymentId = payment.Id;

                await _context.SaveChangesAsync();

                await _userManager.UpdateAsync(user);

                await _signInManager.RefreshSignInAsync(user);

                StatusMessage = "Your payment information has been updated";
                return(RedirectToPage());
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.InnerException);
            }

            return(Page());
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Attempts to add a game to the cart by cart and game.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cart"></param>
        /// <param name="game"></param>
        /// <returns></returns>
        public static async Task <bool> AddToCartAsync(this TurboGamesContext context,
                                                       ShoppingCart cart, Game game)
        {
            try
            {
                await context.CartGames.AddAsync(new ShoppingCartGame { CartId = cart.Id, GameId = game.Id });

                await context.SaveChangesAsync();

                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.InnerException);

                return(false);
            }
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.Events.Add(Event);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> OnPostRemoveAsync(Guid gameId)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            if (!await _context.HasCartAsync(user))
            {
                IsCartEmpty = true;
                return(Page());
            }

            var cart = await _context.GetCartAsync(user);

            if (await _context.GetCartItemCount(cart) == 0)
            {
                IsCartEmpty = true;
                return(Page());
            }

            var cartItems = _context.CartGames
                            .Include(cg => cg.Game)
                            .ThenInclude(g => g.Category)
                            .Where(cg => cg.CartId == cart.Id);

            try
            {
                var cartGame = await cartItems.FirstOrDefaultAsync(ci => ci.GameId == gameId && ci.Cart == cart);

                _context.CartGames.Remove(cartGame);

                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.InnerException);
            }

            return(RedirectToPage());
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            if (!ModelState.IsValid)
            {
                SetDropdownLists();
                return(Page());
            }

            try
            {
                await _context.Games.AddAsync(new Game
                {
                    Title       = Input.Title,
                    Developer   = Input.Developer,
                    Description = Input.Description,
                    PlatformId  = Input.PlatformId,
                    CategoryId  = Input.CategoryId,
                    Price       = Input.Price
                });

                await _context.SaveChangesAsync();

                return(RedirectToPage("./Index"));
            }
            catch (Exception e)
            {
                Debug.WriteLine("Error: " + e.InnerException);
            }

            SetDropdownLists();

            return(Page());
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> OnGetAcceptAsync(Guid reviewId)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            var review = await _context.Reviews.FirstOrDefaultAsync(x => x.Id == reviewId);

            if (review == null)
            {
                StatusMessage = $"Error: Unable to find review.";
                return(RedirectToPage());
            }

            if (review.ReviewStatus == ReviewStatus.Accepted)
            {
                StatusMessage = $"Error: You have already accepted the '{_context.Reviews.Include(x => x.Game).FirstOrDefault(x => x.Id == reviewId).Game.Title}' review.";
                return(RedirectToPage());
            }

            try
            {
                review.ReviewStatus = ReviewStatus.Accepted;
                _context.Update(review);

                await _context.SaveChangesAsync();

                StatusMessage = $"You have accepted the '{_context.Reviews.Include(x => x.Game).FirstOrDefault(x => x.Id == reviewId).Game.Title}' review.";
                return(RedirectToPage());
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.InnerException);
            }

            return(RedirectToPage());
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> OnPostAddFriendAsync(string username)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            var friendships = _context.Friendships
                              .Include(x => x.Receiver)
                              .Include(x => x.Sender)
                              .Where(x => x.ReceiverId == user.Id || x.SenderId == user.Id);

            if (friendships.Any(x => (x.Sender.UserName == username || x.Receiver.UserName == username) && x.RequestStatus == FriendStatusCode.Pending))
            {
                StatusMessage = $"Error: There is already a pending friend request for that user.";

                return(RedirectToPage("./Index"));
            }
            else if (friendships.Any(x => (x.Sender.UserName == username || x.Receiver.UserName == username) && x.RequestStatus == FriendStatusCode.Accepted))
            {
                StatusMessage = $"Error: You already have this user added as a friend.";

                return(RedirectToPage("./Index"));
            }

            var receiver = await _userManager.FindByNameAsync(username);

            if (friendships.Any(x => (x.Sender.UserName == username || x.Receiver.UserName == username) && x.RequestStatus == FriendStatusCode.Rejected))
            {
                var friendship = await friendships.FirstOrDefaultAsync(x => (x.Sender.UserName == username || x.Receiver.UserName == username) && x.RequestStatus == FriendStatusCode.Rejected);

                friendship.RequestStatus = FriendStatusCode.Pending;
                friendship.IsFamily      = false;

                try
                {
                    _context.Update(friendship);
                    await _context.SaveChangesAsync();

                    StatusMessage = $"You have sent them a friend request. You must wait for them to accept it.";
                    return(RedirectToPage("./Index"));
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.InnerException);
                }
            }

            var newFriendship = new Friendship
            {
                SenderId   = user.Id,
                ReceiverId = receiver.Id,
                IsFamily   = false
            };

            try
            {
                await _context.AddAsync(newFriendship);

                await _context.SaveChangesAsync();

                StatusMessage = $"You have sent them a friend request. You must wait for them to accept it.";
                return(RedirectToPage("./Index"));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.InnerException);
            }

            return(Page());
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> OnPostReviewGameAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            Game = await _context.GetGameAsync(Id);

            if (Game == null)
            {
                return(NotFound());
            }

            CanReview = await _context.DoesUserOwnGameAsync(user, Game);

            Reviews = await _context.GetGameReviewsAsync(Game);

            if (!CanReview)
            {
                StatusMessage = $"Error: You are not able to review this game.";
                return(RedirectToPage());
            }

            var review = Reviews.FirstOrDefault(r => r.Reviewer == user);

            HasReview = review == null ? false : true;

            try
            {
                if (HasReview)
                {
                    review.ReviewStatus = ReviewStatus.Pending;
                    review.Content      = Review.Content ?? "No review.";
                    review.Rating       = Review.Rating;

                    _context.Attach(review).State = EntityState.Modified;

                    StatusMessage = $"Review saved and is currently pending. Please wait for an administrator to accept it.";
                }
                else
                {
                    await _context.Reviews.AddAsync(new Review { ReviewerId = user.Id, GameId = Game.Id, Content = Review.Content ?? "No review.", Rating = Review.Rating });

                    StatusMessage = $"Review posted and is currently pending. Please wait for an administrator to accept it.";
                }

                await _context.SaveChangesAsync();

                return(RedirectToPage());
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ReviewExists(Review.Id))
                {
                    StatusMessage = $"Error: An unknown error has occurred while trying to post your review.";
                    return(RedirectToPage());
                }
                else
                {
                    throw;
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Creates the applications roles, admin account and a user account for testing.
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <returns></returns>
        public static async Task CreateRoles(IServiceProvider serviceProvider, IConfiguration configuration, TurboGamesContext context)
        {
            var RoleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();
            var UserManager = serviceProvider.GetRequiredService <UserManager <User> >();

            string[] roleNames = { "Admin", "Member" };

            foreach (var roleName in roleNames)
            {
                var roleExist = await RoleManager.RoleExistsAsync(roleName);

                if (!roleExist)
                {
                    await RoleManager.CreateAsync(new IdentityRole(roleName));
                }
            }

            var admin = new User
            {
                FirstName      = "Turbo",
                LastName       = "Admin",
                UserName       = configuration.GetSection("AdminSettings")["Username"],
                Email          = configuration.GetSection("AdminSettings")["Email"],
                EmailConfirmed = true,
                Gender         = Gender.Other,
                DOB            = DateTime.UtcNow,
                PaymentId      = Guid.Parse("1c3e6619-7425-40de-944b-e07fc1f90ae7")
            };

            var user = new User
            {
                FirstName      = "Turbo",
                LastName       = "User",
                UserName       = configuration.GetSection("UserSettings")["Username"],
                Email          = configuration.GetSection("UserSettings")["Email"],
                EmailConfirmed = true,
                Gender         = Gender.Other,
                DOB            = DateTime.UtcNow,
                PaymentId      = Guid.Parse("1c3e6619-7425-40de-944b-e07fc1f90ae7")
            };

            string adminPassword = configuration.GetSection("AdminSettings")["Password"];
            string userPassword  = configuration.GetSection("UserSettings")["Password"];

            var _admin = await UserManager.FindByEmailAsync(configuration.GetSection("AdminSettings")["Email"]);

            if (_admin == null)
            {
                var createAdmin = await UserManager.CreateAsync(admin, adminPassword);

                if (createAdmin.Succeeded)
                {
                    await UserManager.AddToRoleAsync(admin, "Admin");
                }
            }

            var _user = await UserManager.FindByEmailAsync(configuration.GetSection("UserSettings")["Email"]);

            if (_user == null)
            {
                var createUser = await UserManager.CreateAsync(user, userPassword);

                if (createUser.Succeeded)
                {
                    var addRoleToUser = await UserManager.AddToRoleAsync(user, "Member");

                    if (addRoleToUser.Succeeded)
                    {
                        context.UserGames.Add(
                            new UserGame
                        {
                            UserId       = user.Id,
                            GameId       = Guid.Parse("2c9e6679-7425-40de-944b-e07fc1f90ae7"),
                            PurchaseDate = DateTime.UtcNow
                        });
                        await context.SaveChangesAsync();
                    }
                }
            }
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            if (!await _context.HasCartAsync(user))
            {
                return(RedirectToPage("./Index"));
            }

            if (BillingAddress.Id != null && BillingAddress.Id != Guid.Parse("00000000-0000-0000-0000-000000000000"))
            {
                BillingAddress = await _context.Addresses.FirstOrDefaultAsync(a => a.Id == BillingAddress.Id);
            }

            if (ShippingAddress.Id != null && ShippingAddress.Id != Guid.Parse("00000000-0000-0000-0000-000000000000"))
            {
                ShippingAddress = await _context.Addresses.FirstOrDefaultAsync(a => a.Id == ShippingAddress.Id);
            }

            if (Payment.Id != null && Payment.Id != Guid.Parse("00000000-0000-0000-0000-000000000000"))
            {
                Payment = await _context.Payments.FirstOrDefaultAsync(a => a.Id == Payment.Id);
            }

            if (IsSameAddress)
            {
                ShippingAddress = BillingAddress;
            }

            ModelState.Clear();

            if (!TryValidateModel(BillingAddress))
            {
                Debug.WriteLine("BillingAddress fail");
            }

            if (!TryValidateModel(ShippingAddress))
            {
                Debug.WriteLine("ShippingAddress fail");
            }

            if (!TryValidateModel(Payment))
            {
                Debug.WriteLine("Payment fail");
            }

            if (!ModelState.IsValid)
            {
                StatusMessage = $"Error: Unable to purchase game(s). Please check your information and try again.";
                return(RedirectToPage());
            }

            var cart = await _context.GetCartAsync(user);

            CartCount = await _context.GetCartItemCount(cart);

            if (CartCount == 0)
            {
                return(RedirectToPage("./Index"));
            }

            var cartGames = _context.CartGames.Include(x => x.Game).Where(x => x.CartId == cart.Id);

            if (cartGames == null)
            {
                return(RedirectToPage("./Index"));
            }

            try
            {
                cart.IsCheckedOut = true;
                _context.Carts.Update(cart);

                foreach (var item in cartGames)
                {
                    await _context.AddAsync(new UserGame
                    {
                        GameId = item.Game.Id,
                        UserId = user.Id
                    });
                }

                await _context.SaveChangesAsync();

                return(RedirectToPage("./Confirmation", new { cartId = cart.Id }));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.InnerException);
            }

            return(Page());
        }