コード例 #1
0
        public CommentsResponse GetCommentsByChart(int smartChartId)
        {
            var response = new CommentsResponse();

            try {
                var commentRepository = new ChartCommentRepository();
                var userRepository    = new UserProfileRepository();
                var comments          = commentRepository.Query().Where(x => x.IdSmartChart == smartChartId && x.IsActive == true).OrderBy(x => x.DatePosted).Take(25).ToList();
                foreach (var comment in comments)
                {
                    int userId = Convert.ToInt32(comment.IdUser);
                    response.Comments.Add(new ChartCommentDto()
                    {
                        Message    = comment.Message,
                        DatePosted = comment.DatePosted,
                        UserName   = userRepository.Query().FirstOrDefault(x => x.UserId == userId).UserName,
                        IdComment  = comment.IdComment,
                        IdUser     = userId.ToString()
                    });
                }

                // CHECK ROLE - IsAppAdmin
                commentRepository.Dispose();
                response.Acknowledgment = true;
                response.Message        = "Success";
            }
            catch (Exception ex) {
                _logger.Error("Error Getting the comments for chartid: " + smartChartId + ". With the exception: " + ex.Message);
                response.Acknowledgment = false;
                response.Message        = "Error: " + ex.Message;
            }
            return(response);
        }
コード例 #2
0
        public CommentsResponse FilterComment(int instanceId,
                                              FilterCommentViewModel filter = null)
        {
            var response = new CommentsResponse
            {
                CommentList = new List <CommentViewModel>()
            };

            filter = filter ?? new FilterCommentViewModel();
            var request = new CommentsRequest
            {
                InstanceId           = instanceId,
                CommentTypeCode      = filter.CommentTypeCode,
                DateFrom             = filter.DateFrom,
                DateTo               = filter.DateTo,
                OrderDesc            = filter.OrderBy,
                OrganizationalUnitId = filter.OrganizationalUnitId,
                TopicCommentId       = filter.TopicCommentId,
                UserName             = filter.UserName,
                MyComments           = filter.MyComments,
                IsCheckPublic        = filter.IsCheckPublic,
                IsOpcAgreement       = filter.IsOpcAgreement
            };

            var filterResponse = _commentService.FilterComments(request);

            if (filterResponse.IsValid)
            {
                response = filterResponse;
            }

            return(response);
        }
コード例 #3
0
        public async Task <ActionResult <Comments> > GetComments(Guid id)
        {
            var comments = await _context.Comments.Include(x => x.Account)
                           .Include(x => x.Post)
                           .FirstOrDefaultAsync(x => x.Id == id);

            var accountResponse = new AccountResponse {
                Id = comments.Account.Id, Nome = comments.Account.Nome
            };
            var postViewModel = new PostViewModel {
                Id = comments.Post.Id
            };
            var commentResponse = new CommentsResponse {
                Id      = comments.Id,
                Account = accountResponse,
                Content = comments.Content,
                Post    = postViewModel
            };

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

            return(comments);
        }
コード例 #4
0
ファイル: GroupsService.cs プロジェクト: Makzz90/VKClient_re
        public void GetTopicComments(long gid, long tid, int offset, int count, Action <BackendResult <CommentsInfo, ResultCode> > callback)
        {
            Dictionary <string, string> dictionary = new Dictionary <string, string>();
            string index1 = "group_id";
            string str1   = gid.ToString();

            dictionary[index1] = str1;
            string index2 = "topic_id";
            string str2   = tid.ToString();

            dictionary[index2] = str2;
            string index3 = "offset";
            string str3   = offset.ToString();

            dictionary[index3] = str3;
            string index4 = "count";
            string str4   = count.ToString();

            dictionary[index4] = str4;
            string index5 = "extended";
            string str5   = "1";

            dictionary[index5] = str5;
            string index6 = "need_likes";
            string str6   = "1";

            dictionary[index6] = str6;
            VKRequestsDispatcher.Execute <CommentsInfo>(string.Format("var cm = API.board.getComments({{\"group_id\":{0}, \"topic_id\":{1}, \"offset\":{2}, \"count\":{3}, \"extended\":1, \"need_likes\":1, \"allow_group_comments\":1  }});\r\nvar g = API.groups.getById({{\"group_id\":{0}}})[0];\r\nreturn {{CommentsResponse:cm, Group:g}};", gid, tid, offset, count), callback, (Func <string, CommentsInfo>)(jsonStr =>
            {
                GroupsService.TopicCommentsResponse response = JsonConvert.DeserializeObject <GenericRoot <GroupsService.TopicCommentsResponse> >(jsonStr).response;
                CommentsResponse commentsResponse            = response.CommentsResponse;
                GroupsService.Current.AddCachedGroup(response.Group);
                return(new CommentsInfo()
                {
                    comments = commentsResponse.items,
                    poll = commentsResponse.poll,
                    profiles = commentsResponse.profiles,
                    groups = commentsResponse.groups,
                    TotalCommentsCount = commentsResponse.count
                });
            }), false, true, new CancellationToken?());
        }
