Пример #1
0
        public ActionResult Create(int id, CommentViewModel comment)
        {
            if (this.CurrentUserCommentedInLastMinutes())
            {
                return this.JsonError(string.Format("You can comment every {0} minute", MinutesBetweenComments));
            }

            if (ModelState.IsValid)
            {
                var newComment = new PostComment
                {
                    Content = comment.Content,
                    BlogPostId = id,
                    User = this.currentUser.Get()
                };

                this.commentsData.Add(newComment);
                this.commentsData.SaveChanges();

                comment.User = this.currentUser.Get().UserName;
                comment.CommentedOn = DateTime.Now;

                return this.PartialView("_CommentDetail", comment);
            }
            else
            {
                return this.JsonError("Content is required");
            }
        }
        private PostCommentDetailViewModel PreparePostCommentDetailViewModel(PostComment comment)
        {
            PostCommentDetailViewModel result = Mapper.Map <PostCommentDetailViewModel>(comment);

            result.CreateDateString = result.CreateDate.ToString("dd/MM/yyyy HH:mm:ss");

            return(result);
        }
        public ActionResult DeleteConfirmed(int id)
        {
            PostComment postComment = db.PostComments.Find(id);

            db.PostComments.Remove(postComment);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Пример #4
0
        public PostComment GetPostComment(ISession session)
        {
            PostComment ei = (Id != 0) ? (PostComment)session.Load(typeof(PostComment), Id) : new PostComment();

            ei.Comment = (Comment)session.Load(typeof(Comment), CommentId);
            ei.Post    = (Post)session.Load(typeof(Post), PostId);
            return(ei);
        }
Пример #5
0
        public PostComment Create()
        {
            var postComment = new PostComment {
                ID = Guid.NewGuid().ToString(), Author = "", Title = "", Body = ""
            };

            return(postComment);
        }
Пример #6
0
 public ActionResult CreateComment([Bind(Include = "PostID,PostCommentContent,UserName")] PostComment pC)
 {
     pC.Date = DateTime.Today;
     db.PostComments.Add(pC);
     db.SaveChanges();
     Session["PostCommentContent"] = null;
     return(Redirect("../Posts/Details/" + pC.PostID));
 }
Пример #7
0
        public ActionResult DeleteConfirmed(int id)
        {
            PostComment postcomment = this.commentsData.GetById(id);

            this.commentsData.Delete(postcomment);
            this.commentsData.SaveChanges();
            return(this.RedirectToAction("Index"));
        }
Пример #8
0
        public void SendMail(PostComment pc, ContentPage page)
        {
            HttpRequest request = HttpContext.Current.Request;

            if (this.Settings.NotifyEditors || !String.IsNullOrEmpty(this.Settings.DirectEmailKeyName))
            {
                List <string> emails = new List <string>();

                if (this.Settings.NotifyEditors && page != null)
                {
                    emails.Add(page.CreateUser.Email);

                    if (page.EditUser.UserId != page.CreateUser.UserId)
                    {
                        emails.Add(page.EditUser.Email);
                    }

                    if (page.CreditUserId.HasValue)
                    {
                        emails.Add(page.CreditUser.Email);
                    }
                }

                if (!String.IsNullOrEmpty(this.Settings.DirectEmailKeyName))
                {
                    emails.Add(ConfigurationManager.AppSettings[this.Settings.DirectEmailKeyName].ToString());
                }

                string strHTTPHost = String.Empty;
                try { strHTTPHost = request.ServerVariables["HTTP_HOST"].ToString().Trim(); } catch { strHTTPHost = String.Empty; }

                string hostName = strHTTPHost.ToLowerInvariant();

                string strHTTPPrefix = "http://";
                try {
                    strHTTPPrefix = request.ServerVariables["SERVER_PORT_SECURE"] == "1" ? "https://" : "http://";
                } catch { strHTTPPrefix = "http://"; }

                strHTTPHost = String.Format("{0}{1}", strHTTPPrefix, strHTTPHost).ToLowerInvariant();

                string mailSubject = String.Format("Comment Form From {0}", hostName);

                string sBody = "Name:   " + pc.CommenterName
                               + "\r\nEmail:   " + pc.CommenterEmail
                               + "\r\nURL:   " + pc.CommenterURL
                               + "\r\n-----------------"
                               + "\r\nComment:\r\n" + HttpUtility.HtmlEncode(pc.PostCommentText)
                               + "\r\n=================\r\n"
                               + "\r\nIP:   " + pc.CommenterIP
                               + "\r\nSite URL:   " + String.Format("{0}{1}", strHTTPHost, page.FileName)
                               + "\r\nSite Time:   " + SiteData.CurrentSite.Now.ToString()
                               + "\r\nUTC Time:   " + DateTime.UtcNow.ToString();

                string sEmail = String.Join(";", emails);

                EmailHelper.SendMail(null, sEmail, mailSubject, sBody, false);
            }
        }
        public void DeleteComment(int id)
        {
            var comment = new PostComment()
            {
                Id = id
            };

            _ctx.Entry(comment).State = EntityState.Deleted;
        }
Пример #10
0
        public ActionResult CommentOnCommentPartial(PostComment comment /*Guid? id*/)
        {
            if (comment == null)
            {
                return(Content(""));
            }

            return(PartialView("CommentOnComment", new OxiteViewModelPartial <PostComment>(new OxiteViewModel(), comment)));
        }
        public ActionResult edit(Int32 id = 0, string returnUrl = "/admin_comments")
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get query parameters
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Get the signed in administrator
            Administrator administrator = Administrator.GetSignedInAdministrator();

            // Get the comment
            PostComment comment = PostComment.GetOneById(id);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (administrator != null && administrator.admin_role == "Author" && 
                (comment == null || comment.administrator_id == administrator.id))
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Get the default admin language
            Int32 adminLanguageId = currentDomain.back_end_language;

            // Add data to the view
            ViewBag.TranslatedTexts = StaticText.GetAll(adminLanguageId, "id", "ASC");
            ViewBag.PostComment = comment;
            ViewBag.ReturnUrl = returnUrl;

            // Return the user to the index page if the comment does not exist
            if (ViewBag.PostComment == null)
            {
                // Return the user to the index page
                return Redirect(returnUrl);
            }

            // Return the edit view
            return View("edit");

        } // End of the edit method
