Esempio n. 1
0
        private void PushRatingToCache(User user)
        {
            // TODO add thread-safe version
            if (!user.Points.HasValue)
            {
                return;
            }

            var ratingInfo = new RatingInfo
            {
                AvatarUrl = user.AvatarUrl,
                NickName  = user.NickName,
                LastPlace = user.LastRatingPlace
            };
            Dictionary <string, RatingInfo> dict;

            if (!_userRatings.TryGetValue(user.Points.Value, out dict)) //user points can't be null
            {
                _userRatings.Add(user.Points.Value, new Dictionary <string, RatingInfo> {
                    { user.Id, ratingInfo }
                });
            }
            else
            {
                dict.Add(user.Id, ratingInfo);
            }
        }
Esempio n. 2
0
        public async Task UpdateUserRating(User user, int?oldPoints, int newPoints)
        {
            var ratingInfo = new RatingInfo
            {
                LastPlace = user.LastRatingPlace,
                AvatarUrl = user.AvatarUrl,
                NickName  = user.NickName
            };

            if (oldPoints.HasValue)
            {
                _userRatings[oldPoints.Value].Remove(user.Id);
                if (_userRatings[oldPoints.Value].Values.Count == 0)
                {
                    _userRatings.Remove(oldPoints.Value);
                }
            }

            Dictionary <string, RatingInfo> dict;

            if (!_userRatings.TryGetValue(newPoints, out dict))
            {
                _userRatings.Add(newPoints, new Dictionary <string, RatingInfo> {
                    { user.Id, ratingInfo }
                });
            }
            else
            {
                dict.Add(user.Id, ratingInfo);
            }
            await Task.Yield();
        }
Esempio n. 3
0
        private void UpdateComment(uint start, uint end)
        {
            var commentRequest = new GetRatingMotionInfoStoreRequest(MotionID, start, end);

            commentRequest.ProcessSuccessfully += (reply) =>
            {
                foreach (var comment in reply.rating_info.ratingInfoMotion)
                {
                    RatingInfo comment1 = comment;
                    Dispatcher.BeginInvoke((Action) delegate
                    {
                        var item = new CommentItem(comment1);
                        ReviewStackPanel.Children.Add(item);
                        numberOfComment++;
                        //for (int i = 0; i < 20; i++)
                        //{
                        //    var item = new CommentItem(comment1);
                        //    ReviewStackPanel.Children.Add(item);
                        //    numberOfComment++;
                        //    Console.WriteLine(numberOfComment);
                        //}
                    });
                }
                //Console.WriteLine(ReviewStackPanel.Children.Count);
            };
            commentRequest.ProcessError += (reply, msg) => Debug.Assert(false, msg);
            GlobalVariables.StoreWorker.ForceAddRequest(commentRequest);
        }
 public IActionResult addRating([FromBody] RatingInfo rating)
 {
     try
     {
         return(Ok(ratingService.addRating(rating)));
     }
     catch (Exception e)
     {
         return(NoContent());
     }
 }
Esempio n. 5
0
        public CommentItem(RatingInfo ratingInfo)
        {
            InitializeComponent();

            Info        = ratingInfo;
            DataContext = new CommentItemViewModel();
            ViewModel   = (CommentItemViewModel)DataContext;

            ViewModel.CommentTitle   = ratingInfo.comment_title;
            ViewModel.RatingValue    = ratingInfo.rating / GlobalVariables.RateValueMultiplierFactor;
            ViewModel.UserReview     = FormatUserReviewString(ratingInfo.user_name, ratingInfo.rating_time);
            ViewModel.CommentContent = ratingInfo.comment_content;
        }
Esempio n. 6
0
 private static List <KeyValuePair <string, RatingInfo> > GenerateFilledRatings(
     int points,
     Dictionary <string, RatingInfo> ratingGroup)
 {
     return(ratingGroup.OrderBy(dic => dic.Value.LastPlace).Select(
                dic =>
     {
         var info = new RatingInfo();
         dic.Value.CopyTo(info);
         info.Points = points;
         info.UserId = dic.Key;
         return new KeyValuePair <string, RatingInfo>(dic.Key, info);
     }).ToList());
 }
Esempio n. 7
0
    public bool SetRating(RatingInfo _info)
    {
        if (ratingsNumber >= _maxNumber)
        {
            return(false);
        }

        var item = _itemFactory.Allocate().GetComponent <RatingsListItem>();

        _LocateItem(item);

        item.score = _info.score;
        item.pname = _info.name;
        item.place = _info.place;

        return(true);
    }
