public async Task <IActionResult> PutBookRating([FromRoute] int id, [FromBody] BookRating bookRating)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != bookRating.Id)
            {
                return(BadRequest());
            }

            _context.Entry(bookRating).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BookRatingExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
示例#2
0
        public void UpdateRating(BookRating bookRating)
        {
            var result = _dbContext.BookRating.SingleOrDefault(b => b.Isbn == bookRating.Isbn);

            if (result != null)
            {
                decimal updateRating;
                if (result.Rating >= 1)
                {
                    if (bookRating.Rating >= result.Rating)
                    {
                        updateRating  = 0.5m;
                        result.Rating = result.Rating + updateRating;
                    }
                    else
                    {
                        updateRating  = 0.5m;
                        result.Rating = result.Rating - updateRating;
                    }
                    _dbContext.SaveChanges();
                }
            }
            else
            {
                _dbContext.BookRating.Add(bookRating);
                _dbContext.SaveChanges();
            }
        }
示例#3
0
        public Task AddReviewAsync(string key, string username, string review, BookRating bookRating)
        {
            return(Task.Run(() =>
            {
                var bookReviewItem = new BookReviewItem
                {
                    BookRating = bookRating,
                    Text = review,
                    Username = username
                };

                var reviews = _reviewRepository.Get(key);

                if (reviews != null)
                {
                    reviews.BookReviewItems.Add(bookReviewItem);
                    _reviewRepository.Update(reviews);
                }
                else
                {
                    reviews = new BookReviews()
                    {
                        Id = key,
                        BookReviewItems = new List <BookReviewItem>
                        {
                            bookReviewItem
                        }
                    };
                    _reviewRepository.Add(reviews);
                }
            }));
        }
示例#4
0
        private void UpdateRating(int bookId)
        {
            var newRating = (from r in _db.BookReviews
                             where r.BookId == bookId
                             select r.Rating).DefaultIfEmpty(0).Average();

            var rating = (from r in _db.BookRatings
                          where r.BookId == bookId
                          select r).SingleOrDefault();

            if (rating != null)
            {
                rating.Rating = newRating;
                _db.Update(rating);
            }
            else
            {
                var firstRating = new BookRating
                {
                    BookId = bookId,
                    Rating = newRating
                };
                _db.Add(firstRating);
            }

            _db.SaveChanges();
        }
示例#5
0
        public string AddRating(string bookId, double rating, string username)
        {
            var user = this.UserManager.FindByNameAsync(username).GetAwaiter().GetResult();
            var book = this.Context.Books.Find(bookId);

            bool hasAlreadyRated = AlreadyRated(book.Id, user.UserName);

            if (hasAlreadyRated)
            {
                throw new InvalidOperationException(GlobalConstants.AlreadyRated);
            }

            var userRating = new UserRating()
            {
                Rating = rating,
                UserId = user.Id
            };

            this.Context.UsersRatings.Add(userRating);

            var bookRating = new BookRating()
            {
                Book     = book,
                RatingId = userRating.Id
            };

            this.Context.BooksRatings.Add(bookRating);
            book.BookRatings.Add(bookRating);

            this.Context.Update(book);
            this.Context.SaveChanges();

            return(bookRating.RatingId);
        }
        public HttpResponseMessage Put(BookRating bookRating)
        {
            HttpResponseMessage response;

            try
            {
                ((RatingRepository)_ratingRepo).Update(bookRating);
                response = Request.CreateResponse(HttpStatusCode.OK, "Rating updated");
                return(response);
            }
            catch (ArgumentException)
            {
                try
                {
                    _ratingRepo.Add(bookRating);
                    response = Request.CreateResponse(HttpStatusCode.Created, "Created a new rating");
                    return(response);
                }
                catch (ArgumentException e)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, "Failed. " + e.Message);
                    return(response);
                }
            }
        }
 public void Add(BookRating entity)
 {
     using (var context = new LibraryContext())
     {
         context.BookRatings.Add(entity);
         context.SaveChanges();
     }
 }
 public JsonResult InsertRatedBook(BookRating bookrate)
 {
     if (ModelState.IsValid)
     {
         Rating.InsertRating(bookrate);
     }
     return(Json(new { Result = "Success", Message = "Updated Book Successfully" }, JsonRequestBehavior.AllowGet));
 }