Пример #12
0
 public async Task AddComment(PostComment postComment)
 {
     if (postComment == null || postComment.PostId == Guid.Empty)
     {
         throw new ArgumentNullException(nameof(postComment));
     }
     _appDbContext.PostComments.Add(postComment);
     await _appDbContext.SaveAsync();
 }
Пример #13
0
        public async Task DeleteAsync(PostComment parameters)
        {
            var UserComment = Uow.Repository <PostComment>().FindByKey(parameters.PostCommentId);
            await Uow.RegisterDeletedAsync(UserComment);

            await Uow.CommitAsync();

            // throw new NotImplementedException();
        }
        public ActionResult ApprovePostComment(PostComment model)
        {
            var userId = User.Identity.GetUserId();

            model.CommentStatus = "approved";
            _context.SaveChanges();

            return(new EmptyResult());
        }
Пример #15
0
        private void invalidateCachedCommentDependencies(PostComment comment)
        {
            if (comment.Parent != null)
            {
                cache.InvalidateItem(new PostComment(comment.Parent.ID));
            }

            cache.InvalidateItem(new Post(comment.Post.ID));
        }
Пример #16
0
 public PostCommentDto(PostComment c, IUserBasicDetail p)
 {
     ID    = c.ID.ToString("N");
     By    = p.DisplayName;
     ByID  = c.UserID.ToString("N");
     ByPic = p.Avatar;
     Msg   = c.Message;
     Utc   = c.Utc.ToEpochTimeString();
 }
Пример #17
0
        public JsonResult AddComment(int id, string content)
        {
            string message = string.Empty;

            PostComment _postComment = new PostComment();

            string _loginUser = User.Identity.Name.ToString();

            User _CurrUser = db.Users.Where(x => x.UserName == _loginUser).FirstOrDefault();

            if (!String.IsNullOrEmpty(content))
            {
                int    _postId             = id;
                string _postCommentContent = content;

                Post _post = db.Posts.Where(x => x.PostId == _postId).FirstOrDefault();

                if (_post != null)
                {
                    _post.TotalComments += 1;

                    _postComment.Post    = _post;
                    _postComment.PostId  = _postId;
                    _postComment.Content = _postCommentContent;
                    //_postComment.CreatedBy = _loginUser;
                    _postComment.CreatedDate = DateTime.Now;
                    //_postComment.PerantFlagId = 1;

                    _postComment.User = _CurrUser;
                }

                try
                {
                    //post counter ++
                    db.Posts.Attach(_post);
                    db.Entry(_post).State = EntityState.Modified;

                    db.PostComments.Add(_postComment);
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
            }
            else
            {
                message = "error!";
            }

            return(Json(new
            {
                Html = this.RenderPartialView("_PostComment", _postComment),
                Message = message
            }, JsonRequestBehavior.AllowGet));
        }
        public ActionResult delete(Int32 id = 0, string returnUrl = "/admin_comments")
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get query parameters
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Get the signed in administrator
            Administrator administrator = Administrator.GetSignedInAdministrator();

            // Get the comment
            PostComment comment = PostComment.GetOneById(id);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (administrator != null && administrator.admin_role == "Author" && 
                (comment == null || comment.administrator_id == administrator.id))
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Create an error code variable
            Int32 errorCode = 0;

            // Delete the comment post and all the connected posts (CASCADE)
            errorCode = PostComment.DeleteOnId(id);

            // Check if there is an error
            if (errorCode != 0)
            {
                ViewBag.AdminErrorCode = errorCode;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }

            // Redirect the user to the list
            return Redirect(returnUrl);

        } // End of the delete method
