示例#1
0
 public IActionResult AddRating(int id, [FromBody] UserRating value)
 {
     value.BeerId = id;
     this._databaseService.UserRatings.Add(value);
     this._databaseService.SaveChanges();
     return(Ok("Your rating has been added!"));
 }
示例#2
0
 private void AssertUserRatingsEqual(UserRating expectedUserRating, UserRating actualUserRating)
 {
     Assert.AreEqual(expectedUserRating.RaterUserID, actualUserRating.RaterUserID);
     Assert.AreEqual(expectedUserRating.UserBeingRatedID, actualUserRating.UserBeingRatedID);
     Assert.AreEqual(expectedUserRating.Comment, actualUserRating.Comment);
     Assert.AreEqual(expectedUserRating.RatingID, actualUserRating.RatingID);
 }
 private void AssertRatingsEqual(UserRating expected, UserRating actual)
 {
     Assert.AreEqual(expected.RaterUserID, actual.RaterUserID);
     Assert.AreEqual(expected.UserBeingRatedID, actual.UserBeingRatedID);
     Assert.AreEqual(expected.Comment, actual.Comment);
     Assert.AreEqual(expected.RatingID, actual.RatingID);
 }
示例#4
0
        public async Task <HttpResponseMessage> RateBeer(int id, [FromBody] UserRating rating)
        {
            try
            {
                if (rating == null || rating.Rating < 0 || rating.Rating > 5)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Rating is Invalid"));
                }

                //validate Id
                var result = await WebRequestService.GetRequest($"{api}/beers/{id}");

                if (result.Item1 == HttpStatusCode.OK && !string.IsNullOrEmpty(result.Item2))
                {
                    JArray list = JArray.Parse(result.Item2);
                    if (list.Count < 1)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadGateway, "Beer doesn't exists"));
                    }

                    PunkService.SaveRating(id, rating);
                    return(Request.CreateResponse(HttpStatusCode.OK, "Ratings saved"));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Beer Id"));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
        public void TestGetUserRatings()
        {
            Console.WriteLine("TestGetUserRatings");
            //Arrange
            Database database = new Database();
            string   json     = "[{\"beerId\":5,\"userName\":\"[email protected]\",\"rating\":5,\"comments\":\"Excellent\"}]";

            if (File.Exists(database.getPath()))
            {
                File.Delete(database.getPath());
            }

            using (StreamWriter sw = System.IO.File.CreateText(database.getPath())){
                sw.WriteLine(json);
                sw.Close();
            }

            //Act
            List <UserRating> userRatings = database.GetUserRatings();
            UserRating        rating      = userRatings.First <UserRating>();

            //Assert
            Assert.Equal(5, rating.BeerId);
            Assert.Equal("*****@*****.**", rating.UserName);
            Assert.Equal("Excellent", rating.Comments);
            Assert.Equal(5, rating.Rating);
        }
        public JsonResult SaveRating(float diem, int IdSanPham)
        {
            if (Request.Cookies["A" + IdSanPham.ToString()] == null)
            {
                Response.Cookies["A" + IdSanPham.ToString()].Value   = IdSanPham.ToString();
                Response.Cookies["A" + IdSanPham.ToString()].Expires = DateTime.Now.AddDays(1);

                diem = diem <= 4 ? 4 : diem;
                UserRating _danhgia = new UserRating()
                {
                    IdSanPham  = IdSanPham,
                    Rating     = diem,
                    UserAcount = User.Identity.Name == null ? "" : User.Identity.Name
                };
                _userRatingRepository.Add(_danhgia);
                _unitOfWork.Commit();
            }
            else if (Request.Cookies["A" + IdSanPham.ToString()].Value != IdSanPham.ToString())
            {
                Response.Cookies["A" + IdSanPham.ToString()].Value   = IdSanPham.ToString();
                Response.Cookies["A" + IdSanPham.ToString()].Expires = DateTime.Now.AddDays(1);

                diem = diem <= 4 ? 4 : diem;
                UserRating _danhgia = new UserRating()
                {
                    IdSanPham  = IdSanPham,
                    Rating     = diem,
                    UserAcount = User.Identity.Name == null ? "" : User.Identity.Name
                };
                _userRatingRepository.Add(_danhgia);
                _unitOfWork.Commit();
            }

            return(Json(new { message = "ok" }, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// Either updates or adds a rating to the selected User
        /// </summary>
        /// <param name="request">Object that holds jwt and rating</param>
        /// <param name="rateeID">User that is being rated</param>
        /// <returns>an integer</returns>
        public int RateUser(RateRequest request, string rateeID)
        {
            int        raterID = _jwtServce.GetUserIDFromToken(request.jwtToken);
            UserRating ur      = new UserRating
            {
                RatedId1 = Convert.ToInt32(rateeID),
                RaterId1 = Convert.ToInt32(raterID),
                Rating   = Convert.ToInt32(request.rating)
            };

            try
            {
                var hasClaims = _jwtServce.CheckUserClaims(request.jwtToken, canRateUsers);
                if (hasClaims.CompareTo("Authorized") != 0)
                {
                    return(-2);
                }
                var userRating = _ratingService.GetRating(Convert.ToInt32(raterID), Convert.ToInt32(rateeID));
                if (userRating == false)
                {
                    _ratingService.CreateRating(ur, "");
                    return(1);
                }
                _ratingService.UpdateRating(ur, "");
                return(2);
            }
            catch (Exception e)
            {
                //log
                return(-1);
            }
        }
示例#8
0
        /// <summary>
        /// Updates current user rating with a new rating
        /// </summary>
        /// <param name="rating">new Rating information</param>
        /// <param name="ip">user ip</param>
        /// <returns></returns>
        public bool UpdateRating(UserRating rating, string ip)
        {
            var userRating = new UserRating();

            try
            {
                using (var context = new GreetNGroupContext())
                {
                    var query = context.UserRatings.Where(s => s.RaterId1 == rating.RaterId1 && s.RatedId1 == rating.RatedId1).FirstOrDefault <UserRating>();
                    if (query.Rating == rating.Rating)
                    {
                        query.Rating = 0;
                    }
                    else
                    {
                        query.Rating = rating.Rating;
                    }
                    context.SaveChanges();
                }
                return(true);
            }
            catch (Exception e)
            {
                _gngLoggerService.LogGNGInternalErrors(e.ToString());
                return(false);
            }
        }
示例#9
0
        public async Task <IActionResult> AddRating(int gameId, UserRating userRating)
        {
            int userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            userRating.GameId = gameId;
            userRating.UserId = userId;

            var existingRating = await _context.UserRatings
                                 .Where(ur => ur.UserId == userRating.UserId && ur.GameId == userRating.GameId)
                                 .SingleOrDefaultAsync();

            if (existingRating != null)
            {
                existingRating.RatingValue = userRating.RatingValue;

                await _context.SaveChangesAsync();
            }
            else
            {
                _context.UserRatings.Add(userRating);

                var game = await _context.Games.FindAsync(gameId);

                game.UserRatings.Add(userRating);

                var user = await _context.Users.FindAsync(userRating.UserId);

                user.UserRatings.Add(userRating);

                await _context.SaveChangesAsync();
            }

            return(Ok());
        }
示例#10
0
        public void SaveUserRating(UserRating newRating)
        {
            var collection = _db.GetCollection <UserRating>("Users");
            var exist      = GetBookRating(newRating.BookID, newRating.UserID);

            try
            {
                if (exist == 0)
                {
                    collection.InsertOne(newRating);
                }
                else
                {
                    var builder       = Builders <UserRating> .Filter;
                    var filter        = builder.Eq("BookID", newRating.BookID) & builder.Eq("UserID", newRating.UserID) & builder.Exists("Rating");
                    var updateBuilder = Builders <UserRating> .Update;
                    var update        = updateBuilder.Set("Rating", newRating.Rating);
                    collection.UpdateOne(filter, update);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
示例#11
0
        public ActionResult <MovieRatingModel> AddOrUpdateRating(int movieId, [FromBody] UserRating rating)
        {
            try
            {
                var movieRating = Repository.GetMovieRatings(movieId).Where(r => r.UserId == rating.UserId).FirstOrDefault();

                if (movieRating == null)
                {
                    try
                    {
                        MovieRating m = Repository.AddRating(new MovieRating {
                            MovieId = movieId, UserId = rating.UserId, Rating = rating.Rating
                        });
                        return(CreatedAtAction("GetMovieRating", new { movieId = movieId, userId = movieRating.UserId }, ModelFactory.Create(m)));
                    }
                    catch
                    {
                        return(BadRequest("No such movie"));
                    }
                }
                else
                {
                    movieRating.Rating = rating.Rating;
                    var result = ModelFactory.Create(Repository.UpdateRating(movieRating));
                    Repository.SaveAll();
                    return(Ok(result));
                }
            }
            catch (Exception ex)
            {
                Logger.LogError($"AddOrUpdateRating: {ex}");

                return(StatusCode(500, "Internal server error"));
            }
        }
        public int CreateUserRaiting(UserRating rating)
        {
            var userRatingId = 0;

            using (SqlConnection conn = new SqlConnection(this._configuration.GetConnectionString(SQLNames.ConnectionString)))
            {
                conn.Open();

                var command = new SqlCommand(SQLNames.Proc_UserRating_Create, conn)
                {
                    CommandType = System.Data.CommandType.StoredProcedure
                };

                command.Parameters.Add(new SqlParameter("@" + SQLNames.Proc_UserRating_Param_Comment, rating.Comment));
                command.Parameters.Add(new SqlParameter("@" + SQLNames.Proc_UserRating_Param_RatingValue, rating.RatingValue));

                command.ExecuteNonQuery();

                command = new SqlCommand(string.Format("SELECT TOP 1 {0} FROM {1}",
                                                       SQLNames.Proc_UserRating_Param_UserRatingId,
                                                       SQLNames.UserRating_Table), conn)
                {
                    CommandType = System.Data.CommandType.Text
                };

                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    userRatingId = reader.GetInt32(0);
                }
            }

            return(userRatingId);
        }
示例#13
0
        public IActionResult Post([FromBody] UserRating userRating)
        {
            dynamic ret;

            if (userRating == null)
            {
                return(BadRequest());
            }

            if (userRating.UserID == 0 || userRating.MovieID == 0)
            {
                return(BadRequest());
            }

            if (userRating.Rating >= 1 && userRating.Rating <= 5)
            {
                ret = userRatingBL.PostRating(userRating.UserID, userRating.MovieID, userRating.Rating);
            }
            else
            {
                return(BadRequest());
            }

            if (ret == false)
            {
                return(NotFound());
            }

            return(Ok(ret));
        }
示例#14
0
        public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            string requestBody = new StreamReader(req.Body).ReadToEnd();

            UserRating userRating = JsonConvert.DeserializeObject <UserRating>(requestBody);

            if (!(userRating.Rating >= 0 && userRating.Rating <= 5))
            {
                return((ActionResult) new OkObjectResult($"Rating cannot be less than 0 or larger than 5"));
            }

            userRating.Timestamp = DateTime.UtcNow;
            userRating.Id        = Guid.NewGuid();

            var productResult = Get($"https://serverlessohproduct.trafficmanager.net/api/GetProduct?productid={userRating.ProductId}");

            log.Info("productResult fetched");

            var userResult = Get($"https://serverlessohuser.trafficmanager.net/api/GetUser?userid={userRating.UserId}");

            log.Info("userResult fetched");

            SaveToDb(userRating);
            log.Info("Saved to DB");

            return(new OkObjectResult(userRating));
        }
示例#15
0
    public async Task <ActionResult <Rating> > RatePhotoAsync(int id, UserRating userRating)
    {
        if (userRating == null)
        {
            throw new ArgumentNullException(nameof(userRating));
        }

        var username = User.GetUsername();

        // TODO: handle invalid photo id?
        // TODO: remove photoId from userPhotoRating?
        if (userRating.Rating < 1)
        {
            await _svc.RemoveRatingAsync(id, username, User.GetAllRoles());
        }
        else if (userRating.Rating <= 5)
        {
            await _svc.SaveRatingAsync(id, username, userRating.Rating, User.GetAllRoles());
        }
        else
        {
            return(BadRequest());
        }

        var rating = await InternalGetRatingAsync(id);

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

        return(rating);
    }
        public void Delete(UserRating entity)
        {
            var userRating = _fakeUserRatings.FirstOrDefault(p => p.RaterUserID == entity.RaterUserID &&
                                                             p.UserBeingRatedID == entity.UserBeingRatedID);

            _fakeUserRatings.Remove(userRating);
        }
示例#17
0
        public void GetUserRating()
        {
            var userDataId = 0L;

            // creating   UserDataId   by calling PersistTaxObject
            BusinessObject.Tax1040 tax1040 = new BusinessObject.Tax1040();
            tax1040.UserDataId = 0;
            userDataId         = Utilities.PersistTaxObject(userId, userDataId, tax1040);

            UserDTO userDTO = new UserDTO();

            userDTO.UserDataId = userDataId;
            userDTO.UserId     = userId;

            UserRating userrating = new UserRating();

            userrating.Rating  = 4;
            userrating.Comment = "good";

            mTaxReturnRepository.PersistUserRating(userDTO, userrating);


            var result = mTaxReturnRepository.GetUserRating(userDTO);

            Assert.AreEqual(userrating.Rating, result.Rating);
            Assert.AreEqual(userrating.Comment, result.Comment);
        }
        public ActionResult Get(int id)
        {
            IMovieService   movieService   = InstanceFactory.GetInstance <IMovieService>();
            ICommentService commebtService = InstanceFactory.GetInstance <ICommentService>();
            IRatingService  ratingtService = InstanceFactory.GetInstance <IRatingService>();

            Movie movie = movieService.Get(id);

            if (movie != null)
            {
                List <Rating> ratings = ratingtService.GetAll(x => x.MovieID == id);
                decimal       rating  = ratings.Count > 0 ? ratings.Sum(x => x.rating) / ratings.Count : 0;
                int           count   = ratings.Count;
                UserRating    ur      = new UserRating
                {
                    RatingAverage = rating,
                    RatingCount   = count
                };

                List <Comment> comments = commebtService.GetAll(x => x.MovieID == id);

                MovieForUser movieForUser = new MovieForUser
                {
                    TmdbData   = movie,
                    UserRating = ur,
                    Comments   = comments
                };

                return(Ok(movieForUser));
            }
            else
            {
                return(Ok(new MovieForUser()));
            }
        }
示例#19
0
        public void GetUserRatingTest()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "Get_UserRating_from_database")
                          .Options;

            var user = new UserProfile {
                Id = "userId"
            };
            var rating = new Rating {
                Id = "agencyId"
            };
            var agency = new AgencyProfile {
                Id = "agencyId", RatingId = rating.Id
            };
            var expectedRating = new UserRating {
                RatingId = rating.Id, UserProfileId = user.Id
            };
            UserRating actualRating;

            using (var db = new ApplicationDbContext(options))
            {
                db.UsersRatings.Add(expectedRating);
                db.AgenciesProfiles.Add(agency);
                db.Ratings.Add(rating);
                db.UsersProfiles.Add(user);
                db.SaveChanges();

                IProfileService service = new ProfileService(db);
                actualRating = service.GetUserRating(agency.Id);
            }

            Assert.Equal(expectedRating.RatingId, actualRating.RatingId);
        }
示例#20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="rating"></param>
        /// <param name="ratingBy"></param>
        public void InsertUserRating(string userName, decimal rating, string ratingBy)
        {
            userRating = (from s in unitOfWork.UserRatingRepository.Get()
                          where s.UserName == userName && s.RatingBy == ratingBy
                          select s).SingleOrDefault();

            if (userRating == null)
            {
                userRating = new UserRating
                {
                    UserName = userName,
                    Rating   = rating,
                    RatingBy = ratingBy
                };

                unitOfWork.UserRatingRepository.Insert(userRating);
            }
            else
            {
                userRating.Rating = rating;
                unitOfWork.UserRatingRepository.Update(userRating);
            }

            unitOfWork.Save();
        }
示例#21
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 async Task <IActionResult> AddRating(int id, [FromBody] UserRating userRating)
        {
            var validationErrors = new List <ParameterValidationError>();

            if (!await _beerRepo.IsValidId(id))
            {
                validationErrors.Add(new ParameterValidationError("id", "The Beer with id " + id + " doesn't exist"));
            }

            if (userRating.Rating > 5 || userRating.Rating < 1)
            {
                validationErrors.Add(new ParameterValidationError("rating", "Rating should be between 1 and 5"));
            }

            if (validationErrors.Any())
            {
                string errorStr = null;
                foreach (var item in validationErrors)
                {
                    errorStr = string.Concat(errorStr ?? string.Empty, " ", item.Reason);
                }
                var errorResponse = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content      = new StringContent(errorStr),
                    ReasonPhrase = "Errors in the request!"
                };
                return(BadRequest(errorResponse));
            }

            //add to the file
            return(Ok(_beerRepo.SaveRatings(id, userRating)));
        }
示例#23
0
    public void Bind()
    {
        if (RatingId.HasValue && User.LoggedInUser != null)
        {
            var userRating = UserRating;
            if (userRating == null)
            {
                userRating = new UserRating {
                    UserId   = User.LoggedInUser.UserId,
                    RatingId = Rating.RatingId,
                    Value    = 0
                };
                db.UserRatings.InsertOnSubmit(userRating);
                db.SubmitChanges();
            }

            rating.CurrentRating = userRating.Value;

            if (userRating.Value == 0)
            {
                descMessage.InnerText = "Rate it!";
            }
            else
            {
                descMessage.InnerText = String.Format("Current Vote {0}", userRating.Value);
            }
            Visible = true;
        }
        else
        {
            Visible = false;
        }
    }
            public async Task UpdateView_ReturnsAViewResult_WithData()
            {
                // Arrange
                var rate = new UserRating()
                {
                    Id            = 1,
                    SemestrPoints = 43,
                    SumPoints     = 78,
                    StudentId     = 1,
                    SubjectId     = 1,
                    Subject       = new Subject {
                        Name = "Math"
                    }
                };

                var mockLogic = new Mock <IUserRatingsLogic>();
                int userRatId = 1;

                mockLogic.Setup(repo => repo.GetUserRating(userRatId)).Returns(Task.FromResult(rate));
                var controller = new UserRatingsController(mockLogic.Object);

                //  Act
                IActionResult actionResult = await controller.Edit(userRatId, rate);

                // Assert
                var viewResult = Assert.IsType <RedirectToActionResult>(actionResult);

                mockLogic.Verify(repo => repo.UpdateUserRating(rate), Times.Once);
            }
        public async Task <IActionResult> Edit(int id, [Bind("Id,SemestrPoints,SumPoints,StudentId,SubjectId")] UserRating userRating)
        {
            if (id != userRating.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    await logic.UpdateUserRating(userRating);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!logic.UserRatingExists(userRating.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["StudentId"] = logic.GetStudentsSelectList(userRating.StudentId);
            ViewData["SubjectId"] = logic.GetSubjectsSelectList(userRating.SubjectId);

            userRating = await logic.GetUserRating(id);

            return(View(userRating));
        }
示例#26
0
        public UserRating GetUserRating(int id)
        {
            var comments = db.comment.Where(c => c.user_id == id).ToList();

            var count = comments.Count();

            if (count == 0)
            {
                return(null);
            }
            var    sum     = comments.Select(c => c.rating).Sum();
            double average = sum / count;

            average = System.Math.Round(average, 2);

            var userRating = new UserRating
            {
                userId         = id,
                countComment   = count,
                totalRatePoint = sum,
                average        = average
            };

            return(userRating);
        }
示例#27
0
        public async Task <UserRating> AddRating(long bookId, UserRating userRating)
        {
            var existingRating = await _context.UserRatings.Where(
                ur => ur.UserId == userRating.UserId && ur.BookId == userRating.BookId
                ).SingleOrDefaultAsync();

            if (existingRating != null)
            {
                existingRating.RatingValue = userRating.RatingValue;
                await _context.SaveChangesAsync();
            }
            else
            {
                _context.UserRatings.Add(userRating);

                var book = await _context.Book.FindAsync(bookId);

                book.UserRatings.Add(userRating);

                var user = await _context.User.FindAsync(userRating.UserId);

                user.UserRatings.Add(userRating);

                await _context.SaveChangesAsync();
            }

            return(userRating);
        }
示例#28
0
        public async Task <double> RateUser(ApplicationUser currentUser, string username, int rate)
        {
            var user = await this.db.Users.FirstOrDefaultAsync(x => x.UserName == username);

            var targetRating = await this.db.UserRatings
                               .FirstOrDefaultAsync(x => x.Username == username && x.RaterUsername == currentUser.UserName);

            if (targetRating != null)
            {
                targetRating.Stars = rate;
                this.db.Update(targetRating);
            }
            else
            {
                targetRating = new UserRating
                {
                    RaterUsername = currentUser.UserName,
                    Username      = username,
                    Stars         = rate,
                };
                this.db.UserRatings.Add(targetRating);
            }

            await this.db.SaveChangesAsync();

            return(this.CalculateRatingScore(username));
        }
示例#29
0
 private void RemoveLogWindow(object commandParameter)
 {
     if (commandParameter != null)
     {
         MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Are you sure you want to delete: " + commandParameter.ToString() + "?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
         if (messageBoxResult == MessageBoxResult.Yes)
         {
             if (this.tourItemFactory.EditLogs(currentItem.Name, commandParameter.ToString(), "Test", 1, 1, "Test", DateTime.Today, true) == null)
             {
                 MessageBox.Show("There has been an error deleting your log, please try again!");
             }
         }
         Tours.Clear();
         currentItem = null;
         currentLog  = null;
         RaisePropertyChangedEvent(nameof(CurrentMap));
         RaisePropertyChangedEvent(nameof(CurrentPic));
         RaisePropertyChangedEvent(nameof(CurrentItem));
         RaisePropertyChangedEvent(nameof(CurrentLog));
         FillListBox();
     }
     else
     {
         MessageBox.Show("Please click on a Tour and then click on this Button again to delete a tour!");
     }
 }
示例#30
0
 internal static Review MapToReview(this ReviewDto reviewDto) => new Review
 {
     Id         = reviewDto.Id,
     BookId     = reviewDto.BookId,
     Rating     = UserRating.From(reviewDto.Rating),
     Name       = reviewDto.Name,
     ReviewBody = reviewDto.ReviewBody
 };
        public int Add(int ratingScore, string hitmanId, string clientId)
        {
            var rating = new UserRating();
            rating.Rating = ratingScore;
            rating.HitmanId = hitmanId;
            rating.ClientId = clientId;

            this.userRating.Add(rating);

            return this.userRating.SaveChanges();
        }
        public UserRating AddUserRating(UserRating rating)
        {
            try
            {
                //Testing GitHub
                if (validateUserToken(rating.UserName, rating.UserAccessToken)) {
                    rating.UserId = _ctx.Users.Single(x => x.UserName == rating.UserName).Id;
                    if (_ctx.UserRatings.Where(x => (x.UserId == rating.UserId && x.MovieId == rating.MovieId)).Count() > 0)
                    {
                        var itemToUpdate = _ctx.UserRatings.Single(x => (x.UserId == rating.UserId && x.MovieId == rating.MovieId));

                        itemToUpdate.Rating = rating.Rating;
                        if (rating.VideoReviewThumb != null && rating.VideoReviewUrl != null)
                        {
                            itemToUpdate.VideoReviewUrl = rating.VideoReviewUrl;
                            itemToUpdate.VideoReviewThumb = rating.VideoReviewThumb;
                        }
                    }
                    else
                    _ctx.UserRatings.Add(rating);
                    if (_ctx.SaveChanges() > 0) {
                        UpdateAverageRating(rating.MovieId);
                        return rating;
                    }
                    else
                    {
                        var res = new HttpResponseMessage(HttpStatusCode.NotFound)
                        {
                            Content = new StringContent(string.Format("There was an error adding the rating.")),
                            ReasonPhrase = "There was an error adding the rating."
                        };
                        throw new HttpResponseException(res);
                    }
                }
                else {
                    var res = new HttpResponseMessage(HttpStatusCode.NotFound)
                        {
                            Content = new StringContent(string.Format("User not validated.")),
                            ReasonPhrase = "User not validated."
                    };
                        throw new HttpResponseException(res);
                }

            }
            catch (DbUpdateException) {
                var res = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content = new StringContent(string.Format("There was an error adding the rating.")),
                    ReasonPhrase = "There was an error adding the rating."
                };
                throw new HttpResponseException(res);
            }
        }
示例#33
0
        // POST api/rating
        public string Post(Rating rating)
        {
            UserRating newRating = new UserRating();
            newRating.Comment = rating.Comment;
            newRating.PlaceID = rating.PlaceID;
            newRating.Rating = rating.Ratingg;
            newRating.UserName = rating.UserName;

            WorldDestinationsRepository.WorldDestinations.UserRatings.Add(newRating);
            try
            {
                WorldDestinationsRepository.WorldDestinations.SaveChanges();
                return "YES";
            }
            catch (Exception e)
            {
                return "NO";
            }
        }
示例#34
0
文件: Managers.cs 项目: jonnycoder/jv
        public bool RegisterRating(
                string raterUserid,
                string affiliateId,
                int rating)
        {
            try
            {
                UserRating lookup = Context.UserRatings.Where(r => r.Rated == affiliateId && r.Rater == raterUserid).FirstOrDefault();
                if (null == lookup)
                {
                    lookup = new UserRating();
                    lookup.Rater = raterUserid;
                    lookup.Rated = affiliateId;
                    Context.UserRatings.Add(lookup);
                }
                lookup.Rating = rating;
                Update();
            }
            catch { return false; }

            return true;
        }
 public UserRating AddUserRating(UserRating rating)
 {
     return _repo.AddUserRating(rating);
 }