Esempio n. 8
0
        public ActionResult AddRating(int itemId, int itemType, int price, int quality, int doctor, int attitude, int facility, int customer)
        {
            var objRating = new RatingInfo()
            {
                UserId   = -1,
                ItemId   = itemId,
                ItemType = itemType,
                Price    = price,
                Quality  = quality,
                Doctor   = doctor,
                Attitude = attitude,
                Facility = facility,
                Customer = customer
            };
            var result = new RatingController().InsertRating(objRating);

            return(PartialView(result));
        }
Esempio n. 9
0
 public bool addRating(RatingInfo rating)
 {
     try
     {
         var    rideId     = cabODbContext.Ride.FirstOrDefault(r => r.Guid == rating.rideId).Id;
         Rating ratingData = new Rating {
             RideId    = rideId,
             Timing    = rating.timing,
             Behaviour = rating.behaviour,
             Overall   = rating.overall,
             Comments  = rating.comments
         };
         cabODbContext.Rating.Add(ratingData);
         cabODbContext.SaveChanges();
         return(true);
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Esempio n. 10
0
        public void ShouldWriteRatingInfo()
        {
            RatingInfo ratingInfo = new RatingInfo();

            ratingInfo.RatingSource   = "mpaa";
            ratingInfo.Rating         = "G";
            ratingInfo.SortValue      = 100;
            this.file.Tags.RatingInfo = ratingInfo;
            this.file.Save();

            this.file.Load();
            Assert.AreEqual("mpaa", this.file.Tags.RatingInfo.RatingSource);
            Assert.AreEqual("G", this.file.Tags.RatingInfo.Rating);
            Assert.AreEqual(100, this.file.Tags.RatingInfo.SortValue);
            Assert.AreEqual(string.Empty, this.file.Tags.RatingInfo.RatingAnnotation);

            this.file.Tags.RatingInfo = null;
            this.file.Save();
            this.file.Load();
            Assert.IsNull(this.file.Tags.RatingInfo);
        }
        public async Task <Platform> CreatePlatform(string name,
                                                    PlatformAuthenticationMechanism authMechanism, PlatformIntegrationType platformIntegrationType,
                                                    RatingInfo ratingInfo, int?dataPollIntervalInSeconds, Guid externalPlatformId, string description,
                                                    string logoUrl, string websiteUrl, IAsyncDocumentSession session, bool isInactive = false,
                                                    CancellationToken cancellationToken = default)
        {
            try
            {
                await GetPlatformByExternalId(externalPlatformId, session, cancellationToken);

                throw new PlatformAlreadyExistsException(
                          $"Platform with external id {externalPlatformId} already exists. Name: {name}");
            }
            catch (PlatformDoNotExistException)
            {
                var platform = new Platform(name, externalPlatformId, authMechanism, platformIntegrationType,
                                            ratingInfo, description, logoUrl, websiteUrl, dataPollIntervalInSeconds, isInactive);
                await session.StoreAsync(platform, cancellationToken);

                return(platform);
            }
        }
Esempio n. 12
0
    public void ShowScores()
    {
        RatingInfo info    = new RatingInfo();
        bool       isValid = true;
        int        number  = 0;

        Pair <string, int> cur = ScoreHolder.GetElement(number++);

        while (cur != null)
        {
            info.place = number;
            info.name  = cur.First;
            info.score = cur.Second;

            isValid = SetRating(info);
            if (!isValid)
            {
                break;
            }

            cur = ScoreHolder.GetElement(number++);
        }
    }
Esempio n. 13
0
        public void RatingCreate_UserAlreadyRated_ReturnCorrectError()
        {
            string siteName = "h2g2";
            int siteId = 1;
            string uid = "uid";
            string text = "test comment";
            var siteList = mocks.DynamicMock<ISiteList>();
            var readerCreator = mocks.DynamicMock<IDnaDataReaderCreator>();
            var site = mocks.DynamicMock<ISite>();
            var reader = mocks.DynamicMock<IDnaDataReader>();
            var cacheManager = mocks.DynamicMock<ICacheManager>();
            var callingUser = mocks.DynamicMock<ICallingUser>();
            var ratingForum = new RatingForum { Id = uid, SiteName = siteName };
            var ratingInfo = new RatingInfo { text = text, rating = 0 };

            callingUser.Stub(x => x.IsSecureRequest).Return(true);

            callingUser.Stub(x => x.UserID).Return(1);
            callingUser.Stub(x => x.IsUserA(UserTypes.SuperUser)).Return(false).Constraints(Is.Anything());

            cacheManager.Stub(x => x.GetData("")).Return(null).Constraints(Is.Anything());

            site.Stub(x => x.SiteID).Return(siteId);
            site.Stub(x => x.IsEmergencyClosed).Return(false);
            site.Stub(x => x.IsSiteScheduledClosed(DateTime.Now)).Return(false);

            reader.Stub(x => x.HasRows).Return(true);
            reader.Stub(x => x.Read()).Return(true).Repeat.Once();

            readerCreator.Stub(x => x.CreateDnaDataReader("ratingscreate")).Return(reader);
            var readerUserRating = mocks.DynamicMock<IDnaDataReader>();
            readerUserRating.Stub(x => x.HasRows).Return(true);
            readerUserRating.Stub(x => x.Read()).Return(true);
            readerCreator.Stub(x => x.CreateDnaDataReader("ratingsreadbyforumanduser")).Return(readerUserRating);

            site.Stub(x => x.SiteID).Return(1);
            siteList.Stub(x => x.GetSiteOptionValueString(1, "General", "ComplaintUrl")).Return("http://www.bbc.co.uk/dna/[sitename]/comments/UserComplaintPage?PostID=[postid]&s_start=1");
            siteList.Stub(x => x.GetSite(siteName)).Return(site);
            mocks.ReplayAll();

            var reviews = new Reviews(null, readerCreator, cacheManager, siteList);
            reviews.CallingUser = callingUser;
            try
            {
                reviews.RatingCreate(ratingForum, ratingInfo);
                throw new Exception("No exception thrown");
            }
            catch (ApiException ex)
            {
                Assert.AreEqual(ErrorType.MultipleRatingByUser, ex.type);
            }

            readerCreator.AssertWasNotCalled(x => x.CreateDnaDataReader("ratingscreate"));
        }
Esempio n. 14
0
        public void ShouldWriteRatingInfo()
        {
            RatingInfo ratingInfo = new RatingInfo();
            ratingInfo.RatingSource = "mpaa";
            ratingInfo.Rating = "G";
            ratingInfo.SortValue = 100;
            this.file.Tags.RatingInfo = ratingInfo;
            this.file.Save();

            this.file.Load();
            Assert.AreEqual("mpaa", this.file.Tags.RatingInfo.RatingSource);
            Assert.AreEqual("G", this.file.Tags.RatingInfo.Rating);
            Assert.AreEqual(100, this.file.Tags.RatingInfo.SortValue);
            Assert.AreEqual(string.Empty, this.file.Tags.RatingInfo.RatingAnnotation);

            this.file.Tags.RatingInfo = null;
            this.file.Save();
            this.file.Load();
            Assert.IsNull(this.file.Tags.RatingInfo);
        }
 public RateRestaurant(int restaurantID, RatingInfo rate)
 {
     this.RestaurantID = restaurantID;
     this.Rate = rate;
 }
Esempio n. 16
0
 public RateRestaurant(int restaurantID, RatingInfo rate)
 {
     this.RestaurantID = restaurantID;
     this.Rate         = rate;
 }
Esempio n. 17
0
 public void SetRate(RatingInfo rate)
 {
     repo.SetRate(rate.RestId, rate.Rating);
 }
Esempio n. 18
0
        public void RatingCreate_ProcessPreMod_ReturnCorrectError()
        {
            string siteName = "h2g2";
            int siteId = 1;
            string uid = "uid";
            string text = "test comment";
            var siteList = mocks.DynamicMock<ISiteList>();
            var readerCreator = mocks.DynamicMock<IDnaDataReaderCreator>();
            var site = mocks.DynamicMock<ISite>();
            var reader = mocks.DynamicMock<IDnaDataReader>();
            var cacheManager = mocks.DynamicMock<ICacheManager>();
            var callingUser = mocks.DynamicMock<ICallingUser>();
            var ratingForum = new RatingForum { Id = uid, SiteName = siteName, ModerationServiceGroup= ModerationStatus.ForumStatus.PreMod };
            var ratingInfo = new RatingInfo { text = text, rating = 0 };

            callingUser.Stub(x => x.IsSecureRequest).Return(true);

            callingUser.Stub(x => x.UserID).Return(1);
            callingUser.Stub(x => x.IsUserA(UserTypes.SuperUser)).Return(false).Constraints(Is.Anything());

            cacheManager.Stub(x => x.GetData("")).Return(null).Constraints(Is.Anything());

            site.Stub(x => x.SiteID).Return(siteId);
            site.Stub(x => x.IsEmergencyClosed).Return(false);
            site.Stub(x => x.IsSiteScheduledClosed(DateTime.Now)).Return(false);

            reader.Stub(x => x.HasRows).Return(true);
            reader.Stub(x => x.Read()).Return(true).Repeat.Once();

            readerCreator.Stub(x => x.CreateDnaDataReader("ratingscreate")).Return(reader);
            var readerUserRating = mocks.DynamicMock<IDnaDataReader>();
            readerUserRating.Stub(x => x.HasRows).Return(false);
            readerUserRating.Stub(x => x.Read()).Return(false);
            readerCreator.Stub(x => x.CreateDnaDataReader("ratingsreadbyforumanduser")).Return(readerUserRating);



            siteList.Stub(x => x.GetSiteOptionValueBool(siteId, "Moderation", "ProcessPreMod")).Return(true);
            siteList.Stub(x => x.GetSite(siteName)).Return(site);
            mocks.ReplayAll();

            var reviews = new Reviews(null, readerCreator, cacheManager, siteList);
            reviews.CallingUser = callingUser;
            try
            {
                reviews.RatingCreate(ratingForum, ratingInfo);
                throw new Exception("No exception thrown");
            }
            catch (ApiException ex)
            {
                Assert.AreEqual(ErrorType.InvalidProcessPreModState, ex.type);
            }

            readerCreator.AssertWasNotCalled(x => x.CreateDnaDataReader("ratingscreate"));
        }
Esempio n. 19
0
        public async Task insert(TABLE type, List <string> data)
        {
            print_info("inserting data into database");
            switch (type)
            {
            case TABLE.DRINKS:
                DrinkInfo drink = new DrinkInfo
                {
                    UserId      = data.ElementAt(0),
                    Gin         = data.ElementAt(1),
                    Tonic       = data.ElementAt(2),
                    Garnish     = data.ElementAt(3),
                    Description = data.ElementAt(4),
                    Id          = data.ElementAt(1) + data.ElementAt(2) + data.ElementAt(3)
                };

                var drink_collection = database.GetCollection <DrinkInfo>("drinks");

                if (search(TABLE.DRINKS, drink.Id).Count() > 0)
                {
                    print_error("drink already exists");
                    return;
                }

                print_info("adding drink to database");
                drink_collection.InsertOne(drink);
                break;

            case TABLE.RATING:
                RatingInfo rating = new RatingInfo
                {
                    Id         = ObjectId.GenerateNewId(),
                    UserId     = data.ElementAt(0),
                    DrinkId    = data.ElementAt(1),
                    Rating     = int.Parse(data.ElementAt(2)),
                    Comment    = data.ElementAt(3),
                    Helpfull   = 0,
                    Unhelpfull = 0
                };

                var rating_collection = database.GetCollection <RatingInfo>("ratings");
                var rating_result     = search(TABLE.RATING, rating.UserId);

                foreach (var r in rating_result)
                {
                    var res = (RatingInfo)r;
                    if (res.DrinkId == rating.DrinkId)
                    {
                        print_error("rating for drink by user already exists");
                        return;
                    }
                }

                print_info("adding rating to database");

                rating_collection.InsertOne(rating);
                break;

            case TABLE.USER:
                UserInfo user = new UserInfo
                {
                    Id = data.ElementAt(0)
                };

                var user_collection = database.GetCollection <UserInfo>("users");
                if (search(TABLE.USER, user.Id).Count() > 0)
                {
                    print_error("user already exists");
                    return;
                }

                print_info("adding user to database");
                user_collection.InsertOne(user);
                break;

            default:
                print_error("OBI-WAN");
                break;
            }
        }
Esempio n. 20
0
        public void RatingCreate_NotSecureWithOption_ReturnCorrectError()
        {
            string siteName = "h2g2";
            string uid = "uid";
            var text = "Here is my rating that is not posted securely";
            var siteList = mocks.DynamicMock<ISiteList>();
            var readerCreator = mocks.DynamicMock<IDnaDataReaderCreator>();
            var site = mocks.DynamicMock<ISite>();
            var reader = mocks.DynamicMock<IDnaDataReader>();
            var cacheManager = mocks.DynamicMock<ICacheManager>();
            var callingUser = mocks.DynamicMock<ICallingUser>();
            var ratingForum = new RatingForum { Id = uid, SiteName = siteName };
            var ratingInfo = new RatingInfo { text = text, rating = 0 };

            callingUser.Stub(x => x.UserID).Return(1);
            callingUser.Stub(x => x.IsUserA(UserTypes.SuperUser)).Return(false).Constraints(Is.Anything());

            cacheManager.Stub(x => x.GetData("")).Return(null).Constraints(Is.Anything());

            site.Stub(x => x.IsEmergencyClosed).Return(false);
            site.Stub(x => x.IsSiteScheduledClosed(DateTime.Now)).Return(false);

            reader.Stub(x => x.HasRows).Return(true);
            reader.Stub(x => x.Read()).Return(true).Repeat.Once();

            readerCreator.Stub(x => x.CreateDnaDataReader("ratingscreate")).Return(reader);
            var readerUserRating = mocks.DynamicMock<IDnaDataReader>();
            readerUserRating.Stub(x => x.HasRows).Return(false);
            readerUserRating.Stub(x => x.Read()).Return(false);
            readerCreator.Stub(x => x.CreateDnaDataReader("ratingsreadbyforumanduser")).Return(readerUserRating);
            siteList.Stub(x => x.GetSite(siteName)).Return(site);
            siteList.Stub(x => x.GetSiteOptionValueInt(0, "CommentForum", "EnforceSecurePosting")).Return(1);
            mocks.ReplayAll();

            var reviews = new Reviews(null, readerCreator, cacheManager, siteList);
            reviews.CallingUser = callingUser;
            try
            {
                reviews.RatingCreate(ratingForum, ratingInfo);
                throw new Exception("No exception thrown");
            }
            catch (ApiException ex)
            {
                Assert.AreEqual(ErrorType.NotSecure, ex.type);
            }

            readerCreator.AssertWasNotCalled(x => x.CreateDnaDataReader("ratingscreate"));
        }
Esempio n. 21
0
        public void RatingCreate_AsPreMod_ReturnCorrectError()
        {
            string siteName = "h2g2";
            int siteId = 1;
            string uid = "uid";
            string text = "test text";
            var siteList = mocks.DynamicMock<ISiteList>();
            var readerCreator = mocks.DynamicMock<IDnaDataReaderCreator>();
            var site = mocks.DynamicMock<ISite>();
            var reader = mocks.DynamicMock<IDnaDataReader>();
            var cacheManager = mocks.DynamicMock<ICacheManager>();
            var callingUser = mocks.DynamicMock<ICallingUser>();
            var ratingForum = new RatingForum
                                  {
                                      Id = uid,
                                      SiteName = siteName,
                                      ModerationServiceGroup = ModerationStatus.ForumStatus.PreMod
                                  };
            var ratingInfo = new RatingInfo {text = text, rating = 0};

            callingUser.Stub(x => x.IsSecureRequest).Return(true);

            callingUser.Stub(x => x.UserID).Return(1);
            callingUser.Stub(x => x.IsUserA(UserTypes.SuperUser)).Return(false).Constraints(Is.Anything());

            cacheManager.Stub(x => x.GetData("")).Return(null).Constraints(Is.Anything());

            site.Stub(x => x.SiteID).Return(siteId);
            site.Stub(x => x.IsEmergencyClosed).Return(false);
            site.Stub(x => x.IsSiteScheduledClosed(DateTime.Now)).Return(false);

            reader.Stub(x => x.HasRows).Return(true);
            reader.Stub(x => x.Read()).Return(true).Repeat.Once();

            readerCreator.Stub(x => x.CreateDnaDataReader("ratingscreate")).Return(reader);
            readerCreator.Stub(x => x.CreateDnaDataReader("commentcreate")).Return(reader);

            var readerUserRating = mocks.DynamicMock<IDnaDataReader>();
            readerUserRating.Stub(x => x.HasRows).Return(false);
            readerUserRating.Stub(x => x.Read()).Return(false);
            readerCreator.Stub(x => x.CreateDnaDataReader("ratingsreadbyforumanduser")).Return(readerUserRating);

            siteList.Stub(x => x.GetSite(siteName)).Return(site);
            mocks.ReplayAll();

            var reviews = new Reviews(null, readerCreator, cacheManager, siteList);
            reviews.CallingUser = callingUser;
            RatingInfo comment = reviews.RatingCreate(ratingForum, ratingInfo);

            Assert.IsNotNull(comment);
            readerCreator.AssertWasCalled(x => x.CreateDnaDataReader("commentcreate"));
        }
Esempio n. 22
0
        public void RatingCreate_ValidInput_ReturnCorrectObject()
        {
            string siteName = "h2g2";
            string uid = "uid";
            string text = "test comment";
            var siteList = mocks.DynamicMock<ISiteList>();
            var readerCreator = mocks.DynamicMock<IDnaDataReaderCreator>();
            var site = mocks.DynamicMock<ISite>();
            var reader = mocks.DynamicMock<IDnaDataReader>();
            var cacheManager = mocks.DynamicMock<ICacheManager>();
            var callingUser = mocks.DynamicMock<ICallingUser>();
            var ratingForum = new RatingForum {Id = uid, SiteName = siteName};
            var ratingInfo = new RatingInfo {text = text, rating = 0};

            callingUser.Stub(x => x.IsSecureRequest).Return(true);

            callingUser.Stub(x => x.UserID).Return(1);
            callingUser.Stub(x => x.IsUserA(UserTypes.SuperUser)).Return(false).Constraints(Is.Anything());

            cacheManager.Stub(x => x.GetData("")).Return(null).Constraints(Is.Anything());

            site.Stub(x => x.IsEmergencyClosed).Return(false);
            site.Stub(x => x.IsSiteScheduledClosed(DateTime.Now)).Return(false);

            reader.Stub(x => x.HasRows).Return(true);
            reader.Stub(x => x.Read()).Return(true);
            reader.Stub(x => x.GetInt32NullAsZero("postid")).Return(1);

            readerCreator.Stub(x => x.CreateDnaDataReader("ratingscreate")).Return(reader);
            readerCreator.Stub(x => x.CreateDnaDataReader("commentcreate")).Return(reader);
            var readerUserRating = mocks.DynamicMock<IDnaDataReader>();
            readerUserRating.Stub(x => x.HasRows).Return(false);
            readerUserRating.Stub(x => x.Read()).Return(false);
            readerCreator.Stub(x => x.CreateDnaDataReader("ratingsreadbyforumanduser")).Return(readerUserRating);

            site.Stub(x => x.SiteID).Return(1);
            siteList.Stub(x => x.GetSiteOptionValueString(1, "General", "ComplaintUrl")).Return("http://www.bbc.co.uk/dna/[sitename]/comments/UserComplaintPage?PostID=[postid]&s_start=1");
            siteList.Stub(x => x.GetSite(siteName)).Return(site);
            mocks.ReplayAll();

            var reviews = new Reviews(null, readerCreator, cacheManager, siteList);
            reviews.CallingUser = callingUser;
            RatingInfo comment = reviews.RatingCreate(ratingForum, ratingInfo);

            Assert.IsNotNull(comment);
            readerCreator.AssertWasCalled(x => x.CreateDnaDataReader("commentcreate"));
        }
Esempio n. 23
0
        public static IDictionary <Guid, Tuple <string, string, BlogCommentPolicy, string[], IRatingInfo> > FetchBlogPostExtendedData(this OrganizationServiceContext serviceContext, IEnumerable <Guid> postIds, BlogCommentPolicy defaultCommentPolicy, Guid websiteId)
        {
            if (!postIds.Any())
            {
                return(new Dictionary <Guid, Tuple <string, string, BlogCommentPolicy, string[], IRatingInfo> >());
            }

            var ids = postIds.ToArray();

            var fetchXml = XDocument.Parse(@"
				<fetch mapping=""logical"">
					<entity name=""adx_blogpost"">
						<attribute name=""adx_commentpolicy"" />
						<filter type=""and"">
						</filter>
						<link-entity name=""adx_blog"" from=""adx_blogid"" to=""adx_blogid"" alias=""blog"">
							<attribute name=""adx_commentpolicy"" />
						</link-entity>
						<link-entity link-type=""outer"" name=""contact"" from=""contactid"" to=""adx_authorid"" alias=""author"">
							<attribute name=""contactid"" />
							<attribute name=""fullname"" />
							<attribute name=""firstname"" />
							<attribute name=""lastname"" />
							<attribute name=""emailaddress1"" />
						</link-entity>
						<link-entity link-type=""outer"" name=""adx_blogpost_tag"" from=""adx_blogpostid"" to=""adx_blogpostid"">
							<link-entity link-type=""outer"" name=""adx_tag"" from=""adx_tagid"" to=""adx_tagid"" alias=""tag"">
								<attribute name=""adx_name"" />
								<filter type=""and"">
									<condition attribute=""adx_websiteid"" operator=""eq"" />
								</filter>
							</link-entity>
						</link-entity>
					</entity>
				</fetch>"                );

            var postFilter = fetchXml.XPathSelectElement("//entity[@name='adx_blogpost']/filter");

            if (postFilter == null)
            {
                throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_blogpostid filter condition"));
            }

            postFilter.AddFetchXmlFilterInCondition("adx_blogpostid", ids.Select(id => id.ToString()));

            var websiteConditions = fetchXml.XPathSelectElements("//filter/condition[@attribute='adx_websiteid']");

            foreach (var websiteCondition in websiteConditions)
            {
                websiteCondition.SetAttributeValue("value", websiteId.ToString());
            }

            var fetch       = Fetch.Parse(fetchXml.ToString());
            var contactLink = fetch.Entity.Links.FirstOrDefault(l => l.Name.Equals("contact"));

            if (contactLink != null)
            {
                contactLink.IsUnique = true;
            }

            var response = (serviceContext as IOrganizationService).RetrieveMultiple(fetch);

            var aggregateFilter = fetchXml.Descendants("filter").First();

            aggregateFilter.AddFetchXmlFilterInCondition("adx_blogpostid", ids.Select(id => id.ToString()));
            EntityCollection aggregateResponse = null;

            if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
            {
                XDocument aggregateFetchXml = XDocument.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<entity name=""feedback"">
						<attribute name=""regardingobjectid"" alias=""ratingcount"" aggregate=""countcolumn""/>
						<attribute name=""rating"" alias=""ratingsum"" aggregate=""sum"" />
						<attribute name=""rating"" alias=""value"" groupby=""true"" />
						<filter type=""and"">
							<condition attribute=""statecode"" operator=""eq"" value=""0"" />
							<condition attribute=""rating"" operator=""not-null"" />
						</filter>
						<link-entity name=""adx_blogpost"" from=""adx_blogpostid"" to=""regardingobjectid"">
							<attribute name=""adx_blogpostid"" alias=""postid"" groupby=""true"" />
							<filter type=""and"" />
						</link-entity>
					</entity>
				</fetch>"                );

                aggregateResponse = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(aggregateFetchXml.ToString()));
            }
            return(ids.ToDictionary(id => id, id =>
            {
                var entities = response.Entities.Where(e => e.Id == id).ToArray();

                if (!entities.Any())
                {
                    return new Tuple <string, string, BlogCommentPolicy, string[], IRatingInfo>(null, null, defaultCommentPolicy, new string[] {}, null);
                }

                var entity = entities.First();

                var authorName = Localization.LocalizeFullName(entity.GetAttributeAliasedValue <string>("author.firstname"), entity.GetAttributeAliasedValue <string>("author.lastname"));
                var authorEmail = entity.GetAttributeAliasedValue <string>("author.emailaddress1");

                object postCommentPolicyAttributeValue;
                var postCommentPolicy = entity.Attributes.TryGetValue("adx_commentpolicy", out postCommentPolicyAttributeValue) && (postCommentPolicyAttributeValue is OptionSetValue)
                                        ? (BlogPostCommentPolicy)Enum.ToObject(typeof(BlogPostCommentPolicy), ((OptionSetValue)postCommentPolicyAttributeValue).Value)
                                        : BlogPostCommentPolicy.Inherit;

                var blogCommentPolicyOption = entity.GetAttributeAliasedValue <OptionSetValue>("blog.adx_commentpolicy");
                var blogCommentPolicy = blogCommentPolicyOption == null
                                        ? defaultCommentPolicy
                                        : (BlogCommentPolicy)Enum.ToObject(typeof(BlogCommentPolicy), blogCommentPolicyOption.Value);

                var commentPolicy = postCommentPolicy == BlogPostCommentPolicy.Inherit
                                        ? blogCommentPolicy
                                        : (BlogCommentPolicy)Enum.ToObject(typeof(BlogCommentPolicy), (int)postCommentPolicy);

                var tags = entities
                           .Select(e => e.GetAttributeAliasedValue <string>("tag.adx_name"))
                           .Where(tagName => !string.IsNullOrWhiteSpace(tagName))
                           .ToArray();

                int ratingCount = 0;
                int ratingSum = 0;
                double averageRating = 0;
                int yesCount = 0;
                int noCount = 0;

                if (aggregateResponse != null)
                {
                    var aggregateResults = aggregateResponse.Entities
                                           .Where(e => e.GetAttributeAliasedValue <Guid?>("postid") == id);

                    var aggregateYesResult = aggregateResponse.Entities
                                             .Where(e => e.GetAttributeAliasedValue <Guid?>("postid") == id)
                                             .FirstOrDefault(e => e.GetAttributeAliasedValue <int?>("value") == 1);

                    var aggregateNoResult = aggregateResponse.Entities
                                            .Where(e => e.GetAttributeAliasedValue <Guid?>("postid") == id)
                                            .FirstOrDefault(e => e.GetAttributeAliasedValue <int?>("value") == 0);

                    yesCount = (aggregateYesResult != null) ? aggregateYesResult.GetAttributeAliasedValue <int?>("ratingcount") ?? 0 : 0;

                    noCount = (aggregateNoResult != null) ? aggregateNoResult.GetAttributeAliasedValue <int?>("ratingcount") ?? 0 : 0;

                    foreach (var aggregateResult in aggregateResults)
                    {
                        ratingCount = ratingCount + aggregateResult.GetAttributeAliasedValue <int?>("ratingcount") ?? 0;
                        ratingSum = ratingSum + aggregateResult.GetAttributeAliasedValue <int?>("ratingsum") ?? 0;
                    }

                    if (ratingCount == 0)
                    {
                        averageRating = 0;
                    }
                    else
                    {
                        averageRating = ratingSum / (double)ratingCount;
                    }
                }

                var ratingInfo = new RatingInfo(yesCount, noCount, averageRating, ratingCount, ratingSum);

                return new Tuple <string, string, BlogCommentPolicy, string[], IRatingInfo>(authorName, authorEmail, commentPolicy, tags, ratingInfo);
            }));
        }
Esempio n. 24
0
        public static IDictionary <Guid, Tuple <string, string, string, IRatingInfo> > FetchBlogPostCommentExtendedData(this OrganizationServiceContext serviceContext, IEnumerable <Guid> commentIds)
        {
            if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
            {
                return(new Dictionary <Guid, Tuple <string, string, string, IRatingInfo> >());
            }
            if (!commentIds.Any())
            {
                return(new Dictionary <Guid, Tuple <string, string, string, IRatingInfo> >());
            }

            var ids = commentIds.ToArray();

            XDocument fetchXml = XDocument.Parse(@"
				<fetch mapping=""logical"">
					<entity name=""feedback"">
						<filter type=""and"">
						</filter>
						<link-entity name=""contact"" from=""contactid"" to=""createdbycontact"" alias=""author"">
							<attribute name=""contactid"" />
							<attribute name=""fullname"" />
							<attribute name=""firstname"" />
							<attribute name=""lastname"" />
							<attribute name=""emailaddress1"" />
							<attribute name=""websiteurl"" />
						</link-entity>
					</entity>
				</fetch>"                );

            var filter = fetchXml.Descendants("filter").First();

            filter.AddFetchXmlFilterInCondition("feedbackid", ids.Select(id => id.ToString()));

            var response = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(fetchXml.ToString()));

            XDocument aggregateFetchXml = XDocument.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<entity name=""feedback"">
						<attribute name=""regardingobjectid"" alias=""ratingcount"" aggregate=""countcolumn""/>
						<attribute name=""rating"" alias=""ratingsum"" aggregate=""sum"" />
						<attribute name=""rating"" alias=""value"" groupby=""true"" />
						<link-entity name=""feedback"" from=""feedbackid"" to=""regardingobjectid"">
							<attribute name=""feedbackid"" alias=""commentid"" groupby=""true"" />
							<filter type=""and"" />
						</link-entity>
					</entity>
				</fetch>"                );

            var aggregateFilter = fetchXml.Descendants("filter").First();

            aggregateFilter.AddFetchXmlFilterInCondition("feedbackid", ids.Select(id => id.ToString()));

            var aggregateResponse = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(aggregateFetchXml.ToString()));

            return(ids.ToDictionary(id => id, id =>
            {
                var entity = response.Entities.FirstOrDefault(e => e.Id == id);

                if (entity == null)
                {
                    return new Tuple <string, string, string, IRatingInfo>(null, null, null, null);
                }

                var authorName = Localization.LocalizeFullName(entity.GetAttributeAliasedValue <string>("author.firstname"), entity.GetAttributeAliasedValue <string>("author.lastname"));
                var authorUrl = entity.GetAttributeAliasedValue <string>("author.websiteurl");
                var authorEmail = entity.GetAttributeAliasedValue <string>("author.emailaddress1");

                var aggregateResults = aggregateResponse.Entities
                                       .Where(e => e.GetAttributeAliasedValue <Guid?>("commentid") == id);

                var aggregateYesResult = aggregateResponse.Entities
                                         .Where(e => e.GetAttributeAliasedValue <Guid?>("commentid") == id)
                                         .FirstOrDefault(e => e.GetAttributeAliasedValue <int?>("value") == 1);

                var aggregateNoResult = aggregateResponse.Entities
                                        .Where(e => e.GetAttributeAliasedValue <Guid?>("commentid") == id)
                                        .FirstOrDefault(e => e.GetAttributeAliasedValue <int?>("value") == 0);

                var yesCount = (aggregateYesResult != null) ? aggregateYesResult.GetAttributeAliasedValue <int?>("ratingcount") ?? 0 : 0;
                var noCount = (aggregateNoResult != null) ? aggregateNoResult.GetAttributeAliasedValue <int?>("ratingcount") ?? 0 : 0;

                var ratingCount = 0;
                var ratingSum = 0;

                foreach (var aggregateResult in aggregateResults)
                {
                    ratingCount = ratingCount + aggregateResult.GetAttributeAliasedValue <int?>("ratingcount") ?? 0;
                    ratingSum = ratingSum + aggregateResult.GetAttributeAliasedValue <int?>("ratingsum") ?? 0;
                }

                double averageRating;

                if (ratingCount == 0)
                {
                    averageRating = 0;
                }
                else
                {
                    averageRating = ratingSum / (double)ratingCount;
                }

                var ratingInfo = new RatingInfo(yesCount, noCount, averageRating, ratingCount, ratingSum);

                return new Tuple <string, string, string, IRatingInfo>(authorName, authorUrl, authorEmail, ratingInfo);
            }));
        }