Пример #19
0
        ///////////////////////////////////////////////////// profile
        //reply
        /////////////////////////////////////////////////////
        public async Task AddReply(PostComment postcomment, string stockCurrent, int currentUserId, string userName, string avataImageUrl, long postid)
        {
            #region format message
            string messagedefault = "";
            messagedefault = postcomment.Message;
            List <string> listMessege       = postcomment.Message.Split(' ').ToList();
            string        messageFromatHTML = "";
            foreach (var item in listMessege)
            {
                if (item.Contains("$") || item.Contains("@"))
                {
                    messageFromatHTML += "<b>" + item + "</b>" + " ";
                }
                else if (item.Contains("http") || item.Contains("www."))
                {
                    messageFromatHTML += "<a target='_blank' href='" + item + "'>[LINK]</a>" + " ";
                }
                else
                {
                    messageFromatHTML += item + " ";
                }
            }

            postcomment.Message    = messageFromatHTML;
            postcomment.PostedDate = DateTime.Now;
            postcomment.PostedBy   = postid;
            postcomment.CommentBy  = currentUserId;
            #endregion

            var listStock = new List <string>();
            listStock.Add(stockCurrent.ToUpper());
            #region explan this passing messege to stockcode and username list

            //List<string> listMessegeSplit = messagedefault.Split(' ').ToList().FindAll(p => p.Contains("$") || p.Contains("@"));

            #endregion

            using (testEntities db = new testEntities())
            {
                db.PostComments.Add(postcomment);
                await db.SaveChangesAsync();

                var ret = new
                {
                    ReplyMessage = postcomment.Message,
                    //PostedBy = post.PostedBy,
                    ReplyByName   = userName,
                    ReplyByAvatar = "/" + avataImageUrl.Replace("amp;", ""),
                    ReplyDate     = postcomment.PostedDate,
                    ReplyId       = postcomment.PostCommentsId
                };
                await Clients.Client(Context.ConnectionId).addReply(ret);

                await Clients.OthersInGroups(listStock).newReplyNoti(1, postid);
            }
        }
        /// <summary>
        /// Deletes a comment from the database
        /// </summary>
        /// <param name="commentId">The Id of the comment to be deleted</param>
        /// <returns>Nothing</returns>
        public async Task Delete(int commentId)
        {
            await DeleteAllLikes(commentId);
            await DeletePostToCommentEntities(commentId);

            PostComment commentToBeDeleted = await _context.PostComments.FindAsync(commentId);

            _context.Entry(commentToBeDeleted).State = EntityState.Deleted;
            await _context.SaveChangesAsync();
        }
Пример #21
0
 public CommentDTO(PostComment comment, List <CommentDTO> replies)
 {
     Id         = comment.Id;
     PostedDate = comment.PostedDate;
     Content    = comment.Content;
     Author     = comment.Author;
     Parents    = comment.Parents;
     PostId     = comment.PostId;
     Replies    = replies;
 }
 public ActionResult Edit([Bind(Include = "ID,Text,CommentDate,ProfileID,PostID")] PostComment postComment)
 {
     if (ModelState.IsValid)
     {
         db.Entry(postComment).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(postComment));
 }
Пример #23
0
        private ActionResult ChangeCommentStatus(int id, bool approved)
        {
            PostComment comment = db.PostComments.Single(x => x.Id == id);

            comment.IsApproved  = approved;
            comment.ModeratedBy = db.Users.Single(x => x.UserName == User.Identity.Name);
            db.SaveChanges();

            return(Json(true));
        }
        public IActionResult Put(int id, PostComment pc)
        {
            if (id != pc.Id)
            {
                return(BadRequest());
            }

            _postCommentRepository.Update(pc);
            return(NoContent());
        }
Пример #25
0
		public void AddComment(PostComment comment)
		{
			var commentAdding = new CommentAddingEventArgs(this, comment);
			CommentAdding.Raise(commentAdding);
			if (commentAdding.Cancel)
				return;
			postRepository.SaveComment(comment);
			var commentAdded = new CommentAddedEventArgs(this, comment);
			CommentAdded.Raise(commentAdded);
		}
Пример #26
0
        public IActionResult CommentOnPost(PostComment p, Guid postID, Guid parentID)
        {
            Guid ID = Guid.NewGuid();
            // call commentcommandhandler, pass the comment as a model, and will get it sorted.
            Comment temp = new Comment(ID, parentID, postID, p.theReply, new User(), null);

            CommentCommandHandler.AddNewComment(temp);

            return(RedirectToAction("commentDisplay", "Post", new { ID = postID }));
        }
Пример #27
0
 public void Can_insert_post_comment()
 {
     var postComment = new PostComment();
     postService.Expect(x => x.GetPostById(blog, 1))
         .Return(new Post {FriendlyTitle = "m"});
     var actionResult = controller.AddComment(1, postComment);
     Assert.That(((ViewResult) actionResult).ViewName == "Read");
     Assert.That(actionResult, Is.Not.Null);
     postService.AssertWasCalled(x => x.AddComment(postComment));
 }
Пример #28
0
 public CommentResponse(PostComment entity)
 {
     Id             = entity.Id;
     Content        = entity.Content;
     PostId         = entity.PostId;
     CommentId      = entity.ParentPostCommentId;
     CreatedBy      = entity.CreatedBy;
     CreatedAt      = entity.DateCreated;
     LastModifiedAt = entity.LastModifiedTime;
 }
