public static IHtmlString GetCourseRating(CourseRating courseRating)
        {
            int fullStars = (int)courseRating.Rating;

            int halfStar = courseRating.Rating - fullStars >= 0.5m
             ? 1
             : 0;

            int zeroStar = 5 - fullStars - halfStar;

            var sb = new StringBuilder();

            while (fullStars-- > 0)
            {
                sb.Append("<i class='tm-star fa fa-star'></i>");
            }
            while (halfStar-- > 0)
            {
                sb.Append("<i class='tm-star fa fa-star-half-o'></i>");
            }
            while (zeroStar-- > 0)
            {
                sb.Append("<i class='tm-star fa fa-star-o'></i>");
            }

            var courseRatingHtmlString = string.Format("<span class='text-nowrap' style='cursor: default;' title='{0:N1} points from {1} user(s)'>{2}</span>",
                                                       courseRating.Rating, courseRating.Raters, sb.ToString());

            var courseRatingMvcString = MvcHtmlString.Create(courseRatingHtmlString);

            return(courseRatingMvcString);
        }
Example #2
0
        public IActionResult AddRating(string courseId, int rating)
        {
            var user   = _userManager.GetUserAsync(User).Result;
            var course = _courseService.GetCourse(courseId);

            if (course == null || user == null)
            {
                return(BadRequest("Something went wrong!"));
            }

            if (!_access.CourseViewAccess(User, courseId))
            {
                return(BadRequest("You don't have access to the course"));
            }

            var rate = new CourseRating();

            if (_context.Ratings.Include(x => x.Course).Include(x => x.User).Where(x => x.Course == course).Any(x => x.User == user))
            {
                rate = _context.Ratings.Include(x => x.Course).Include(x => x.User).Where(x => x.CourseId == course.Id)
                       .Single(x => x.UserId == user.Id);
                rate.Rating = rating;
                _context.Ratings.Update(rate);
                _context.SaveChanges();
                return(Ok("Rating updated"));
            }

            rate = new CourseRating()
            {
                Course = course, User = user, Rating = rating
            };
            _context.Add(rate);
            _context.SaveChanges();
            return(Ok("Rating added"));
        }
        /// <exception cref="NodeParseException">Incorrect data in <paramref name="ratingNode"/>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="ratingNode"/> is <see langword="null" />.</exception>
        public CourseRating ParseCourseRating(INode ratingNode)
        {
            if (ratingNode == null)
            {
                throw new ArgumentNullException("ratingNode");
            }

            try
            {
                var ratingString = ratingNode.GetAttributeValue(Constants.CourseRatingAttribute);
                if (ratingString.Equals("Not enough course ratings", StringComparison.OrdinalIgnoreCase))
                {
                    return(new CourseRating());
                }
                // context: "X.X stars from Y users" where X - Rating; Y - RaterCount
                var stringParts = ratingString.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                var raters = int.Parse(stringParts[3], PositiveIntegerNumberStyle);
                var rating = decimal.Parse(stringParts[0], PositiveFloatNumberStyle, NumberFormatInfo.InvariantInfo);

                var courseRating = new CourseRating
                {
                    Raters = raters,
                    Rating = rating
                };
                return(courseRating);
            }
            // ReSharper disable once CatchAllClause
            catch (Exception ex)
            {
                var message = string.Format(Resources.CatalogNodeParseException_Message, "ratingNode");
                throw new NodeParseException(message, ratingNode.OuterText, ex);
            }
        }
        public CourseRating Update(CourseRating courseRatingChanges)
        {
            var courseRating = dBContext.CourseRatings.Attach(courseRatingChanges);

            courseRating.State = EntityState.Modified;
            dBContext.SaveChanges();
            return(courseRatingChanges);
        }
        public ActionResult Feedback(string CourseId)
        {
            if (Session["userId"] == null || Session["userId"].ToString() == "")
            {
                return(RedirectToAction("Index", "Home"));
            }
            ModelContext db           = new ModelContext();
            CourseRating courseRating = db.CourseRatings.Find(CourseId);

            return(View(courseRating));
        }
        public ActionResult Rating(string CourseId, int rating, string comment)
        {
            if (Session["userId"] == null || Session["userId"].ToString() == "")
            {
                return(RedirectToAction("Index", "Home"));
            }
            string       email        = Session["userId"].ToString();
            ModelContext db           = new ModelContext();
            CourseRating courseRating = db.CourseRatings.Find(CourseId);

            courseRating.UserRating = rating;
            courseRating.Comment    = comment;
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #7
0
        public void Should_ParseCourseRatingNode()
        {
            // Arrange
            var expected = new CourseRating {
                Raters = 103, Rating = 1.25m
            };
            var          nodeData = string.Format(CultureInfo.InvariantCulture, "{0} stars from {1} users", expected.Rating, expected.Raters);
            const string courseRatingAttribute = ParserConstants.CourseRatingAttribute;

            var ratingNode = Mock.Of <INode>(n => n.GetAttributeValue(courseRatingAttribute) == nodeData);

            var sut = new PluralsightNodeParser(SiteUrl, _nodeSelector);

            // Act
            var result = sut.ParseCourseRating(ratingNode);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(expected.Rating, result.Rating);
            Assert.Equal(expected.Raters, result.Raters);
        }
Example #8
0
        public void Should_ReturnEmptyRating_When_RatingNotSpecified()
        {
            // Arrange
            var expected = new CourseRating {
                Raters = 0, Rating = 0m
            };
            var          nodeData = "Not enough course ratings";
            const string courseRatingAttribute = ParserConstants.CourseRatingAttribute;

            var ratingNode = Mock.Of <INode>(n => n.GetAttributeValue(courseRatingAttribute) == nodeData);

            var sut = new PluralsightNodeParser(SiteUrl, _nodeSelector);

            // Act
            var result = sut.ParseCourseRating(ratingNode);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(expected.Rating, result.Rating);
            Assert.Equal(expected.Raters, result.Raters);
        }
        //public ActionResult UVIndex()
        //{
        //    if (Session["userId"] == null || Session["userId"].ToString() == "")
        //        return RedirectToAction("Index", "Home");

        //    ModelContext db = new ModelContext();
        //    List<OnlineServices> list = new List<OnlineServices>();
        //    List<Service> services = db.Services.ToList();
        //    foreach (Service s in services)
        //    {


        //        OnlineServices t = new OnlineServices();
        //        t.ServiceName = s.Name;
        //        t.Courses = new List<Course>();

        //        t.UserCourseRatings = new List<CourseRating>();
        //        List<Service_Course> sc = db.Service_Courses.ToList();
        //        foreach (Service_Course temp in sc)
        //        {
        //            if (temp.ServiceId == s.ServiceId)
        //            {
        //                t.Courses.Add(db.Courses.Find(temp.CourseId));

        //                CourseRating courseRating = db.CourseRatings.Find(temp.CourseId);
        //                t.UserCourseRatings.Add(courseRating);


        //            }
        //        }
        //        t.Amount = s.Amount;



        //        list.Add(t);

        //    }
        //    //return Content(" " + list[0].UserCourseRatings[0].UserRating+ " " + list[0].UserCourseRatings[1].UserRating);
        //    return View("UVIndex",list);
        //}

        public ActionResult UVIndex()
        {
            if (Session["userId"] == null || Session["userId"].ToString() == "")
            {
                return(RedirectToAction("Index", "Home"));
            }

            ModelContext          db       = new ModelContext();
            List <OnlineServices> list     = new List <OnlineServices>();
            List <Service>        services = db.Services.ToList();

            foreach (Service s in services)
            {
                OnlineServices t = new OnlineServices();
                t.ServiceName = s.Name;

                t.Courses = new List <Course>();

                t.UserCourseRatings = new List <CourseRating>();



                List <Service_Course> sc = db.Service_Courses.ToList();
                foreach (Service_Course temp in sc)
                {
                    if (temp.ServiceId == s.ServiceId)
                    {
                        t.Courses.Add(db.Courses.Find(temp.CourseId));
                        //t.UserCourseRatings.Add(db.CourseRatings.Find(temp.CourseId));
                        CourseRating courseRating = db.CourseRatings.Find(temp.CourseId);
                        t.UserCourseRatings.Add(courseRating);
                    }
                }
                t.Amount = s.Amount;

                list.Add(t);
            }

            return(View(list));
        }
        public bool CreateRating(CourseRatingCreate model)
        {
            var rating = new CourseRating()
            {
                CourseId      = model.CourseId,
                CourseRatings = model.CourseRatings,
                PlayerId      = model.PlayerId,
                DatePlayed    = model.DatePlayed,
                OwnerID       = _userId
            };

            using (var ctx = new ApplicationDbContext())
            {
                ctx.Ratings.Add(rating);
                if (ctx.SaveChanges() == 1)
                {
                    CalculateRating(rating.CourseId);
                    return(true);
                }
                return(false);
            }
        }
        public ViewResult Detail()
        {
            CourseDetailViewModel viewModel = new CourseDetailViewModel();

            if (Request.QueryString["course"] != null && StaticData.courseList.Where(p => GlobalFunctions.escapeQuerystringElement(p.code) == GlobalFunctions.escapeQuerystringElement(Request.QueryString["course"].ToString())).Count() == 1)
            {
                Course course = StaticData.courseList
                                .Where(p => GlobalFunctions.escapeQuerystringElement(p.code) == GlobalFunctions.escapeQuerystringElement(Request.QueryString["course"].ToString()))
                                .FirstOrDefault();

                //Get semesters to display
                List <Semester> semesterRange = StaticData.semesters.Where(p =>
                                                                           new SemesterComparer().Compare(p.semester, GlobalVariables.CurrentSemesterLow) >= 0 &&
                                                                           new SemesterComparer().Compare(p.semester, GlobalVariables.CurrentSemesterHigh) <= 0).ToList();

                List <CourseRating> courseRatings = CourseRatingRepositorySQL.Instance.listByCategoryAndSemesters(
                    Convert.ToInt32(GlobalVariables.CurrentCategory), semesterRange.Select(p => p.semester).ToArray())
                                                    .Where(p => p.classSize >= p.responses)
                                                    .ToList();

                //Filter only sections within the department (Not all ratings of a professor who had a course within that department)
                courseRatings = courseRatings.Where(p => p.courseID == course.courseID).ToList();

                List <Instructor> instructorsAll = InstructorRepositorySQL.Instance.listByCourse(course.courseID)
                                                   .Where(p => courseRatings.Select(u => u.instructorID).Distinct().Contains(p.instructorID))
                                                   .ToList();

                var instructorDeptMapping = instructorsAll.Select(p =>
                {
                    CourseRating firstRating = courseRatings.Where(u => u.instructorID == p.instructorID).FirstOrDefault();
                    var dept = StaticData.courseList.Where(t => t.courseID == firstRating.courseID).FirstOrDefault().departmentID;
                    return(new
                    {
                        instructorID = p.instructorID,
                        departmentID = dept
                    });
                }).ToList();

                int    totalResponses = 0;
                int    totalStudents  = 0;
                double averageRating  = 0.0;

                List <InstructorDomain> instructors = instructorsAll.Select(p =>
                {
                    var courseRatingInstructor = courseRatings.Where(x => x.instructorID == p.instructorID);
                    var responses = courseRatingInstructor.Select(y => y.responses).Sum(z => z);
                    var students  = courseRatingInstructor.Select(y => y.classSize).Sum(z => z);
                    var semesters = courseRatingInstructor.Select(v => v.semester).Distinct()
                                    .OrderByDescending(t => t, new SemesterComparer());

                    totalResponses += responses;
                    totalStudents  += students;
                    averageRating  += courseRatingInstructor.Sum(z => (double)z.responses * z.ratings[0].averageRating);

                    return(new InstructorDomain
                    {
                        instructorID = p.instructorID,
                        firstName = p.firstName,
                        lastName = p.lastName,
                        responses = responses.ToString(),
                        students = students.ToString(),
                        responseRate = ((double)responses / (double)students).ToString("p1"),
                        department = StaticData.departmentList.Where(x => x.departmentID == instructorDeptMapping.Where(a => a.instructorID == p.instructorID).FirstOrDefault().departmentID).FirstOrDefault().name,
                        lastSemester = (semesters.Count() > 0 ? semesters.FirstOrDefault() : ""),
                        rating = courseRatingInstructor.Sum(z => ((double)z.responses / (double)responses) * z.ratings[0].averageRating).ToString("#.##")
                    });
                }).ToList();

                viewModel.course              = course;
                viewModel.instructors         = instructors;
                viewModel.totalResponses      = totalResponses.ToString("N0");
                viewModel.totalStudents       = totalStudents.ToString("N0");
                viewModel.averageResponseRate = ((double)totalResponses / (double)totalStudents).ToString("p1");
                viewModel.averageRating       = (averageRating / (double)totalResponses).ToString("#.##");
                viewModel.currentSemesterLow  = GlobalVariables.CurrentSemesterLow.Split(' ')[1] + " " + GlobalVariables.CurrentSemesterLow.Split(' ')[0];
                viewModel.currentSemesterHigh = GlobalVariables.CurrentSemesterHigh.Split(' ')[1] + " " + GlobalVariables.CurrentSemesterHigh.Split(' ')[0];
            }
            else
            {
                throw new HttpException(404, "Course not found!");
            }

            return(View(viewModel));
        }
      /// <exception cref="NodeParseException">Incorrect data in <paramref name="ratingNode"/>.</exception>
      /// <exception cref="ArgumentNullException"><paramref name="ratingNode"/> is <see langword="null" />.</exception>
      public CourseRating ParseCourseRating(INode ratingNode)
      {
         if (ratingNode == null) 
            throw new ArgumentNullException("ratingNode");

         try
         {
            var ratingString = ratingNode.GetAttributeValue(Constants.CourseRatingAttribute);
            if (ratingString.Equals("Not enough course ratings", StringComparison.OrdinalIgnoreCase))
            {
               return new CourseRating();
            }
            // context: "X.X stars from Y users" where X - Rating; Y - RaterCount
            var stringParts = ratingString.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);

            var raters = int.Parse(stringParts[3], PositiveIntegerNumberStyle);
            var rating = decimal.Parse(stringParts[0], PositiveFloatNumberStyle, NumberFormatInfo.InvariantInfo);

            var courseRating = new CourseRating
            {
               Raters = raters,
               Rating = rating
            };
            return courseRating;
         }
         // ReSharper disable once CatchAllClause
         catch (Exception ex)
         {
            var message = string.Format(Resources.CatalogNodeParseException_Message, "ratingNode");
            throw new NodeParseException(message, ratingNode.OuterText, ex);
         }
      }
