//Alright gents... here we go...

        //A few notes. First, we made was in the data assembly --> Ratings Class there were two classes inside of another class. We removed the class the was housing the two classes and commented out the one with the list in it.

        //Second, We also updated some names for clarification and added two Foreign Keys so that the ratings get connected to the specific instrument or product.

        //Third, I also changes the ID in accessory data table to "AccessoryId" for clarification

        //Fourth, we created an "AverageRating" property in both Instrument and Accessory data models


        //Directly below is the create a Product rating that takes in the values passed in through Postman and then calls in the AverageRating method (directly below) which creates the average and then saves it. Jess helped us so this a hybrid of the one he shared and the average method that was originally in here.

        //I'll note out steps
        public bool CreatingProductRating(RatingCreate model)
        {
            // Here is like all our other create functins just passing in the model
            var entity =
                new ProductRating()
            {
                StarRating   = model.StarRating,
                InstrumentId = model.InstrumentId,
                AccessoryId  = model.AccessoryId,
            };

            using (var ctx = new ApplicationDbContext())
            {
                //Opened the Dbcontext and then "entity" passes in the model directly above
                ctx.Ratings.Add(entity);

                //This saves the changes the "entity" model passes into the Ratings Dbcontext before we send it to the AverageRating method. Jess wasn't sure why this step was needed, but I think it adds it to the table.
                ctx.SaveChanges();

                //This send the info to the averaging method below
                AverageRating(model.InstrumentId, model.AccessoryId);

                //It's odd everything actually runs through the Averaging method before it hits this step
                return(ctx.SaveChanges() == 0);
            }
        }
Beispiel #2
0
        public async Task <IActionResult> RateProduct(int id)
        {
            var user = await GetCurrentUserAsync();

            //gives us a default value for message
            HttpContext.Session.SetString("Message", "");
            //gives a list of all product ratings that contain the current users id & the id
            //of the selected product
            List <ProductRating> productRatings = _context.ProductRating.Where(pr => pr.ProductId == id && pr.UserId == user.Id).ToList();

            //checks if a product rating already exists for this user & this product
            if (productRatings.Count > 0)
            {
                //sets message in session storage to the appropriate error
                HttpContext.Session.SetString("Message", "You have already rated this product.");
                //sends the user back to the order history index view
                return(RedirectToAction("OrderHistoryIndex", "Profile"));
            }

            ProductRating productRating = new ProductRating
            {
                ProductId = id,
                UserId    = user.Id,
                Rating    = null
            };

            return(View(productRating));
        }