Пример #29
0
        Task INicoCommentProvider.PostCommentAsync(string comment, bool is184, string color, string size, string position)
        {
            var elapsed     = DateTime.Now.AddHours(-9) - _vposBaseTime.Value;
            var ms          = elapsed.TotalMilliseconds;
            var vpos        = (long)Math.Round(ms / 10);
            var postComment = new PostComment(comment, vpos, is184, color, size, position);

            _metaProvider.Send(postComment);
            return(Task.CompletedTask);
        }
Пример #30
0
        public PartialViewResult Contact(ContactInfo model)
        {
            model.ReconstructSettings();
            this.ViewData[ContactInfo.Key] = model;
            model.IsSaved = false;

            LoadPage(model.Settings.Uri);

            var settings = model.Settings;

            if (settings.UseValidateHuman)
            {
                bool IsValidated = model.ValidateHuman.ValidateValue(model.ValidationValue);
                if (!IsValidated)
                {
                    ModelState.AddModelError("ValidationValue", model.ValidateHuman.AltValidationFailText);
                    model.ValidationValue = String.Empty;
                }
            }

            //TODO: log the comment and B64 encode some of the settings (TBD)
            if (ModelState.IsValid)
            {
                string sIP = Request.ServerVariables["REMOTE_ADDR"].ToString();

                PostComment pc = new PostComment();
                pc.ContentCommentID = Guid.NewGuid();
                pc.Root_ContentID   = _page.ThePage.Root_ContentID;
                pc.CreateDate       = SiteData.CurrentSite.Now;
                pc.IsApproved       = false;
                pc.IsSpam           = false;
                pc.CommenterIP      = sIP;
                pc.CommenterName    = Server.HtmlEncode(model.CommenterName);
                pc.CommenterEmail   = Server.HtmlEncode(model.CommenterEmail ?? String.Empty);
                pc.PostCommentText  = Server.HtmlEncode(model.PostCommentText);                //.Replace("<", "&lt;").Replace(">", "&gt;");
                pc.CommenterURL     = Server.HtmlEncode(model.CommenterURL ?? String.Empty);

                pc.Save();

                model.IsSaved = true;

                model.CommenterName   = String.Empty;
                model.CommenterEmail  = String.Empty;
                model.PostCommentText = String.Empty;
                model.CommenterURL    = String.Empty;
                model.ValidationValue = String.Empty;

                this.ViewData[ContactInfo.Key] = model;
                model.SendMail(pc, _page.ThePage);

                ModelState.Clear();
            }

            return(PartialView(settings.PostPartialName));
        }
        // GET api/Comment/5
        public PostComment GetPostComment(int id)
        {
            PostComment postcomment = db.PostComments.Find(id);

            if (postcomment == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return(postcomment);
        }
Пример #32
0
        public ActionResult edit_comment(FormCollection collection)
        {
            // Get the signed in user
            Administrator user = Administrator.GetSignedInAdministrator();

            // Check if the user is signed in
            if (user == null)
            {
                return RedirectToAction("login", "user");
            }

            // Get the current domain
            Domain domain = Tools.GetCurrentDomain();

            // Get the translated texts
            KeyStringList tt = StaticText.GetAll(domain.front_end_language, "id", "ASC");

            // Get form values
            Int32 commentId = Convert.ToInt32(collection["hiddenId"]);
            Int32 languageId = Convert.ToInt32(collection["hiddenLanguageId"]);
            string commentText = collection["txtCommentText"];

            // Modify the comment text
            commentText = commentText.Replace(Environment.NewLine, "<br />");

            // Get the comment
            PostComment comment = PostComment.GetOneById(commentId);

            // Get the post
            Post post = Post.GetOneById(comment.post_id, languageId);

            // Update the comment
            if(comment != null && comment.administrator_id == user.id)
            {
                // Update values
                comment.comment_date = DateTime.UtcNow;
                comment.comment_text = commentText;

                // Update the comment
                PostComment.Update(comment);

                // Send a email to the administrator of the website
                string subject = tt.Get("comment") + " - " + domain.website_name;
                string message = tt.Get("post") + ": " + comment.post_id.ToString() + "<br />"
                    + tt.Get("language") + ": " + comment.language_id.ToString() + "<br />"
                    + tt.Get("user_name") + ": " + user.admin_user_name + "<br /><br />" 
                    + comment.comment_text;
                Tools.SendEmailToHost("", subject, message);
            }

            // Redirect the user to the post
            return Redirect("/home/post/" + post.page_name + "#comments");

        } // End of the edit_comment method
Пример #33
0
        public IHttpActionResult GetPostComment(int id)
        {
            PostComment postComment = db.PostComments.Find(id);

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

            return(Ok(postComment));
        }
Пример #34
0
        internal void SetComment(PostComment c)
        {
            this.message = null;

            if (c != null)
            {
                this.title.Text = string.Empty;
                this.body.Text = c.Body;

                string person = (c.Author != null ? c.Author.ToString() : "Unknown");

                info.Text = string.Format("Posted on {0} at {1} by {2}", c.PostedOn.ToShortDateString(), c.PostedOn.ToLongTimeString(), person);
                info.Top = body.Bottom + 5;
            }
        }
Пример #35
0
 protected void Post_Click(object sender, EventArgs e)
 {
     PostComment pc = new PostComment();
     pc.ProjectID = Int32.Parse(Request.QueryString["prid"].ToString());
     pc.DateAdded = DateTime.Today;
     pc.Comment = TextBox1.Text;
     var query = from emp in db.Employees
                 where emp.Fname == Page.User.Identity.Name
                 select emp;
     pc.EmpId = query.First<Employee>().EmpId;
     if (CheckBox1.Checked)
         pc.IsPublic = 'Y';
     db.PostComments.InsertOnSubmit(pc);
     db.SubmitChanges();
     PopulatePage();
     TextBox1.Text = "";
 }
Пример #36
0
    } // End of the constructor

    #endregion

    #region Insert methods

    /// <summary>
    /// Add one post
    /// </summary>
    /// <param name="post">A reference to a post</param>
    public static long Add(PostComment post)
    {
        // Create the long to return
        long idOfInsert = 0;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "INSERT INTO dbo.posts_comments (post_id, administrator_id, language_id, comment_date, comment_text) "
            + "VALUES (@post_id, @administrator_id, @language_id, @comment_date, @comment_text);SELECT SCOPE_IDENTITY();";

        // The using block is used to call dispose automatically even if there are is a exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are is a exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@post_id", post.post_id);
                cmd.Parameters.AddWithValue("@administrator_id", post.administrator_id);
                cmd.Parameters.AddWithValue("@language_id", post.language_id);
                cmd.Parameters.AddWithValue("@comment_date", post.comment_date);
                cmd.Parameters.AddWithValue("@comment_text", post.comment_text);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection
                    cn.Open();

                    // Execute the insert
                    idOfInsert = Convert.ToInt64(cmd.ExecuteScalar());

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        // Return the id of the inserted item
        return idOfInsert;

    } // End of the Add method