コード例 #5
0
        public CommentsResponse AddChartComment(ChartCommentDto comment)
        {
            var response = new CommentsResponse();

            try
            {
                var commentRepository = new ChartCommentRepository();
                var userRepository    = new UserProfileRepository();
                var newComment        = new ChartComment
                {
                    IdUser       = comment.IdUser,
                    DatePosted   = DateTime.Now,
                    Message      = comment.Message,
                    IdSmartChart = comment.IdSmartChart,
                    IsActive     = true
                };
                commentRepository.Add(newComment);
                commentRepository.SaveChanges();
                int userId = Convert.ToInt32(comment.IdUser);
                response.Comments.Add(new ChartCommentDto()
                {
                    Message    = newComment.Message,
                    DatePosted = newComment.DatePosted,
                    UserName   = userRepository.Query().FirstOrDefault(x => x.UserId == userId).UserName,
                    IdComment  = newComment.IdComment,
                    IdUser     = userId.ToString()
                });
                commentRepository.Dispose();
                response.Acknowledgment = true;
                response.Message        = "Success";
            }
            catch (Exception ex)
            {
                _logger.Error("Error adding comment. With the exception: " + ex.Message);
                response.Acknowledgment = false;
                response.Message        = "Error: " + ex.Message;
            }

            return(response);
        }