Beispiel #3
0
        public IActionResult RateProductUsingEntity(
            [FromODataUri] int key,
            ODataActionParameters parameters)
        {
            try
            {
                if (parameters == null)
                {
                    return(BadRequest());
                }

                if (!parameters.ContainsKey("value"))
                {
                    return(BadRequest());
                }

                ProductRating rating = (ProductRating)parameters["value"];

                rating.ProductId = key;
                rating.Username  = User.Identity.Name ?? string.Empty;
                rating.RatedOn   = DateTime.UtcNow;

                _businessService.RateProduct(rating);

                return(Ok());
            }
            catch (ItemNotFoundException)
            {
                return(NotFound());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Beispiel #4
0
        public async Task <IActionResult> Edit(int id, [Bind("ProductRatingId,ProductId,UserId,Rating")] ProductRating productRating)
        {
            if (id != productRating.ProductRatingId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(productRating);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ProductRatingExists(productRating.ProductRatingId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ProductId"] = new SelectList(_context.Product, "ProductId", "Description", productRating.ProductId);
            ViewData["UserId"]    = new SelectList(_context.ApplicationUsers, "Id", "Id", productRating.UserId);
            return(View(productRating));
        }
Beispiel #5
0
        // GET: ProductRatings/Details/5
        public async Task <IActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var productRating = await _context.ProductRating
                                .Include(p => p.Product)
                                .Include(p => p.User)
                                .FirstOrDefaultAsync(m => m.ProductId == id);

            if (productRating == null)
            {
                var nullProductRating = new ProductRating();
                nullProductRating.Product = await _context.Product
                                            .Include(p => p.ProductType)
                                            .Include(p => p.User)
                                            .FirstOrDefaultAsync(m => m.ProductId == id);

                nullProductRating.User = await GetCurrentUserAsync();

                return(View(nullProductRating));
            }

            return(View(productRating));
        }
Beispiel #6
0
        public async Task <IActionResult> CreateRating(ProductRating productRating)
        {
            _context.Add(productRating);
            await _context.SaveChangesAsync();

            return(RedirectToAction("OrderHistoryIndex", "Profile"));
        }
        public virtual void SaveProductRating(ProductRating productRating)
        {
            if (productRating == null)
            {
                throw new ArgumentNullException(nameof(productRating));
            }

            using (var repository = _repositoryFactory())
                using (var changeTracker = base.GetChangeTracker(repository))
                {
                    var sourceEntity = AbstractTypeFactory <ProductRatingEntity> .TryCreateInstance()
                                       .FromModel(productRating);

                    var targetEntity = repository.ProductRatings
                                       .Where(x => x.ProductId == productRating.ProductId)
                                       .FirstOrDefault();


                    if (targetEntity != null)
                    {
                        changeTracker.Attach(targetEntity);
                        sourceEntity.Patch(targetEntity);
                    }
                    else
                    {
                        repository.Add(sourceEntity);
                    }

                    repository.UnitOfWork.Commit();
                }
        }
        public ProductRating ToModel(ProductRating model)
        {
            model.ProductId = ProductId;
            model.Rating    = Rating;

            return(model);
        }
Beispiel #9
0
        public IHttpActionResult PostProductRating(int id, ProductRatingBindingModel rateFromBody)
        {
            if (!db.Products.Any(p => p.Id == id))
            {
                return(NotFound());
            }

            var productRating = new ProductRating
            {
                Rating    = rateFromBody.Rating,
                UserId    = UserHelper.GetCurrentUserId(),
                ProductId = id,
                Added     = DateTime.Now
            };

            db.ProductRatings.Add(productRating);
            try
            {
                db.SaveChanges();
            }
            catch (Exception)
            {
                return(BadRequest("ocena już wystawiona"));
            }

            return(Ok(productRating));
        }
        private static SqlParameter[] GetInsertOrUpdateParameterArray(ProductRating productRating)
        {
            var result = new List <SqlParameter>()
            {
                new SqlParameter("@PID", (decimal)productRating.PID),
                new SqlParameter("@Language", productRating.LanguageString),

                new SqlParameter("@NativeRating1s", productRating.NativeRatings[1]),
                new SqlParameter("@NativeRating2s", productRating.NativeRatings[2]),
                new SqlParameter("@NativeRating3s", productRating.NativeRatings[3]),
                new SqlParameter("@NativeRating4s", productRating.NativeRatings[4]),
                new SqlParameter("@NativeRating5s", productRating.NativeRatings[5]),

                new SqlParameter("@ExternalRating1s", productRating.ExternalRatings[1]),
                new SqlParameter("@ExternalRating2s", productRating.ExternalRatings[2]),
                new SqlParameter("@ExternalRating3s", productRating.ExternalRatings[3]),
                new SqlParameter("@ExternalRating4s", productRating.ExternalRatings[4]),
                new SqlParameter("@ExternalRating5s", productRating.ExternalRatings[5]),

                new SqlParameter("@NativeTotalReviews", productRating.NativeTotalReviewCount),
                new SqlParameter("@ExternalTotalReviews", productRating.ExternalTotalReviewCount)
            };

            return(result.ToArray());
        }
Beispiel #11
0
        public IHttpActionResult PutProductRating(int productId, int userId, ProductRating productRating)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            if (productId != productRating.ProductId && userId != productRating.UserId)
            {
                return(BadRequest());
            }

            db.Entry(productRating).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (db.ProductRatings.Count(e => e.ProductId == productId && e.UserId == userId) == 0)
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Beispiel #12
0
        public IQueryable <ProductRating> GetRatings()
        {
            List <ProductRating> res = new List <ProductRating>();
            string queryString       = "SELECT * FROM dbo.ProductRatings;";

            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                SqlCommand command = new SqlCommand(queryString, conn);


                conn.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var result = new ProductRating()
                        {
                            ProductId = (int)reader[0]
                        };
                        result.AverageRating = reader[1] == DBNull.Value ? null : (decimal?)reader[1];
                        res.Add(result);
                    }
                }
            }
            return(res.AsQueryable());
        }