Пример #37
0
 public ActionResult AddComment(int postId, PostComment comment)
 {
     var post = postService.GetPostById(CurrentBlog, postId);
     comment.Post = post;
     comment.Date = DateTime.Now;
     using (var tranScope = new TransactionScope())
     {
         try
         {
             postService.AddComment(comment);
             tranScope.Complete();
         }
         catch (ValidationException vex)
         {
             Transaction.Current.Rollback();
             ModelState.AddValidationExceptionToModel("comment", vex);
         }
     }
     return View("Read", post);
 }
Пример #38
0
 /// <summary>
 /// コンストラクタ
 /// </summary>
 public CommentRoomSentEventArgs(int roomIndex, string roomLabel,
                                 PostComment comment)
     : base(roomIndex, roomLabel)
 {
     IsError = false;
     Comment = comment;
 }
Пример #39
0
        /// <summary>
        /// コメント投稿成功時に送られます。
        /// </summary>
        private void OnSendCommentSuccess()
        {
            var tmpComment = this.sendingComment;

            using (new DebugLock(SyncRoot))
            {
                // 送信したメッセージをキューから削除します。
                RemoveMessage(this.sendingComment);

                this.postTryCount = 0;
                this.sendingComment = null;
            }

            // メッセージを削除した後に、イベントを呼びます。
            // LeaveCommentCountの数を調整するためです。
            this.commentClient.OnCommentSentRoom(
                this, tmpComment);
        }
Пример #40
0
        /// <summary>
        /// コメント送信時に呼ばれます。
        /// </summary>
        internal void OnCommentSentRoom(CommentRoom sender, PostComment comment)
        {
            this.CommentSent.SafeRaiseEvent(
                this,
                new CommentRoomSentEventArgs(
                    sender.Index, sender.RoomLabel, comment));

            // 未送信のコメント数が変わった可能性があります。
            this.RaisePropertyChanged("LeaveCommentCount");
        }
Пример #41
0
        /// <summary>
        /// コメント投稿失敗時に呼ばれます。
        /// </summary>
        private void OnSendCommentError(ChatResultStatus? status)
        {
            // もう一度投稿してみます。
            using (new DebugLock(SyncRoot))
            {
                Log.Error(this,
                    "chat_resultから失敗報告が来ました。(status={0}, Text={1})",
                    (status == null ? "不明" : status.ToString()),
                    (this.sendingComment == null ? "" : this.sendingComment.Text));

                // エラーコードによる個別のエラー処理を行います。
                switch (status)
                {
                    case ChatResultStatus.NormalError:
                        // 原因)
                        // ・同じ内容のコメントを投稿した
                        // ・連続アクセスエラー
                        // 対策)
                        // エラーカウントなどを使い次の投稿時にはコメントの内容を
                        // 変えるため、上の理由の場合は特にすることはありません。
                        // 連続アクセス時も、対応した長期休憩コードが別途あるため、
                        // 特になにもする必要がありません。
                        break;
                    case ChatResultStatus.Error2:
                        // 原因)
                        // ・分かりません><
                        break;
                    case ChatResultStatus.Error3:
                        // 原因)
                        // ・分かりません><
                        break;
                    case ChatResultStatus.PostKey:
                        // 原因)
                        // ・postkeyの値が不正。
                        // 対策)
                        // キャッシュされているpostkeyの値を初期化し、
                        // 次の投稿時には新しいpostkeyを取得するようにしています。
                        this.postKey = null;
                        break;
                    default:
                        break;
                }

                // コメントの投稿に3回以上連続で失敗した場合は、
                // アクセス多寡などの理由と判断し長い休憩時間を入れます。
                if (this.postTryCount > 2)
                {
                    AddPostMessageWait(AccessDeniedWaitTime);
                    this.postTryCount = 0;

                    // 送信に失敗したコメントも削除します。
                    RemoveMessage(this.sendingComment);
                }
                else
                {
                    this.postTryCount += 1;
                }

                // 投稿中のコメントをnullにし、新しいコメントを
                // 投稿出来るようにします。
                this.sendingComment = null;
            }
        }