示例#9
0
        public ApiResult <string> AddRating(RatingRequest ratingRequest)
        {
            var countVote = eShopDbContext.Users.Find(ratingRequest.UserId)?.BookRatings?.Where(x => x.BookId == ratingRequest.BookId)?.Count();

            if (countVote > 4)
            {
                return(new ApiResult <string>(success: false, messge: "Bạn đã đánh giá trước đó nhiều lần !", payload: "MAXIMUM"));
            }

            var book = eShopDbContext.Books.Find(ratingRequest.BookId);

            if (book == null)
            {
                return(new ApiResult <string>(success: false, messge: "Không tìm thấy cuốn sách mà bạn muốn đánh giá", payload: "NO_BOOK"));
            }

            /// kiem tra kkhac hang da mua sp hay chua
            var isBuy = false;

            eShopDbContext.Users.Find(ratingRequest.UserId).Orders.ForEach(order =>
            {
                order.OrderDetails.ForEach(orderDetail =>
                {
                    if (orderDetail.BookId == ratingRequest.BookId)
                    {
                        isBuy = true;
                        return;
                    }
                    if (isBuy)
                    {
                        return;
                    }
                });
            });

            if (!isBuy)
            {
                return(new ApiResult <string>(success: false, messge: "Chưa mua sao đánh giá được 😀", payload: "DONT_BUY"));
            }

            var rating = new BookRating()
            {
                BookId  = ratingRequest.BookId,
                Comment = ratingRequest.Comment,
                UserId  = ratingRequest.UserId,
                Rating  = ratingRequest.Rating,
            };

            //diem tru di do vote se gap doi neu vote 1 sao va bag neu vote 2* , khong tru neu vote 3 sao (Tam on)
            book.WeekScore  += (3 - ratingRequest.Rating) * 10;
            book.MonthScore += (3 - ratingRequest.Rating) * 10;
            book.YearScore  += (3 - ratingRequest.Rating) * 10;

            eShopDbContext.BookRatings.Add(rating);
            eShopDbContext.SaveChangesAsync();
            return(new ApiResult <string>(success: true, messge: "Đã gửi đánh giá của bạn ✔", payload: "SUCCESS"));
        }
示例#10
0
 public HttpResponseMessage Update(BookRating bookRating)
 {
     try
     {
         genericRating.UpdateRating(bookRating);
         return(Request.CreateResponse(HttpStatusCode.OK, "Successfully updated book rating"));
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, ex.Message.ToString()));
     }
 }
示例#11
0
 public void UpdateRating(BookRating bookRating)
 {
     try
     {
         bookRatingRepo.Update(bookRating);
         bookRatingRepo.Save();
     }
     catch (Exception ex)
     {
         Error.InsertError(ex);
     }
 }
        public async Task <IActionResult> PostBookRating([FromBody] BookRating bookRating)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.BookRatings.Add(bookRating);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetBookRating", new { id = bookRating.Id }, bookRating));
        }
示例#13
0
        public async Task Handle(BookAddedIntegrationEvent @event)
        {
            var rating = new BookRating
            {
                BookId    = @event.BookId.ToString(),
                BookTitle = @event.Title,
                Stars     = GetRandomNumber(1, 5)
            };

            _context.BookRatings.Add(rating);

            await _context.SaveChangesAsync();
        }
 public static BookRatingModel Create(BookRating entity)
 {
     if (entity != null)
     {
         var model = new BookRatingModel
         {
             Id     = entity.Id,
             Name   = entity.Name,
             Rating = entity.Rating,
             ISBN   = entity.Isbn
         };
         return(model);
     }
     return(null);
 }
示例#15
0
        /// <summary>
        /// 根据Id获得BookRating对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public BookRating GetBookRatingById(int id)
        {
            BookRating    bookRating = null;
            string        sql        = "select Id,BookId,UserId,Rating,Comment,CreatedTime from BookRatings where Id = @Id";
            SqlDataReader reader     = DBHelper.ExecuteReader(sql, CommandType.Text, new SqlParameter("@Id", id));

            if (reader.HasRows)
            {
                if (reader.Read())
                {
                    bookRating = LoadBookRating(reader);
                }
            }
            reader.Close();
            return(bookRating);
        }
        public void Update(BookRating bookRating)
        {
            using (var context = new LibraryContext())
            {
                BookRating result = context.BookRatings.Where(br => br.BookId == bookRating.BookId && br.UserId == bookRating.UserId).SingleOrDefault();

                if (result != null)
                {
                    result.Rating = bookRating.Rating;
                    context.SaveChanges();
                }
                else
                {
                    throw new ArgumentException("Book not found");
                }
            }
        }