Example #13
0
        public ViewResult Detail()
        {
            CollegeDetailViewModel viewModel = new CollegeDetailViewModel();

            if (Request.QueryString["college"] != null && StaticData.collegeList.Where(p => GlobalFunctions.escapeQuerystringElement(p.name) == GlobalFunctions.escapeQuerystringElement(Request.QueryString["college"].ToString())).Count() == 1)
            {
                College college = StaticData.collegeList
                                  .Where(p => GlobalFunctions.escapeQuerystringElement(p.name) == GlobalFunctions.escapeQuerystringElement(Request.QueryString["college"].ToString()))
                                  .FirstOrDefault();

                List <CourseRating> courseRatings = CourseRatingRepositorySQL.Instance.listByCategoryAndSemesters(
                    Convert.ToInt32(GlobalVariables.CurrentCategory),
                    (GlobalVariables.CurrentSemester == "-1" ? StaticData.semesters.Take(3).Select(y => y.semester).ToArray() : new[] { GlobalVariables.CurrentSemester }))
                                                    .Where(p => p.classSize >= p.responses)
                                                    .ToList();

                List <Instructor> instructorsAll = InstructorRepositorySQL.Instance.listByCollege(college.collegeID)
                                                   .Where(p => courseRatings.Select(u => u.instructorID).Distinct().Contains(p.instructorID))
                                                   .ToList();

                var instructorDeptMapping = instructorsAll.Select(p => {
                    CourseRating firstRating = courseRatings.Where(u => u.instructorID == p.instructorID).FirstOrDefault();
                    var dept = StaticData.courseList.Where(t => t.courseID == firstRating.courseID).FirstOrDefault().departmentID;
                    return(new
                    {
                        instructorID = p.instructorID,
                        departmentID = dept
                    });
                }).ToList();

                int    totalResponses = 0;
                int    totalStudents  = 0;
                double averageRating  = 0.0;

                //Add department
                List <InstructorDomain> instructors = instructorsAll.Select(p => {
                    var courseRatingInstructor = courseRatings.Where(x => x.instructorID == p.instructorID && StaticData.departmentList
                                                                     .Where(y => y.departmentID == StaticData.courseDeptMapping[x.courseID.ToString()]).FirstOrDefault().collegeID == college.collegeID);
                    var responses = courseRatingInstructor.Select(y => y.responses).Sum(z => z);
                    var students  = courseRatingInstructor.Select(y => y.classSize).Sum(z => z);
                    var semesters = courseRatingInstructor.Select(v => v.semester).Distinct()
                                    .OrderByDescending(t => t, new SemesterComparer());

                    totalResponses += responses;
                    totalStudents  += students;
                    averageRating  += courseRatingInstructor.Sum(z => (double)z.responses * z.ratings[0].averageRating);

                    return(new InstructorDomain
                    {
                        instructorID = p.instructorID,
                        firstName = p.firstName,
                        lastName = p.lastName,
                        responses = responses.ToString(),
                        students = students.ToString(),
                        responseRate = ((double)responses / (double)students).ToString("p1"),
                        department = StaticData.departmentList.Where(x => x.departmentID == instructorDeptMapping.Where(a => a.instructorID == p.instructorID).FirstOrDefault().departmentID).FirstOrDefault().name,
                        lastSemester = (semesters.Count() > 0 ? semesters.FirstOrDefault() : ""),
                        rating = courseRatingInstructor.Sum(z => ((double)z.responses / (double)responses) * z.ratings[0].averageRating).ToString("#.##")
                    });
                }).ToList();

                viewModel.college             = college;
                viewModel.instructors         = instructors;
                viewModel.totalResponses      = totalResponses.ToString("N0");
                viewModel.totalStudents       = totalStudents.ToString("N0");
                viewModel.averageResponseRate = ((double)totalResponses / (double)totalStudents).ToString("p1");
                viewModel.averageRating       = (averageRating / (double)totalResponses).ToString("#.##");
                viewModel.currentSemester     = (GlobalVariables.CurrentSemester == "-1" ? "the past three semesters" : GlobalVariables.CurrentSemester.Split(' ')[1] + " " + GlobalVariables.CurrentSemester.Split(' ')[0]);
            }
            else
            {
                throw new HttpException(404, "College not found!");
            }

            return(View(viewModel));
        }