Пример #42
0
        /// <summary>
        /// コメントの投稿が可能かどうか調べます。
        /// </summary>
        private bool CanSendComment(PostComment comment)
        {
            using (new DebugLock(SyncRoot))
            {
                var now = DateTime.Now;

                // 投稿可能時刻に達していない場合は、コメントは投稿できません。
                if (now < comment.StartDate)
                {
                    return false;
                }

                // 前回の投稿から規定時間以上経っていない場合は、エラーとなります。
                if (now - this.lastPostTime < this.waitForPostTime)
                {
                    return false;
                }

                return true;
            }
        }
 /// <summary>
 /// There are no comments for PostComment in the schema.
 /// </summary>
 public void AddToPostComment(PostComment postComment)
 {
     base.AddObject("PostComment", postComment);
 }
Пример #44
0
        /// <summary>
        /// メッセージをメッセージキューに追加します。
        /// </summary>
        private void EnqueueOwnerComment(PostComment comment)
        {
            if (comment == null)
            {
                return;
            }

            lock (this.ownerCommentList)
            {
                this.ownerCommentList.Add(comment);

                // 投稿可能時刻が早い順にソートします。
                // List.Sortは安定なソートでないためこうしています。
                this.ownerCommentList =
                    this.ownerCommentList.OrderBy(
                        cm => cm.StartDate).ToList();
            }
        }
        /// <summary>
        /// Log when someone responds to a partner call by public comment
        /// </summary>
        /// <param name="post"></param>
        /// <param name="postComment"></param>
        public void LogPartnerCallCommentReply(Post post, PostComment postComment)
        {
            //-- Can't reply to yourself.
            if (post.UserID != postComment.UserID)
            {
                var pc = pcRepo.GetByID(post.ID);

                var pcr = new PartnerCallReply() { ID = Guid.NewGuid(), Message = postComment.Message, PartnerCallID = post.ID,
                     TypeID = (byte)PartnerCallReplyType.Comment, Utc = DateTime.UtcNow, UserID = postComment.UserID };

                AddPartnerCallSubscriptionWorkItemReply(pc, pcr);
            }
        }
Пример #46
0
        /// <summary>
        /// メッセージをメッセージキューに追加します。
        /// </summary>
        private void AddMessage(PostComment comment)
        {
            if (comment == null)
            {
                return;
            }

            using (new DebugLock(SyncRoot))
            {
                this.postCommentList.Add(comment);

                // 投稿可能時刻が早い順にソートします。
                // List.Sortは安定なソートでないためこうしています。
                this.postCommentList =
                    this.postCommentList.OrderBy(
                        cm => cm.StartDate).ToList();
            }
        }
