Exemplo n.º 1
0
        public async Task<ActionResult> SubmitReview(ReviewViewModel model)
        {
            var review = await _hcSerivice.GetReviewByReviewIdAsync(model.ReviewId);
            review.Feedback = model.Feedback;
            review.Mark = model.Mark;
            var result = await _hcSerivice.SubmitReview(review);
            return Json(result);

        }
Exemplo n.º 2
0
        public ReviewToolWindow() :
            base(null)
        {
            Caption = "Review";
            ToolBar = new CommandID(Identifiers.CommandGroupId, MenuCommands.TWToolbar);
            ToolBarLocation = (int)VSTWT_LOCATION.VSTWT_TOP;

            var view = ViewResolver.Resolve<ReviewViewModel>();

            viewModel = ((FrameworkElement)view).DataContext as ReviewViewModel;
            viewModel.PropertyChanged += ViewModelPropertyChanged;

            Content = view;
        }
Exemplo n.º 3
0
        public async Task <IActionResult> PostReview([FromBody] ReviewViewModel model)
        {
            try
            {
                var newReview = await reviewService.AddReviewAsync(model.UserName, model.BeerName,
                                                                   model.Rating, model.RMessage);

                var newReviewModel = new ReviewViewModel(newReview.RMessage, newReview.Rating,
                                                         newReview.User, newReview.UserId, newReview.Beer,
                                                         newReview.BeerId, newReview.ReviewedOn);

                return(Ok(newReviewModel));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
Exemplo n.º 4
0
        public ActionResult Create(ReviewViewModel model)
        {
            if (model != null)
            {
                var reviewDTO = new ReviewDTO
                {
                    Comment = model.Comment.Trim(),
                    UserId  = model.UserId
                };

                reviewService.Create(reviewDTO);

                ModelState.Clear();
                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Exemplo n.º 5
0
        public async Task <IActionResult> Delete(ReviewViewModel reviewViewModel)
        {
            User user = await _userManager.GetUserAsync(User);

            int customerID = user.CustomerID.Value;

            if (!await CheckCustomerIDWithCurrentUser(reviewViewModel.CustomerID))
            {
                return(View("Error", new ErrorViewModel()));
            }

            await _service.RemoveReviewFromItemAsync(customerID, reviewViewModel.ID);

            return(RedirectToAction(
                       "Details",
                       $"{reviewViewModel.Category}s",
                       new { id = reviewViewModel.ItemID }));
        }
Exemplo n.º 6
0
        public IActionResult Update(Guid id)
        {
            ViewBag.AllUsers    = _userManager.GetAllUsers();
            ViewBag.AllProducts = _dataManager.ProductRepository.GetAllEntities().ToList();

            var             review    = _dataManager.ReviewRepository.GetEntity(id);
            ReviewViewModel viewModel = new ReviewViewModel()
            {
                Id        = id,
                Title     = review.Title,
                Text      = review.Text,
                Rating    = review.Rating,
                ProductId = review.Product.Id,
                UserId    = review.User.Id,
            };

            return(View(viewModel));
        }
Exemplo n.º 7
0
        public async System.Threading.Tasks.Task <IActionResult> Review()
        {
            var user = await _userManager.GetUserAsync(User);

            var cart = Cart.GetCart(user.Id);

            /*var _books = (from m in _db.Books
             *            where cart.G)*/

            var viewModel = new ReviewViewModel
            {
                Books     = cart.GetCartItems(),
                CartTotal = cart.GetTotal(),
                //Books = addedItem * cartItem.Count
            };

            return(View(viewModel));
        }
 public IActionResult AddReview(ReviewViewModel model)
 {
     if (ModelState.IsValid)
     {
         Review newReview = new Review
         {
             name            = model.name,
             restaurant_name = model.restaurant_name,
             stars           = model.stars,
             review          = model.review,
             date_of_visit   = model.date_of_visit
         };
         _context.Add(newReview);
         _context.SaveChanges();
         return(RedirectToAction("AllReviews"));
     }
     return(View("Create", model));
 }
        public static ReviewViewModel MapToReviewViewModel(this Book book, string userId)
        {
            var viewModel = new ReviewViewModel();

            viewModel.Id                  = book.Id;
            viewModel.CoverImageUrl       = book.CoverImageUrl;
            viewModel.UserId              = userId;
            viewModel.Title               = book.Title;
            viewModel.AuthorName          = book.Author.Name;
            viewModel.Pages               = book.Pages;
            viewModel.Country             = book.Country;
            viewModel.Language            = book.Language;
            viewModel.SubjectCategoryName = book.SubjectCategory.Name;
            viewModel.Copies              = book.Copies;
            viewModel.Year                = book.Year;
            viewModel.Grade               = book.BookRating?.Rating;
            return(viewModel);
        }
Exemplo n.º 10
0
        public ActionResult Index(ReviewViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (this.reviewProvider.AddEntry(model.NewEntry))
                {
                    model.Message = "Благодарим! Вашето мнение е важно за нас.";
                }
                else
                {
                    model.Message = "Възникна проблем, моля опитайте по-късно.";
                }
            }

            model.PreviousEntries = this.reviewProvider.GetAllEntries();

            return(this.View(model));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Review(int mediaId, ReviewViewModel data)
        {
            return(Forbid());

            var user = await _userManager.GetUserAsync(HttpContext.User);

            //HttpContext.User.Claims.FirstOrDefault(c => c.Type == "DisplayName").Value
            try
            {
                await _repo.AddReviewAsync(mediaId, user.UserName, data.Content);
            }
            catch (ArgumentException)
            {
                return(NotFound());
            }

            return(RedirectToAction(nameof(Detail), mediaId));
        }
Exemplo n.º 12
0
        public async Task Create_WorksProperly()
        {
            var service = await this.CreateReviewService(new List <Review>());

            var expected = new ReviewViewModel()
            {
                Name        = "TestReview",
                Description = "Amazing",
                Type        = "Piece",
                Contents    = "Test"
            };
            var principle = new Mock <ClaimsPrincipal>();

            principle.Setup(u => u.Identity.Name).Returns("*****@*****.**");
            var created = service.Create(expected, principle.Object);

            Assert.AreEqual(expected.Name, created.Name);
        }
        public ActionResult List(int page = 1)
        {
            ReviewViewModel roomView = new ReviewViewModel
            {
                Reviews = unitOfWork.Reviews.Reviews
                          .Skip((page - 1) * pageSize)
                          .Take(pageSize)
                ,
                PagingInfo = new PagingInfo
                {
                    CurrentPage  = page,
                    ItemsPerPage = pageSize,
                    TotalItems   = unitOfWork.Reviews.Reviews.Count()
                }
            };

            return(View(roomView));
        }
Exemplo n.º 14
0
        public IActionResult Add(ReviewViewModel vm)
        {
            //convert the ReviewViewModel to a DTO object accepted by the API and POST it
            var result = _reviewsController.Post(vm.ToDto());

            if (result.GetType() == typeof(OkResult))
            {
                //success message
                SetResultsMessage("Your review has been added sucessfully!");
            }
            else
            {
                //Error
                SetResultsMessage("An unknown error occured while trying to add your review. Please try again.", true);
            }

            return(RedirectToAction(nameof(Index)));
        }
Exemplo n.º 15
0
        public async Task <IActionResult> ReviewAanmaken(int postId)
        {
            Gebruiker gebruiker = await gebruikerContext.GetByNaam(User.Identity.Name);

            Review review = new Review
            {
                PostId      = postId,
                GebruikerId = gebruiker.GebruikerId
            };

            ReviewViewModel reviewViewModel = new ReviewViewModel
            {
                PostId = postId,
                Review = review
            };

            return(View(reviewViewModel));
        }
Exemplo n.º 16
0
        public ReviewDTO AddReview(int userID, int bookID, ReviewViewModel review)
        {
            var user = db.Users.Where(u => u.ID == userID).SingleOrDefault();

            // Check if user exists
            if (user == null)
            {
                throw new NotFoundException(userNotFoundMessage);
            }

            var book = db.Books.Where(b => b.ID == bookID).SingleOrDefault();

            // Check if book exists
            if (book == null)
            {
                throw new NotFoundException(bookNotFoundMessage);
            }


            // Check if review already exists
            if (db.Reviews.Where(r => r.UserID == userID && r.BookID == bookID).Any())
            {
                throw new AlreadyExistsException(reviewAlreadyExistsMessage);
            }

            // Add review
            var reviewEntity = mapper.Map <ReviewViewModel, ReviewEntity>(review);

            reviewEntity.BookID = bookID;
            reviewEntity.UserID = userID;

            db.Reviews.Add(reviewEntity);
            db.SaveChanges();

            var userDTO = mapper.Map <UserEntity, UserDTO>(user);
            var bookDTO = mapper.Map <BookEntity, BookDTO>(book);

            var reviewDTO = mapper.Map <ReviewEntity, ReviewDTO>(reviewEntity);

            reviewDTO.Book = bookDTO;
            reviewDTO.User = userDTO;

            return(reviewDTO);
        }
Exemplo n.º 17
0
        public ReviewView(int reservationId)
        {
            InitializeComponent();

            _reservationId = reservationId;

            BindingContext = model = new ReviewViewModel(_reservationId);



            backImage.Source          = ImageSource.FromResource("OpenRoads.Mobile.Resources.backIcon.png");
            backImage.WidthRequest    = 40;
            backImage.HeightRequest   = 40;
            backImage.CornerRadius    = 25;
            backImage.BackgroundColor = Color.White;

            SignOutBtn.Padding      = new Thickness(3);
            SignOutBtn.CornerRadius = 3;
        }
Exemplo n.º 18
0
        public async Task <IActionResult> EditReview(ReviewViewModel reviewViewModel)
        {
            Recipe recipe = repository.Recipes.FirstOrDefault(r => r.RecipeID == reviewViewModel.RecipeID);

            if (ModelState.IsValid)
            {
                var LoggedUser = await userManager.GetUserAsync(User);

                reviewViewModel.Review.Recipe = recipe;
                reviewViewModel.Review.UserId = LoggedUser.UserName;
                repository.EditReview(reviewViewModel.Review);
                TempData["message"] = $"{reviewViewModel.Review.Title} was Saved";
                return(View("DisplayPage", recipe));
            }
            else
            {
                return(View(reviewViewModel));
            }
        }
Exemplo n.º 19
0
 public IActionResult AddReview(int ActivityID, ReviewViewModel review)
 {
     if (ModelState.IsValid)
     {
         Review reviewToAdd = new Review {
             Title       = review.Title,
             Rating      = review.Rating,
             Description = review.Description,
             ActivityID  = ActivityID,
             ReviewerID  = (int)HttpContext.Session.GetInt32("logged_id")
         };
         _context.Reviews.Add(reviewToAdd);
         _context.SaveChanges();
         return(RedirectToAction("ShowReviews", "Review", new { ActivityID = ActivityID }));
     }
     //if validation fails, reload page with same activity
     ViewBag.Activity = _context.Activities.Include(activity => activity.Creator).Include(activity => activity.UsersAttending).ThenInclude(ua => ua.User).SingleOrDefault(activity => activity.ActivityID == ActivityID);
     return(View("ReviewForm"));
 }
Exemplo n.º 20
0
        public IActionResult UpdateReview(int bookId, int userId, [FromBody] ReviewViewModel updatedReview)
        {
            if (updatedReview == null)
            {
                return(BadRequest());
            }
            if (!ModelState.IsValid)
            {
                return(StatusCode(412));
            }

            var review = _reviewService.UpdateBookReview(userId, bookId, updatedReview);

            if (review == null)
            {
                return(NotFound());
            }
            return(Ok(review));
        }
Exemplo n.º 21
0
        public ReviewViewModel AddReviewByUser(RatingDTO rating, int userID, int bookID)
        {
            if (rating.Rating > 5 || rating.Rating < 0)
            {
                throw new RatingException("Rating can only be from 0 - 5");
            }
            var user = _friends.SingleOrDefault(f => f.ID == userID);

            if (user == null)
            {
                throw new ObjectNotFoundException("User ID not found");
            }
            var book = _books.SingleOrDefault(b => b.ID == bookID);

            if (book == null)
            {
                throw new ObjectNotFoundException("Book ID not found");
            }
            var newReview = new Review {
                friendID = userID,
                bookID   = bookID,
                Rating   = rating.Rating
            };

            var rat = _reviews.Where(x => x.bookID == bookID).ToList();
            var sum = 0;

            foreach (var x in rat)
            {
                sum += x.Rating;
            }
            var avg = sum / rat.Count();

            _reviews.Add(newReview);
            var rev = new ReviewViewModel {
                BookTitle       = book.Title,
                AuthorFirstName = book.FirstName,
                AuthorLastName  = book.LastName,
                Rating          = avg
            };

            return(rev);
        }
Exemplo n.º 22
0
        public IEnumerable <ReviewViewModel> GetReviewsForHotel(int id)
        {
            var rev = HotelHelper.GetReviewsForHotel(id);
            var vms = new List <ReviewViewModel>();

            foreach (var item in rev)
            {
                var vm = new ReviewViewModel
                {
                    Header      = item.ReviewHeader,
                    CurrentDate = item.ReviewDate,
                    Description = item.ReviewDescription,
                    Rating      = int.Parse(item.ReviewScore),
                    User        = unit.GetById(item.UserId)
                };
                vms.Add(vm);
            }
            return(vms);
        }
Exemplo n.º 23
0
        public async Task <IActionResult> Create([Bind("ID,BeerID,UserID,Rating,Description,LikesCount,IsDeleted,IsFlagged")] ReviewViewModel review)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    await _service.CreateAsync(review.MapReviewViewToDTO());

                    return(RedirectToAction(nameof(Details), "Beers", new { id = review.BeerID }));
                }
                catch (Exception)
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            ViewData["BeerID"] = _beerService.GetAsync(review.BeerID);
            ViewData["UserID"] = _userService.GetUser(review.UserID);
            return(View(review));
        }
Exemplo n.º 24
0
        //Action that adds the review to the DB.
        public ActionResult AddReview(ReviewViewModel rev)
        {
            if (Session["username"] == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            ReviewsDal dal    = new ReviewsDal();
            Review     review = new Review();

            if (ModelState.IsValid)
            {
                review      = rev.review;
                review.name = Session["username"].ToString();
                dal.reviews.Add(review);
                dal.SaveChanges();
                return(RedirectToAction("Index", "Home"));
            }
            return(View("Contact"));
        }
Exemplo n.º 25
0
        public async Task <IActionResult> Review(ReservationsRouteModel routeModel)
        {
            GetCachedReservationResult cachedReservation;

            try
            {
                var query = new GetCachedReservationQuery
                {
                    Id = routeModel.Id.GetValueOrDefault()
                };

                cachedReservation = await _mediator.Send(query);
            }
            catch (ValidationException e)
            {
                var errors = new StringBuilder();
                errors.AppendLine();
                foreach (var member in e.ValidationResult.MemberNames)
                {
                    errors.AppendLine(member);
                }

                _logger.LogWarning($"Validation Error when reviewing a reservation: {errors}");

                return(RedirectToRoute(RouteNames.Error500));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(RedirectToRoute(RouteNames.Error500));
            }

            routeModel.FromReview = true;

            var viewModel = new ReviewViewModel(
                routeModel,
                cachedReservation.TrainingDate,
                cachedReservation.CourseDescription,
                cachedReservation.AccountLegalEntityName,
                cachedReservation.AccountLegalEntityPublicHashedId);

            return(View(viewModel.ViewName, viewModel));
        }
        public IActionResult Create([Bind("UserName,Password,SellerName,Score,Comment")] ReviewViewModel viewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (viewModel.Password != RepoPers.GetPeopleByName(viewModel.UserName).First(p => p.Username.ToLower() == viewModel.UserName.ToLower()).Password)
                    {
                        return(View(viewModel));
                    }
                    var review = new Domain.Model.Review
                    {
                        Id       = viewModel.ReviewId,
                        Comment  = viewModel.Comment,
                        Score    = viewModel.Score,
                        PersonId = RepoPers.GetPeopleByName(viewModel.UserName).First(p => p.Username.ToLower() == viewModel.UserName.ToLower()).Id,
                        SellerId = RepoSell.GetSellersByName(viewModel.SellerName).First(p => p.Name.ToLower() == viewModel.SellerName.ToLower()).Id
                    };
                    List <string> mySellers = new List <string> ();
                    foreach (var val in RepoSell.GetSellersByName().ToList())
                    {
                        mySellers.Add(val.Name);
                    }
                    ViewData["SellerName"] = new SelectList(mySellers);
                    List <string> myPeople = new List <string> ();
                    foreach (var val in RepoPers.GetPeopleByName().ToList())
                    {
                        myPeople.Add(val.Username);
                    }
                    ViewData["UserName"] = new SelectList(myPeople);

                    RepoRev.AddReview(review);
                    RepoRev.Save();

                    return(RedirectToAction(nameof(Index)));
                }
                return(View(viewModel));
            }
            catch
            {
                return(View(viewModel));
            }
        }
Exemplo n.º 27
0
        public ActionResult Reviews_Update([DataSourceRequest]DataSourceRequest request, ReviewViewModel model)
        {
            if (ModelState.IsValid)
            {
                this.reviews.Edit(
                    model.Id,
                    model.GameTitle,
                    model.CategoryId,
                    model.Content,
                    model.MinPlayers,
                    model.MaxPlayers,
                    model.MinAgeRequired,
                    model.MinPlayingTimeInMinutes,
                    model.UrlToOfficialSite,
                    model.ImageId);
            }

            return Json(new[] { model }.ToDataSourceResult(request, ModelState));
        }
Exemplo n.º 28
0
        public IActionResult Create([FromBody] ReviewCreateViewModel vm)
        {
            vm.PostedBy   = Convert.ToInt32(this.User.FindFirstValue(ClaimTypes.NameIdentifier));
            vm.DatePosted = DateTime.Now;
            Review          R      = Converter.ReviewCreateViewModelToReview(vm);
            int             id     = Repo.CreateReview(R);
            ReviewViewModel result = new ReviewViewModel()
            {
                ReviewId     = id,
                PostedById   = vm.PostedBy,
                Body         = vm.Body,
                Rating       = vm.Rating,
                BookReviewed = vm.BookReviewed,
                DatePosted   = vm.DatePosted,
                PostedBy     = User.Identity.Name
            };

            return(PartialView("_Detail", result));
        }
Exemplo n.º 29
0
        public ActionResult CreateFromIndex(ReviewViewModel model)
        {
            Review review = new Review
            {
                Accepted      = false,
                PublishedDate = DateTime.Now,
                Title         = model.Title,
                UserId        = model.UserId,
                GameId        = model.GameId,
                Content       = model.Content
            };

            foreach (var item in db.Users)
            {
                if (item.UserName == User.Identity.Name)
                {
                    review.UserId = item.Id;
                }
            }

            if (ModelState.IsValid)
            {
                db.Reviews.Add(review);
                db.SaveChanges();
                return(RedirectToAction("Index", "Review"));
            }


            var games          = db.Games.Where(c => c.Accepted == true);
            var gameViewModels = Mapper.Map <IEnumerable <Game>, IEnumerable <GameViewModel> >(games);
            var data           = gameViewModels.ToList().Select(t => new GroupedSelectListItem
            {
                GroupKey  = t.CategoryName.ToString(),
                GroupName = t.CategoryName,
                Text      = t.Name,
                Value     = t.Id.ToString()
            });

            model.Games = data;

            return(View(model));
        }
Exemplo n.º 30
0
        public ActionResult reviews()
        {
            //return Session["USERID"].ToString();
            if (Session["type"].ToString() == "2")
            {
                ReviewService service = new ReviewService();
                List <Review> revs    = new List <Review>();
                int           id      = Convert.ToInt32(Session["USERID"]);
                revs = service.getAllReviews(id);

                List <ReviewViewModel> res = new List <ReviewViewModel>();


                AuthService atsr = new AuthService();
                for (int i = 0; i < revs.Count; i++)
                {
                    ReviewViewModel tmp = new ReviewViewModel();
                    tmp.Time    = revs[i].Time;
                    tmp.Rating  = revs[i].Rating;
                    tmp.Comment = revs[i].Comment;

                    if (revs[i].FromUserId == id)
                    {
                        tmp.IsToMe = 0;
                        tmp.Who    = atsr.getUsername(revs[i].ToUserId);
                    }
                    else
                    {
                        tmp.IsToMe = 1;
                        tmp.Who    = atsr.getUsername(revs[i].FromUserId);
                    }

                    res.Add(tmp);
                }
                return(View("reviews", res));
            }

            else
            {
                return(RedirectToAction("index", "Login"));
            }
        }
Exemplo n.º 31
0
        public IActionResult AddNewReview(int userId, int bookId, [FromBody] ReviewViewModel newReview)
        {
            if (newReview == null)
            {
                return(BadRequest());
            }
            if (!ModelState.IsValid)
            {
                return(StatusCode(412));
            }

            var review = _reviewService.AddNewReview(bookId, userId, newReview);

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

            return(Ok(review));
        }
Exemplo n.º 32
0
        public PartialViewResult CreateReviewForGame([NotNull] Game game)
        {
            if (!(User?.Identity?.IsAuthenticated ?? false))
            {
                // Don't return a partial for unauthenticated users
                return null;
            }

            Guid memberId = idGetter.GetUserId(HttpContext.User.Identity);
            GameReview previousReview = game.AllReviews.FirstOrDefault(r => r.MemberId == memberId);

            ReviewViewModel viewModel = new ReviewViewModel
            {
                GameId = game.Id,
                GameSKUSelectList = new SelectList(game.GameSKUs, "Id", "NamePlatformDistinct"),
                Review = previousReview
            };

            return PartialView(viewModel);
        }
Exemplo n.º 33
0
        public async Task Succeed()
        {
            var reviewServiceMock = new Mock <IReviewService>();

            var sut = new ReviewsController(reviewServiceMock.Object);

            var reviewViewModel = new ReviewViewModel()
            {
                Id = 1,
                OriginalDescription = "This is first review",
                BusinessUnitId      = 1,
                Rating = 1
            };

            reviewServiceMock.Setup(x => x.CreateReviewAsync(reviewViewModel.OriginalDescription, reviewViewModel.BusinessUnitId, reviewViewModel.Rating)).ReturnsAsync(TestHelpersReviewController.TestReviewDTO01());

            var actionResult = await sut.Create(reviewViewModel);

            Assert.IsInstanceOfType(actionResult, typeof(OkObjectResult));
        }
Exemplo n.º 34
0
        public async Task ThrowsBadRequestWhenReviewWasNotCreatedNotFoundReviewId()
        {
            var reviewServiceMock = new Mock <IReviewService>();

            var sut = new ReviewsController(reviewServiceMock.Object);

            var reviewViewModel = new ReviewViewModel()
            {
                Id = 3,
                OriginalDescription = null,
                BusinessUnitId      = 1,
                Rating = 1
            };

            reviewServiceMock.Setup(x => x.CreateReviewAsync(reviewViewModel.OriginalDescription, reviewViewModel.BusinessUnitId, reviewViewModel.Rating)).ReturnsAsync(TestHelpersReviewController.TestReviewDTO01());

            var actionResult = await sut.Create(reviewViewModel);

            Assert.IsInstanceOfType(actionResult, typeof(BadRequestObjectResult));
        }
        public async void CreateReviewForGameProduct_ValidExisting_MarkAsChangedCalledOnce()
        {
            var existingReviews = new List<GameReview>
            {
                ratingOnlyReview
            };

            var games = new List<Game> {game};

            Mock<DbSet<Game>> gamesStub = TestHelpers.GetFakeAsyncDbSet(games.AsQueryable());

            Mock<DbSet<GameReview>> gameReviewsStub = TestHelpers.GetFakeAsyncDbSet(existingReviews.AsQueryable());
            gameReviewsStub.Setup(rdb => rdb.FindAsync(It.IsAny<Guid>(), It.IsAny<Guid>())).ReturnsAsync(fullReview);
        
            Mock<IVeilDataAccess> dbMock = TestHelpers.GetVeilDataAccessFake();
            dbMock.Setup(db => db.GameReviews).Returns(gameReviewsStub.Object);
            dbMock.Setup(db => db.MarkAsModified(It.IsAny<GameReview>())).Verifiable();
            dbMock.Setup(db => db.SaveChangesAsync()).ReturnsAsync(0).Verifiable();
            dbMock.Setup(db => db.Games).Returns(gamesStub.Object);

            Mock<ControllerContext> contextStub = new Mock<ControllerContext>();
            contextStub.SetupUser().InMemberRole();

            var idGetter = TestHelpers.GetSetupIUserIdGetterFake(memberId);

            ReviewsController controller = new ReviewsController(dbMock.Object, idGetter.Object)
            {
                ControllerContext = contextStub.Object,
            };

            ReviewViewModel model = new ReviewViewModel()
            {
                GameId = game.Id,
                GameSKUSelectList = null,
                Review = fullReview
            };

            await controller.CreateReviewForGameProduct(model);

            Assert.That(() => dbMock.Verify(db => db.MarkAsModified(fullReview), Times.Once), Throws.Nothing);
            Assert.That(() => dbMock.Verify(db => db.SaveChangesAsync(), Times.Once), Throws.Nothing);
        }
        public async void CreateReviewForGameProduct_POST_Invalid_SaveChangesNotCalled()
        {
            Mock<DbSet<GameReview>> gameReviewStub = TestHelpers.GetFakeAsyncDbSet(new List<GameReview>().AsQueryable());
            gameReviewStub.Setup(rdb => rdb.FindAsync(It.IsAny<Guid>(), It.IsAny<Guid>())).ReturnsAsync(null);

            Mock<IVeilDataAccess> dbMock = TestHelpers.GetVeilDataAccessFake();
            dbMock.Setup(db => db.GameReviews).Returns(gameReviewStub.Object);
            dbMock.Setup(db => db.SaveChangesAsync()).ReturnsAsync(0).Verifiable();


            Mock<ControllerContext> contextStub = new Mock<ControllerContext>();
            contextStub.SetupUser().InMemberRole();

            var idGetter = TestHelpers.GetSetupIUserIdGetterFake(memberId);

            ReviewsController controller = new ReviewsController(dbMock.Object, idGetter.Object)
            {
                ControllerContext = contextStub.Object,
            };
            controller.ModelState.AddModelError("GameId", "GameId is required");

            ReviewViewModel model = new ReviewViewModel()
            {
                GameId = game.Id,
                GameSKUSelectList = null,
                Review = fullReview
            };

            await controller.CreateReviewForGameProduct(model);

            Assert.That(() => dbMock.Verify(db => db.SaveChangesAsync(), Times.Never), Throws.Nothing);
        }
        public async void CreateReviewForGameProduct_POST_UserNotInMemberRole_RedirectsBackToGameDetail()
        {
            Mock<IVeilDataAccess> dbStub = TestHelpers.GetVeilDataAccessFake();

            Mock<ControllerContext> contextStub = new Mock<ControllerContext>();
            contextStub.SetupUser().InNoRoles();

            var idGetter = TestHelpers.GetSetupIUserIdGetterFake(memberId);

            ReviewsController controller = new ReviewsController(dbStub.Object, idGetter.Object)
            {
                ControllerContext = contextStub.Object,
            };

            ReviewViewModel model = new ReviewViewModel()
            {
                GameId = game.Id,
                GameSKUSelectList = null,
                Review = fullReview
            };

            var result = await controller.CreateReviewForGameProduct(model) as RedirectToRouteResult;

            Assert.That(result != null);
            Assert.That(result.RouteValues["Action"], Is.EqualTo(nameof(GamesController.Details)));
            Assert.That(result.RouteValues["Controller"], Is.EqualTo("Games"));
            Assert.That(result.RouteValues["id"], Is.EqualTo(model.GameId));
        }
Exemplo n.º 38
0
        public ActionResult Reviews_Destroy([DataSourceRequest]DataSourceRequest request, ReviewViewModel model)
        {
            this.reviews.Delete(model.Id);

            return Json(new[] { model }.ToDataSourceResult(request, ModelState));
        }