コード例 #6
0
ファイル: VK.cs プロジェクト: vasichmen/turizm
        /// <summary>
        /// Обновление БД комментариев
        /// </summary>
        /// <param name="database"></param>
        /// <param name="options"></param>
        public void UpdateDB(CommentDatabase database, Options options, Label labelProgress)
        {
            /*
             * 1. Добавить недостающие обсуждения
             * 2. Пройтись по всем обсуждениям и добавить недостающие комментарии
             *      а. проверить последний добавленный комментарий (по дате написания комментария) (MAX date WHERE topic_id == t.TopicID)
             *      б. загрузить с сайта все коменты этого обсуждения, начиная с последнего добавленного (по частям)
             *      в. записать всё в БД
             */
            List <Topic> topics = database.ParseTopicLinks(options.Topics);

            database.LoadTopics(topics);

            try
            {
                for (int i = 0; i < topics.Count; i++)
                {
                    Topic            t         = topics[i]; //Текущее обсуждение
                    Comment          last_comm = database.GetLastComment(t);
                    CommentsResponse response  = GetCommentsFrom(t, last_comm, (perc) =>
                    {
                        string status      = "Обработка обсуждения " + (i + 1) + "/" + topics.Count + ", завершено " + perc.ToString("0.0") + "%";
                        labelProgress.Text = status;
                        Application.DoEvents();
                    });

                    labelProgress.Text = "Обработка обсуждения " + (i + 1) + "/" + topics.Count + ", обработка результатов"; Application.DoEvents();
                    database.AddUsers(response.Users);

                    List <Comment> filtered_comments = prefilter.Prefilter(response.Comments);
                    database.AddComments(filtered_comments);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Возникла ошибка во время загрузки комментариев", "Загрузка комментариев", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }
コード例 #7
0
        public CommentsResponse DeactivateCommentsByChartId(int userId, int idComment, string[] appRoles)
        {
            var response   = new CommentsResponse();
            var isAppAdmin = new List <string>(appRoles).Exists(x => x == "Administrator");

            try
            {
                var commentRepository = new ChartCommentRepository();
                var userRepository    = new UserProfileRepository();
                var userXSubscription = new UsersXSubscriptionRepository();

                var comment    = commentRepository.Query().FirstOrDefault(x => x.IdComment == idComment);
                var isSubAdmin = userXSubscription.Query().Any(x => x.IdSubscriptionRoleTypes == 1 && x.idSubscription == comment.SmartChart.SmartReport.ServiceDelivery.ServiceSubscription.idServiceSubscription && x.idUser == userId);
                if (comment.IdUser == userId.ToString() || isAppAdmin || isSubAdmin)
                {
                    comment.IsActive = false;
                    commentRepository.SaveChanges();
                    commentRepository.Dispose();
                    response.Acknowledgment = true;
                    response.Message        = "Success";
                }
                else
                {
                    _logger.Error("User " + userId + " does not have the right roles to delete this comment " + idComment + " date:" + DateTime.Now.ToString());
                    response.Acknowledgment = false;
                    response.Message        = "User " + userId + " does not have the right roles to delete this comment " + idComment + " date:" + DateTime.Now.ToString();
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error Getting the comment " + idComment + ". With the exception: " + ex.Message);
                response.Acknowledgment = false;
                response.Message        = "Error: " + ex.Message;
            }
            return(response);
        }
コード例 #8
0
ファイル: VK.cs プロジェクト: vasichmen/turizm
        /// <summary>
        /// Получить все комментарии в заданном обсуждении, начиная с заданного комментария
        /// https://vk.com/dev/board.getComments
        /// </summary>
        /// <param name="t">обсуждение</param>
        /// <param name="last_comm">комментарий, с которого надо начать (не включая его)</param>
        /// <returns></returns>
        private CommentsResponse GetCommentsFrom(Topic t, Comment last_comm, Action <double> callback)
        {
            if (t == null)
            {
                throw new ArgumentException("Нельзя найти комментарии неопределенного обсуждения");
            }

            string start_comment_id = "";

            if (last_comm == null)
            {
                start_comment_id = "";
            }
            else
            {
                start_comment_id = "&start_comment_id=" + last_comm.CommentID.ToString();
            }

            CommentsResponse res = new CommentsResponse();

            string url = string.Format("https://api.vk.com/method/board.getComments?group_id={0}&topic_id={1}&need_likes=1{2}&count={3}&extended=1&v=5.52&access_token={4}",
                                       t.GroupID,
                                       t.TopicID,
                                       start_comment_id,
                                       100, //Запрашиваем по 100 комментариев
                                       options.AccessToken);
            JToken json = this.GetJson(url);

            //Добавление комментариев
            JToken resp = json["response"];

            if (resp == null)
            {
                MessageBox.Show(((JObject)json).ToString(Newtonsoft.Json.Formatting.Indented), "Загрузка комментариев", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                throw new Exception("");
            }

            JToken items = resp["items"];

            foreach (JToken item in items)
            {
                long     comment_id  = long.Parse(item["id"].ToString());
                long     from_id     = long.Parse(item["from_id"].ToString());
                long     date        = long.Parse(item["date"].ToString());
                string   text        = item["text"].ToString();
                int      likes       = int.Parse(item["likes"]["count"].ToString());
                DateTime parsed_date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(date);
                res.Add(new Comment()
                {
                    CommentID = comment_id, Likes = likes, Text = text, TopicID = t.TopicID, UserID = from_id, Date = parsed_date
                });
            }

            //Добавление пользователей
            JToken profiles = json["response"]["profiles"];

            foreach (JToken profile in profiles)
            {
                long   id    = long.Parse(profile["id"].ToString());
                string fname = profile["first_name"].ToString();
                string lname = profile["last_name"].ToString();
                res.Add(new User()
                {
                    FirstName = fname, LastName = lname, UserID = id
                });
            }

            //Общее количество комментариев в этом обсуждении
            int total = int.Parse(json["response"]["count"].ToString());

            //Сдвиг на сколько комментариев уже передвинулись в этом обсуждении
            int offset = 0;

            if (json["response"]["real_offset"] == null)
            {
                offset = 0;
            }
            else
            {
                offset = int.Parse(json["response"]["real_offset"].ToString());
            }

            //Вывод прогресса
            callback.Invoke((((double)offset / (double)total) * 100d));
            Application.DoEvents();

            //Рекурсивно добавляем остальные комментарии
            if (total - offset > res.CountComents)
            {
                res.Add(GetCommentsFrom(t, res.Comments[res.CountComents - 1], callback));
            }

            //Если был задан стартовый элемент, то надо удалить, а то он два раза добавляется
            //да, ненаучно, но что поделать)
            if (last_comm != null)
            {
                res.RemoveCommentAt(0);
            }

            return(res);
        }