示例#17
0
 public void InsertRating(BookRating bookRating)
 {
     try
     {
         BookRating bookrating = new BookRating
         {
             RatingNumber = bookRating.RatingNumber,
             MemberId     = GlobalIXHelper.GetMemberId(),
             BookId       = bookRating.BookId
         };
         bookRatingRepo.Insert(bookrating);
         bookRatingRepo.Save();
     }
     catch (Exception ex)
     {
         Error.InsertError(ex);
     }
 }
        public HttpResponseMessage Post(BookRating newBookRating)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, "Sucessfully added to DB");

            try
            {
                _ratingRepo.Add(newBookRating);
            }
            catch (ArgumentException a)
            {
                response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid parameters. " + a.Message);
            }
            catch (DbUpdateException a)
            {
                response = Request.CreateResponse(HttpStatusCode.BadRequest, a.Message);
            }
            return(response);
        }
        public async Task CreateReviewAsync(string userId, decimal grade, string description, string bookId)
        {
            var bookTitle = await _bookService.GetBookTitleAsync(bookId).ConfigureAwait(false);

            var allBooksWithSameTitle = await _bookService.GetAllSameBooks(bookId).ConfigureAwait(false);

            //BookRating item.BookRating = _context.BookRating.Where(br => br.BookId == bookId);
            foreach (var item in allBooksWithSameTitle)
            {
                if (item.BookRating != null)
                {
                    item.BookRating.Rating = grade;
                    _context.Update(item);
                    await _context.SaveChangesAsync().ConfigureAwait(false);
                }
                else
                {
                    var bookRating = new BookRating
                    {
                        BookId = bookId,
                        Rating = grade
                    };
                    _context.BookRating.Add(bookRating);
                    await _context.SaveChangesAsync().ConfigureAwait(false);

                    item.BookRatingId = bookRating.Id;
                    _context.Update(item);
                    await _context.SaveChangesAsync().ConfigureAwait(false);
                }

                var review = new Review
                {
                    BookRatingId = item.BookRating.Id,
                    Description  = description,
                    Grade        = grade,
                    UserId       = userId,
                    BookTitle    = bookTitle
                };
                _context.Review.Add(review);
                await _context.SaveChangesAsync().ConfigureAwait(false);
            }
        }
示例#20
0
        public async Task AddRating_Should_Success()
        {
            var book = new Book()
            {
                Id      = "1",
                Author  = null,
                Summary = "summary",
                Title   = "title"
            };

            var user = new BookCreatorUser()
            {
                Id       = "123",
                Name     = "Papuncho Kunchev",
                UserName = "******"
            };

            await userManager.CreateAsync(user);

            this.Context.Books.Add(book);
            this.Context.SaveChanges();

            var bookId   = book.Id;
            var rating   = 9.5;
            var username = user.UserName;

            var ratingId = bookService.AddRating(bookId, rating, username);

            var bookRating = new BookRating()
            {
                RatingId = ratingId,
                BookId   = bookId
            };

            var result = this.Context.BooksRatings.FirstOrDefault();

            result.Should().NotBeNull()
            .And.Subject.Should()
            .BeOfType <BookRating>()
            .And.Should()
            .BeEquivalentTo(bookRating, x => x.ExcludingMissingMembers());
        }
示例#21
0
        public void AddRating_Should_Throw_Exception_AlreadyRated()
        {
            var book = new Book()
            {
                Id      = "1",
                Author  = null,
                Summary = "summary",
                Title   = "title"
            };

            var user = new BookCreatorUser()
            {
                Id       = "123",
                Name     = "Papuncho Kunchev",
                UserName = "******"
            };

            var rating = new UserRating()
            {
                Id     = "1",
                UserId = user.Id,
                Rating = 9.5
            };

            var bookRating = new BookRating()
            {
                RatingId = rating.Id,
                BookId   = book.Id
            };

            userManager.CreateAsync(user).GetAwaiter().GetResult();

            this.Context.Books.Add(book);
            this.Context.BooksRatings.Add(bookRating);
            this.Context.UsersRatings.Add(rating);
            this.Context.SaveChanges();

            Action act = () => bookService.AddRating(book.Id, 2.00, user.UserName);

            act.Should().Throw <InvalidOperationException>().WithMessage(GlobalConstants.AlreadyRated);
        }