Пример #47
0
    } // End of the Add method

    #endregion

    #region Update methods

    /// <summary>
    /// Update a post
    /// </summary>
    /// <param name="post">A reference to a post</param>
    public static void Update(PostComment post)
    {
        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "UPDATE dbo.posts_comments SET post_id = @post_id, administrator_id = @administrator_id, "
            + "language_id = @language_id, comment_date = @comment_date, comment_text = @comment_text WHERE id = @id;";

        // The using block is used to call dispose automatically even if there is a exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there is a exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", post.id);
                cmd.Parameters.AddWithValue("@post_id", post.post_id);
                cmd.Parameters.AddWithValue("@administrator_id", post.administrator_id);
                cmd.Parameters.AddWithValue("@language_id", post.language_id);
                cmd.Parameters.AddWithValue("@comment_date", post.comment_date);
                cmd.Parameters.AddWithValue("@comment_text", post.comment_text);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Execute the update
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Update method
Пример #48
0
		public void RemoveComment(PostComment comment)
		{
			postRepository.DeleteComment(comment);
		}
Пример #49
0
        /// <summary>
        /// メッセージキューからメッセージを一つ削除します。
        /// </summary>
        private void RemoveMessage(PostComment comment)
        {
            using (new DebugLock(SyncRoot))
            {
                if (!this.postCommentList.Any())
                {
                    return;
                }

                this.postCommentList.Remove(comment);
            }
        }
Пример #50
0
        public void CanSaveAllEntities()
        {
            using (var session = factory.OpenSession())
            {
                using (var tran = session.BeginTransaction())
                {
                    var blog = new Blog();
                    var user = new User();
                    var post = new Post();
                    var tag = new Tag();
                    var postComment = new PostComment();

                    var configuration = new BlogConfiguration();
                    configuration.PageSize = 3;
                    configuration["osman"] = "mahmut";

                    user.UserName = "******";
                    user.Password = "******";
                    user.Email = "*****@*****.**";
                    user.Blogs.Add(blog);

                    blog.Configuration = configuration;
                    blog.Writers.Add(user);
                    blog.Title = "my blog";
                    blog.Name = "My Blog";
                    blog.Founder = user;
                    blog.Posts.Add(post);
                    blog.Host = "localhost";

                    post.Blog = blog;
                    post.Content = "hello";
                    post.Publisher = user;
                    post.DateCreated = DateTime.Now;
                    post.DatePublished = DateTime.Now.AddMinutes(3);
                    post.Title = "post title";
                    post.FriendlyTitle = post.Title.Replace(' ', '_').ToLower();
                    post.AddComment(postComment, null);

                    postComment.Post = post;
                    postComment.Date = DateTime.Now.AddMinutes(6);
                    postComment.Email = "*****@*****.**";
                    postComment.Name = "Some One";
                    postComment.Comment = "Some One wrote here!!";

                    tag.Name = "Tag";
                    tag.FriendlyName = "Tagged";
                    tag.Posts.Add(post);
                    post.Tags.Add(tag);

                    var blogVal = new BlogValidator();
                    blogVal.ValidateAndThrowException(blog);

                    var postVal = new PostValidator();
                    postVal.ValidateAndThrowException(post);

                    var postCommVal = new PostCommentValidator();
                    postCommVal.ValidateAndThrowException(postComment);

                    var userVal = new UserValidator();
                    userVal.ValidateAndThrowException(user);

                    var tagVal = new TagValidator();
                    tagVal.ValidateAndThrowException(tag);

                    session.Save(user);
                    session.Save(blog);
                    session.Save(post);
                    session.Save(postComment);
                    session.Save(tag);

                    tran.Commit();
                }
            }

            using (var session = factory.OpenSession())
            {
                var item = session.CreateCriteria(typeof (Blog)).UniqueResult<Blog>();
                var pageSize = item.Configuration.PageSize;
                Assert.That(pageSize, Is.EqualTo(3));
            }
        }
Пример #51
0
        /// <summary>
        /// もしメッセージがあれば、非同期のメッセージ送信処理を行います。
        /// </summary>
        public void UpdateSendComment()
        {
            try
            {
                XElement elem;
                byte[] sendData;

                using (new DebugLock(SyncRoot))
                {
                    if (!IsConnected || IsDisconnecting)
                    {
                        //Log.ErrorMessage(this,
                        //    "コネクションは切断されています。");
                        return;
                    }

                    // 投稿用コメントを取得します。
                    var comment = GetMessage();
                    if (comment == null || !CanSendComment(comment))
                    {
                        return;
                    }

                    // コメント送信中でかつ、対応するchat_resultが返って来ていない場合、
                    // そのコメントは無視します。
                    if (this.sendingComment != null)
                    {
                        Log.Error(this,
                            "対応するchar_resultが返って来ませんでした(Text = {0})",
                            this.sendingComment.Text);

                        // 次のメッセージを送ってしまいます。
                        this.sendingComment = null;
                    }

                    elem = BuildCommentString(comment);
                    sendData = Encoding.UTF8.GetBytes(elem.ToString() + "\0");

                    // コメントの投稿時刻などを設定します。
                    // エラー処理に必要になります。
                    this.lastPostText = elem.Value;
                    this.sendingComment = comment;

                    SetPostMessageWait(DateTime.Now, MinimumWaitTimeForPost);
                }

                // コメントの投稿処理を開始します。
                this.socket.BeginSend(
                    sendData, 0, sendData.Length,
                    SocketFlags.None,
                    SendCommentDone,
                    null);

                Log.Trace(this,
                    "メッセージの送信処理を開始しました。(Text = {0})",
                    elem.Value);
            }
            catch (Exception ex)
            {
                Log.ErrorException(this, ex,
                    "メッセージの非同期送信に失敗しました。");

                using (new DebugLock(SyncRoot))
                {
                    this.sendingComment = null;
                }
            }
        }
Пример #52
0
        /// <summary>
        /// 放送主コメントを送信します。
        /// </summary>
        public void SendOwnerComment(PostComment comment)
        {
            if (comment == null || !comment.Validate())
            {
                return;
            }

            lock (SyncRoot)
            {
                if (this.publishStatus == null)
                {
                    throw new NicoLiveException(LiveStatusCode.PermissionDenied);
                }
                
                if (string.IsNullOrEmpty(this.publishStatus.Stream.Token))
                {
                    Log.Error(this,
                        "tokenがないため放送主コメントを送ることができません。");

                    throw new NicoLiveException(LiveStatusCode.PermissionDenied);
                }

                // コメントを追加した後、コメント処理を行います。
                EnqueueOwnerComment(comment);

                // コメント投稿に時間がかかる場合があるため、
                // 送信処理は必ず別スレッド上で行うようにします。
                //UpdateOwnerComment();
            }
        }
Пример #53
0
        /// <summary>
        /// コメントを非同期で送信します。
        /// </summary>
        public void SendComment(string text, string mail, DateTime startTime)
        {
            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            var comment = new PostComment()
            {
                Text = text,
                Mail = mail,
                StartDate = startTime,
            };
            
            AddMessage(comment);

            // 別スレッド上で投稿します。
            //UpdateSendComment();
        }
 /// <summary>
 /// Create a new PostComment object.
 /// </summary>
 /// <param name="commentID">Initial value of CommentID.</param>
 /// <param name="commentRating">Initial value of CommentRating.</param>
 /// <param name="commentContent">Initial value of CommentContent.</param>
 /// <param name="commentDate">Initial value of CommentDate.</param>
 public static PostComment CreatePostComment(int commentID, int commentRating, string commentContent, global::System.DateTime commentDate)
 {
     PostComment postComment = new PostComment();
     postComment.CommentID = commentID;
     postComment.CommentRating = commentRating;
     postComment.CommentContent = commentContent;
     postComment.CommentDate = commentDate;
     return postComment;
 }
Пример #55
0
 public void RemoveComment_calls_underlyting_repository_to_delete()
 {
     var comment = new PostComment();
     postService.RemoveComment(comment);
     postRepository.AssertWasCalled(x => x.DeleteComment(comment));
 }
Пример #56
0
        /// <summary>
        /// コメント投稿用の文字列を作成します。
        /// </summary>
        private XElement BuildCommentString(PostComment comment)
        {
            var postkey = GetPostKey();
            if (string.IsNullOrEmpty(postkey))
            {
                Log.Error(this,
                    "postkeyの取得に失敗しました。");

                ClearMessage();
                AddPostMessageWait(TimeSpan.FromSeconds(5.0));
                return null;
            }

            var playerStatus = this.commentClient.PlayerStatus;

            // 前回と同じ内容のコメントは投稿できないので、必要に応じて
            // 0幅文字を追加しています。
            //
            // 0幅文字についてはここを参考にしました。
            // http://nicowiki.com/空白・特殊記号.html
            var text = comment.Text +
                ((this.lastPostText != null && this.lastPostText == comment.Text)
                ? "\u200E" : "");

            // エラー時は同じ内容のコメントを何度も投稿することがあり、
            // 同じコメントの連続投稿規則にひっかっかってしまう可能性があるため、
            // 投稿内容をエラー回数によって少し変えています。
            text += new string('\u200C', this.postTryCount);

            // vposには放送開始からの経過時間を10ms単位で設定します。
            var elapse = DateTime.Now - playerStatus.Stream.BaseTime;

            // 投稿するメッセージを作成します。
            var elem = new XElement("chat",
                new XAttribute("thread", this.ThreadId),
                new XAttribute("ticket", this.ticket),
                new XAttribute("vpos", (int)elapse.TotalMilliseconds / 10),
                new XAttribute("postkey", postkey),
                new XAttribute("user_id", playerStatus.User.UserId),
                new XAttribute("mail", comment.Mail),
                new XAttribute("premium", (playerStatus.User.IsPremium ? "1" : "0")),
                new XAttribute("locale", "jp"),
                text);

            return elem;
        }
Пример #57
0
 public void AddComment_calls_underlying_repository()
 {
     var postComment = new PostComment();
     postService.AddComment(postComment);
     postRepository.AssertWasCalled(x => x.SaveComment(postComment));
 }
Пример #58
0
        /// <summary>
        /// 何らかの理由で接続が切断されたときに呼ばれます。
        /// </summary>
        private void NotifyDisconnected(DisconnectReason reason)
        {
            using (new DebugLock(SyncRoot))
            {
                if (this.socket != null)
                {
                    this.socket.Close();
                    this.socket = null;
                }

                this.isDisconnecting = false;
                this.sendingComment = null;
                this.postKey = null;
                this.postTryCount = 0;
                this.receivedBuffer.SetLength(0);
                ClearMessage();
            }

            this.commentClient.OnDisconnectedRoom(this, reason);

            Log.Debug(this,
                "コメントルームから切断されました。(理由={0})",
                reason);
        }
Пример #59
0
    } // End of the MasterPostExists method

    /// <summary>
    /// Get one comment by id
    /// </summary>
    /// <param name="id">The id</param>
    /// <returns>A reference to a post</returns>
    public static PostComment GetOneById(Int32 id)
    {
        // Create the post to return
        PostComment post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "SELECT * FROM dbo.posts_comments WHERE id = @id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", id);

                // Create a MySqlDataReader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new PostComment(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                        reader.Close();
                }
            }
        }

        // Return the post
        return post;

    } // End of the GetOneById method
Пример #60
0
        /*/// <summary>
        /// 放送主コメントを送信します。
        /// </summary>
        public void SendOwnerComment(string text, string mail, DateTime sendTime)
        {
            var comment = new PostComment()
            {
                Text = text,
                Mail = mail,
                StartDate = sendTime,
            };

            SendOwnerComment(comment);
        }*/

        /// <summary>
        /// 放送主コメントを送信します。
        /// </summary>
        public void SendOwnerComment(string text, string mail, string name)
        {
            var comment = new PostComment()
            {
                Text = text,
                Mail = mail,
                Name = name,
                StartDate = DateTime.Now,
            };

            SendOwnerComment(comment);
        }