Example #14
0
 public async Task UpdateRatingAsync(CourseRating task)
 {
     _context.Entry(task).State = EntityState.Modified;
     await _context.SaveChangesAsync();
 }
Example #15
0
 public async Task RateAsync(CourseRating rating)
 {
     _context.CourseRating.Add(rating);
     await _context.SaveChangesAsync();;
 }
Example #16
0
        public async Task <ActionResult <string> > UpdateRatings([FromBody] UserView updateData)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var viewed =
                await _dbContext.UserViews
                .Where(c =>
                       c.CourseId == updateData.CourseId && c.UserId == updateData.UserId)
                .ToListAsync();

            bool contained = viewed.Any(c => c.VideoId == updateData.VideoId);

            if (contained)
            {
                return(Ok());
            }

            // get course
            var course = await _dbContext.Courses.FirstOrDefaultAsync(c => c.CourseId == updateData.CourseId);

            // Get Course Rating
            var courseRating =
                await _dbContext.CourseRatings
                .FirstOrDefaultAsync(c =>
                                     c.CourseId == updateData.CourseId && c.UserId == updateData.UserId);

            // Increment Views
            var viewedCount = viewed.Count + 1;

            _dbContext.UserViews.Add(new UserView
            {
                UserId   = updateData.UserId,
                CourseId = updateData.CourseId,
                VideoId  = updateData.VideoId
            });
            // Increment Rating
            var rating = (float)((float)viewedCount / course.VideoCount * maxRating);

            if (courseRating == null)
            {
                courseRating = new CourseRating
                {
                    UserId   = updateData.UserId,
                    CourseId = updateData.CourseId,
                    Rating   = rating
                };
            }
            else
            {
                courseRating.Rating = rating;
            }

            _dbContext.CourseRatings.Update(courseRating);
            await _dbContext.SaveChangesAsync();

            SaveModel();
            return(Ok());
        }
 public CourseRating Create(CourseRating courseRating)
 {
     dBContext.CourseRatings.Add(courseRating);
     dBContext.SaveChanges();
     return(courseRating);
 }
      public void Should_ParseCourseRatingNode()
      {
         // Arrange
         var expected = new CourseRating { Raters = 103, Rating = 1.25m };
         var nodeData = string.Format(CultureInfo.InvariantCulture, "{0} stars from {1} users", expected.Rating, expected.Raters);
         const string courseRatingAttribute = ParserConstants.CourseRatingAttribute;

         var ratingNode = Mock.Of<INode>(n => n.GetAttributeValue(courseRatingAttribute) == nodeData);

         var sut = new PluralsightNodeParser(SiteUrl, _nodeSelector);

         // Act
         var result = sut.ParseCourseRating(ratingNode);

         // Assert
         Assert.NotNull(result);
         Assert.Equal(expected.Rating, result.Rating);
         Assert.Equal(expected.Raters, result.Raters);
      }
 public static IHtmlString DisplayCourseRating(this HtmlHelper html, CourseRating courseRating)
 {
     return(GetCourseRating(courseRating));
 }
      public void Should_ReturnEmptyRating_When_RatingNotSpecified()
      {
         // Arrange
         var expected = new CourseRating { Raters = 0, Rating = 0m };
         var nodeData = "Not enough course ratings";
         const string courseRatingAttribute = ParserConstants.CourseRatingAttribute;

         var ratingNode = Mock.Of<INode>(n => n.GetAttributeValue(courseRatingAttribute) == nodeData);

         var sut = new PluralsightNodeParser(SiteUrl, _nodeSelector);

         // Act
         var result = sut.ParseCourseRating(ratingNode);

         // Assert
         Assert.NotNull(result);
         Assert.Equal(expected.Rating, result.Rating);
         Assert.Equal(expected.Raters, result.Raters);
      }
        public async Task <IActionResult> RateCourse([FromBody] CourseRating courseRating)
        {
            var lang          = Request.Headers["language"].ToString();
            var errorMessages = new List <string>();

            try
            {
                var user = await _userManager.FindByIdAsync(courseRating.UserId);

                var course = _courseRepository.FindById(courseRating.CourseId);

                if (user == null || course == null)
                {
                    errorMessages.Add(_translator.GetTranslation("ERROR", lang));
                    return(BadRequest(new { errors = errorMessages }));
                }


                var allowedValues = new List <float>()
                {
                    1, 2, 3, 4, 5
                };

                if (!allowedValues.Contains(courseRating.Value))
                {
                    errorMessages.Add(_translator.GetTranslation("ERROR", lang));
                    return(BadRequest(new { errors = errorMessages }));
                }

                var          rating = _courseRatingRepository.FindByUserCourse(user.Id, course.Id);
                CourseRating createdCourseRating;

                if (rating == null)
                {
                    var newRating = new CourseRating()
                    {
                        Course       = course,
                        CourseId     = course.Id,
                        User         = user,
                        UserId       = user.Id,
                        Value        = courseRating.Value,
                        RateDateTime = DateTime.Now
                    };

                    createdCourseRating = _courseRatingRepository.Create(newRating);
                }
                else
                {
                    rating.OldValue            = rating.Value;
                    rating.Value               = courseRating.Value;
                    rating.RateDateTimeUpdated = DateTime.Now;

                    createdCourseRating = _courseRatingRepository.Update(rating);
                }

                if (createdCourseRating == null)
                {
                    errorMessages.Add(_translator.GetTranslation("ERROR", lang));
                    return(BadRequest(new { errors = errorMessages }));
                }

                //await _hubContext.Clients.All.SendAsync("SignalCourseRateReceived", ResponseGenerator.GenerateCourseResponse(course));

                return(Ok(new { course = ResponseGenerator.GenerateCourseResponse(course, false) }));
            }
            catch
            {
                errorMessages.Add(_translator.GetTranslation("ERROR", lang));
                return(BadRequest(new { errors = errorMessages }));
            }
        }