示例#22
0
        public static void Main(string[] args)
        {
            var services = new ServiceCollection();
            var builder  = new ConfigurationBuilder()
                           .SetBasePath(Path.Combine(AppContext.BaseDirectory))
                           .AddJsonFile("appsettings.json", optional: true);

            configuration = builder.Build();

            var dbConnectionString = System.Environment.GetEnvironmentVariable("DB_CONNECTION") ?? configuration["Data:DefaultConnection:ConnectionString"];

            services.AddDbContext <RatingContext>(options => options.UseSqlServer(dbConnectionString));
            services.AddTransient <IRatingProvider, RatingProvider>();
            serviceProvider = services.BuildServiceProvider();
            var ratingProvider = serviceProvider.GetRequiredService <IRatingProvider>();

            var sastoken = System.Environment.GetEnvironmentVariable("SERVICEBUS_TOKEN") ?? configuration["ServiceBusEndpoint:Sastoken"];
            var url      = System.Environment.GetEnvironmentVariable("SERVICEBUS_URL") ?? configuration["ServiceBusEndpoint:Url"];

            var message = string.Empty;

            do
            {
                message = GetMessages(sastoken, url).Result;
                if (!string.IsNullOrEmpty(message))
                {
                    var        sbMessage = JsonConvert.DeserializeObject <Utility.Message>(message);
                    BookRating bRating   = new BookRating
                    {
                        Name   = sbMessage.Name,
                        Isbn   = sbMessage.ISBN,
                        Rating = sbMessage.Rating
                    };

                    ratingProvider.UpdateRating(bRating);
                }
            } while (!string.IsNullOrEmpty(message));
        }
示例#23
0
        /// <summary>
        /// 从SqlDataReader中读取数据,返回BookRating对象
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private BookRating LoadBookRating(SqlDataReader reader)
        {
            Book       book       = new BookService().GetBookById(reader.GetInt32(1));
            UserInfo   user       = new UserService().GetUserInfoById(reader.GetInt32(2));
            BookRating bookRating = new BookRating(reader.GetInt32(0), book, user, reader.GetDateTime(5));

            if (!(reader["Rating"] is DBNull))
            {
                bookRating.Rating = reader.GetInt32(3);
            }
            else
            {
                bookRating.Rating = 0;
            }
            if (!(reader["Comment"] is DBNull))
            {
                bookRating.Comment = reader.GetString(4);
            }
            else
            {
                bookRating.Comment = null;
            }
            return(bookRating);
        }
        public async Task <bool> SetRating(BookRatingQueryParams ratingQueryParams)
        {
            var book = await _bookRepository.FindByIdAsync(ratingQueryParams.BookId);

            if (book == null)
            {
                return(false);
            }

            var bookRating = new BookRating(ratingQueryParams.BookId, ratingQueryParams.UserId, ratingQueryParams.Rating);

            _bookRatingRepository.Add(bookRating);
            await _bookRatingRepository.SaveChangesAsync();

            var avgRating = _bookRatingRepository.GetAll()
                            .Where(b => b.BookId == ratingQueryParams.BookId)
                            .Average(b => b.Rating);

            book.Rating = avgRating;
            _bookRepository.Update(book);
            await _bookRepository.SaveChangesAsync();

            return(true);
        }
 public void Create(BookRating book)
 {
 }
示例#26
0
 /// <summary>
 /// Creates a single BookRating as a Hash
 /// </summary>
 /// <param name="rating"></param>
 /// <returns></returns>
 public async Task Create(BookRating rating)
 {
     await _db.HashSetAsync(BookRatingKey(rating.Id), rating.AsHashEntries().ToArray());
 }
        public async Task <IActionResult> Create(BookRating rating)
        {
            await _bookRatingService.Create(rating);

            return(StatusCode(201));
        }