Beispiel #13
0
        public void TestAuthorId_ShouldWorkCorrectly(string authorId)
        {
            var productRating = new ProductRating();

            productRating.AuthorId = authorId;

            Assert.AreEqual(authorId, productRating.AuthorId);
        }
 public async Task EditProductRating(ProductRating productRating, double rating)
 {
     if (productRating != null)
     {
         productRating.Rating = rating;
     }
     await context.SaveChangesAsync();
 }
        public bool Remove(ProductRatingVM rvm)
        {
            ProductRating productRating = db.ProductRatings.Find(rvm.ID);

            db.ProductRatings.Remove(productRating);
            db.SaveChanges();
            return(true);
        }
        public bool Remove(long id)
        {
            ProductRating productRating = db.ProductRatings.Find(id);

            db.ProductRatings.Remove(productRating);
            db.SaveChanges();
            return(true);
        }
Beispiel #17
0
        public void TestProductRatingId_ShouldWorkCorrectly(int productRatingId)
        {
            var productRating = new ProductRating();

            productRating.ProductRatingId = productRatingId;

            Assert.AreEqual(productRatingId, productRating.ProductRatingId);
        }
Beispiel #18
0
        public ActionResult DeleteConfirmed(int id)
        {
            ProductRating productRating = db.ProductRatings.Find(id);

            db.ProductRatings.Remove(productRating);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public static IHtmlString Rating(this System.Web.Mvc.HtmlHelper html, ProductRating rating)
 {
     if (rating == null || rating.ReviewCount == 0)
     {
         return(new MvcHtmlString("<span><em>No Rating</em></span>"));
     }
     return(html.Partial("_Rating", rating));
 }
        public ActionResult Rate(Rating rating)
        {
            string currentUser  = User.Identity.GetUserId();
            int    ratedProduct = rating.ProductId;

            try
            {
                bool alreadyRated = false;

                foreach (Rating x in db.Ratings)
                {
                    if (x.ProductId == ratedProduct && x.UserId == currentUser)
                    {
                        alreadyRated             = true;
                        TempData["AlreadyRated"] = "You have already rated this product.";
                        Redirect("/Products/Show/" + ratedProduct);
                    }
                }
                if (!alreadyRated)
                {
                    Rating mark = new Rating();
                    mark.UserId    = currentUser;
                    mark.ProductId = ratedProduct;
                    mark.Mark      = rating.Mark;

                    db.Ratings.Add(mark);
                    db.SaveChanges();
                    TempData["message"] = "You have rated this product!";

                    float overallRating = 0;
                    int   nr            = 0;

                    foreach (Rating x in db.Ratings)
                    {
                        if (x.ProductId == ratedProduct)
                        {
                            overallRating += x.Mark;
                            nr++;
                        }
                    }

                    ProductRating productRating = db.ProductRatings.Find(ratedProduct);

                    if (TryUpdateModel(productRating))
                    {
                        productRating.Rating = overallRating / nr;
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception e)
            {
                return(Redirect("/Products/Show/" + ratedProduct));
            }

            return(Redirect("/Products/Show/" + ratedProduct));
        }
Beispiel #21
0
        public void AddRatingToProduct_Fail()
        {
            ProductRating rating = new ProductRating {
                Id = 0, Rating = 3
            };
            var result = _controller.AddProductRating(rating);

            Assert.That(result, Is.InstanceOf <BadRequestResult>());
        }
Beispiel #22
0
        public void Constructor_ShouldSetAuthorContentCorrectly(int rating, string content)
        {
            var mockedProduct = new Mock <Product>();
            var mockedUser    = new Mock <User>();

            var productRating = new ProductRating(rating, content, mockedProduct.Object, mockedUser.Object);

            Assert.AreEqual(productRating.Author, mockedUser.Object);
        }
        public void Update(ProductRating productRating)
        {
            _logger.Debug("In Update.");

            var parameters = GetInsertOrUpdateParameterArray(productRating);

            ExecuteNonQuery("uspProductRatingsUpdate", parameters);

            _logger.Debug("Existing Update.");
        }
        private IEnumerable <ProductRating> GetProductRatings(Product product)
        {
            Log.Debug("In GetProductRatings");

            long productId;

            if (!long.TryParse(product.Id, out productId))
            {
                var message = string.Format("Product ID is not in the correct format. Skipping. PID: {0}", product.Id);
                Log.Error(message);
                if (ExecutionLogLoggerMessageLimit == 0 || _executionLogLoggerMessageCount++ <= ExecutionLogLoggerMessageLimit)
                {
                    _executionLogLogger.AddCustomMessage(message);
                }
                else if (ExecutionLogLoggerMessageLimit != 0)
                {
                    Log.ErrorFormat("ExecutionLogLogger message limit of {0} has been exceeded.",
                                    ExecutionLogLoggerMessageLimit);
                }

                return(Enumerable.Empty <ProductRating>());
            }

            var externalReviewStatistics = ComputeExternalReviewStatistics(product.Id, product.NativeReviewStatistics,
                                                                           product.ReviewStatistics);

            var nativeLocaleDistributionItems   = GetAggregatedLocaleDistributionItems(product.NativeReviewStatistics);
            var externalLocaleDistributionItems = GetAggregatedLocaleDistributionItems(externalReviewStatistics);

            var generalLocaleList = GetCombinedLocaleList(GetDisplayLocaleList(nativeLocaleDistributionItems), GetDisplayLocaleList(externalLocaleDistributionItems));

            var result = generalLocaleList.Select(generalLocaleString =>
            {
                LocaleDistributionItem nativeDistributionItem =
                    nativeLocaleDistributionItems.FirstOrDefault(
                        item => item.DisplayLocale.Equals(generalLocaleString, StringComparison.OrdinalIgnoreCase));

                LocaleDistributionItem externalDistributionItem =
                    externalLocaleDistributionItems.FirstOrDefault(
                        item => item.DisplayLocale.Equals(generalLocaleString, StringComparison.OrdinalIgnoreCase));

                var localizedNativeReviewStatistics   = GetReviewStatistics(nativeDistributionItem);
                var localizedExternalReviewStatistics = GetReviewStatistics(externalDistributionItem);

                var resultItem = new ProductRating(productId, generalLocaleString,
                                                   localizedNativeReviewStatistics,
                                                   localizedExternalReviewStatistics);

                return(resultItem);
            });

            Log.Debug("Exiting GetProductRatings");

            return(result);
        }
        public virtual ProductRatingEntity FromModel(ProductRating productRating)
        {
            if (productRating == null)
            {
                throw new ArgumentNullException(nameof(productRating));
            }
            ProductId = productRating.ProductId;
            Rating    = productRating.Rating;

            return(this);
        }
        public ProductRatingVM Update(ProductRatingVM rvm)
        {
            ProductRating productRating = db.ProductRatings.Find(rvm.ID);

            productRating.ProductID = rvm.ProductID;
            productRating.Star      = rvm.Star;

            db.Entry(productRating).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            db.SaveChanges();
            return(rvm);
        }
Beispiel #27
0
 public async Task <bool> CreateRating(ProductRating rating)
 {
     if (await _ratingRepository.CreateRating(rating))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Beispiel #28
0
 public ActionResult Edit([Bind(Include = "Id,ProductId,UserId,DateTime,IP,Rating")] ProductRating productRating)
 {
     if (ModelState.IsValid)
     {
         db.Entry(productRating).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.ProductId = new SelectList(db.Products, "Id", "Name", productRating.ProductId);
     ViewBag.UserId    = new SelectList(db.Users, "Id", "Name", productRating.UserId);
     return(View(productRating));
 }
Beispiel #29
0
 public async Task <bool> CreateRating(ProductRating rating)
 {
     _context.Add(rating);
     if (await _context.SaveChangesAsync() > 0)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
        public ProductRatingVM Add(ProductRatingVM rvm)
        {
            ProductRating productRating = new ProductRating();

            productRating.ProductID = rvm.ProductID;
            productRating.Star      = rvm.Star;

            db.ProductRatings.Add(productRating);
            db.SaveChanges();
            rvm.ID = productRating.ID;
            return(rvm);
        }
 public static ProductRating CreateProductRating(int ID, int productID, int rating)
 {
     ProductRating productRating = new ProductRating();
     productRating.ID = ID;
     productRating.ProductID = productID;
     productRating.Rating = rating;
     return productRating;
 }
        public void Insert(int ProductId,string UserName,int Rating,string CreatedBy,DateTime CreatedOn,string ModifiedBy,DateTime ModifiedOn)
        {
            ProductRating item = new ProductRating();

            item.ProductId = ProductId;

            item.UserName = UserName;

            item.Rating = Rating;

            item.CreatedBy = CreatedBy;

            item.CreatedOn = CreatedOn;

            item.ModifiedBy = ModifiedBy;

            item.ModifiedOn = ModifiedOn;

            item.Save(UserName);
        }
 public void AddToRatings(ProductRating productRating)
 {
     base.AddObject("Ratings", productRating);
 }